1 //===- MIRParser.cpp - MIR serialization format parser implementation -----===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the class that parses the optional LLVM IR and machine
10 // functions that are stored in MIR files.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/MIRParser/MIRParser.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/AsmParser/Parser.h"
20 #include "llvm/AsmParser/SlotMapping.h"
21 #include "llvm/CodeGen/GlobalISel/RegisterBank.h"
22 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
23 #include "llvm/CodeGen/MIRParser/MIParser.h"
24 #include "llvm/CodeGen/MIRYamlMapping.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/TargetFrameLowering.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DiagnosticInfo.h"
34 #include "llvm/IR/Instructions.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/ValueSymbolTable.h"
38 #include "llvm/Support/LineIterator.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/SMLoc.h"
41 #include "llvm/Support/SourceMgr.h"
42 #include "llvm/Support/YAMLTraits.h"
43 #include "llvm/Target/TargetMachine.h"
50 /// This class implements the parsing of LLVM IR that's embedded inside a MIR
58 std::unique_ptr
<PerTargetMIParsingState
> Target
;
60 /// True when the MIR file doesn't have LLVM IR. Dummy IR functions are
61 /// created and inserted into the given module when this is true.
62 bool NoLLVMIR
= false;
63 /// True when a well formed MIR file does not contain any MIR/machine function
65 bool NoMIRDocuments
= false;
67 std::function
<void(Function
&)> ProcessIRFunction
;
70 MIRParserImpl(std::unique_ptr
<MemoryBuffer
> Contents
, StringRef Filename
,
72 std::function
<void(Function
&)> ProcessIRFunction
);
74 void reportDiagnostic(const SMDiagnostic
&Diag
);
76 /// Report an error with the given message at unknown location.
78 /// Always returns true.
79 bool error(const Twine
&Message
);
81 /// Report an error with the given message at the given location.
83 /// Always returns true.
84 bool error(SMLoc Loc
, const Twine
&Message
);
86 /// Report a given error with the location translated from the location in an
87 /// embedded string literal to a location in the MIR file.
89 /// Always returns true.
90 bool error(const SMDiagnostic
&Error
, SMRange SourceRange
);
92 /// Try to parse the optional LLVM module and the machine functions in the MIR
95 /// Return null if an error occurred.
96 std::unique_ptr
<Module
>
97 parseIRModule(DataLayoutCallbackTy DataLayoutCallback
);
99 /// Create an empty function with the given name.
100 Function
*createDummyFunction(StringRef Name
, Module
&M
);
102 bool parseMachineFunctions(Module
&M
, MachineModuleInfo
&MMI
);
104 /// Parse the machine function in the current YAML document.
107 /// Return true if an error occurred.
108 bool parseMachineFunction(Module
&M
, MachineModuleInfo
&MMI
);
110 /// Initialize the machine function to the state that's described in the MIR
113 /// Return true if error occurred.
114 bool initializeMachineFunction(const yaml::MachineFunction
&YamlMF
,
115 MachineFunction
&MF
);
117 bool parseRegisterInfo(PerFunctionMIParsingState
&PFS
,
118 const yaml::MachineFunction
&YamlMF
);
120 bool setupRegisterInfo(const PerFunctionMIParsingState
&PFS
,
121 const yaml::MachineFunction
&YamlMF
);
123 bool initializeFrameInfo(PerFunctionMIParsingState
&PFS
,
124 const yaml::MachineFunction
&YamlMF
);
126 bool initializeCallSiteInfo(PerFunctionMIParsingState
&PFS
,
127 const yaml::MachineFunction
&YamlMF
);
129 bool parseCalleeSavedRegister(PerFunctionMIParsingState
&PFS
,
130 std::vector
<CalleeSavedInfo
> &CSIInfo
,
131 const yaml::StringValue
&RegisterSource
,
132 bool IsRestored
, int FrameIdx
);
134 template <typename T
>
135 bool parseStackObjectsDebugInfo(PerFunctionMIParsingState
&PFS
,
139 bool initializeConstantPool(PerFunctionMIParsingState
&PFS
,
140 MachineConstantPool
&ConstantPool
,
141 const yaml::MachineFunction
&YamlMF
);
143 bool initializeJumpTableInfo(PerFunctionMIParsingState
&PFS
,
144 const yaml::MachineJumpTable
&YamlJTI
);
146 bool parseMachineMetadataNodes(PerFunctionMIParsingState
&PFS
,
148 const yaml::MachineFunction
&YMF
);
151 bool parseMDNode(PerFunctionMIParsingState
&PFS
, MDNode
*&Node
,
152 const yaml::StringValue
&Source
);
154 bool parseMBBReference(PerFunctionMIParsingState
&PFS
,
155 MachineBasicBlock
*&MBB
,
156 const yaml::StringValue
&Source
);
158 bool parseMachineMetadata(PerFunctionMIParsingState
&PFS
,
159 const yaml::StringValue
&Source
);
161 /// Return a MIR diagnostic converted from an MI string diagnostic.
162 SMDiagnostic
diagFromMIStringDiag(const SMDiagnostic
&Error
,
163 SMRange SourceRange
);
165 /// Return a MIR diagnostic converted from a diagnostic located in a YAML
166 /// block scalar string.
167 SMDiagnostic
diagFromBlockStringDiag(const SMDiagnostic
&Error
,
168 SMRange SourceRange
);
170 void computeFunctionProperties(MachineFunction
&MF
);
172 void setupDebugValueTracking(MachineFunction
&MF
,
173 PerFunctionMIParsingState
&PFS
, const yaml::MachineFunction
&YamlMF
);
176 } // end namespace llvm
178 static void handleYAMLDiag(const SMDiagnostic
&Diag
, void *Context
) {
179 reinterpret_cast<MIRParserImpl
*>(Context
)->reportDiagnostic(Diag
);
182 MIRParserImpl::MIRParserImpl(std::unique_ptr
<MemoryBuffer
> Contents
,
183 StringRef Filename
, LLVMContext
&Context
,
184 std::function
<void(Function
&)> Callback
)
187 In(SM
.getMemoryBuffer(SM
.AddNewSourceBuffer(std::move(Contents
), SMLoc()))
189 nullptr, handleYAMLDiag
, this),
190 Filename(Filename
), ProcessIRFunction(Callback
) {
194 bool MIRParserImpl::error(const Twine
&Message
) {
195 Context
.diagnose(DiagnosticInfoMIRParser(
196 DS_Error
, SMDiagnostic(Filename
, SourceMgr::DK_Error
, Message
.str())));
200 bool MIRParserImpl::error(SMLoc Loc
, const Twine
&Message
) {
201 Context
.diagnose(DiagnosticInfoMIRParser(
202 DS_Error
, SM
.GetMessage(Loc
, SourceMgr::DK_Error
, Message
)));
206 bool MIRParserImpl::error(const SMDiagnostic
&Error
, SMRange SourceRange
) {
207 assert(Error
.getKind() == SourceMgr::DK_Error
&& "Expected an error");
208 reportDiagnostic(diagFromMIStringDiag(Error
, SourceRange
));
212 void MIRParserImpl::reportDiagnostic(const SMDiagnostic
&Diag
) {
213 DiagnosticSeverity Kind
;
214 switch (Diag
.getKind()) {
215 case SourceMgr::DK_Error
:
218 case SourceMgr::DK_Warning
:
221 case SourceMgr::DK_Note
:
224 case SourceMgr::DK_Remark
:
225 llvm_unreachable("remark unexpected");
228 Context
.diagnose(DiagnosticInfoMIRParser(Kind
, Diag
));
231 std::unique_ptr
<Module
>
232 MIRParserImpl::parseIRModule(DataLayoutCallbackTy DataLayoutCallback
) {
233 if (!In
.setCurrentDocument()) {
236 // Create an empty module when the MIR file is empty.
237 NoMIRDocuments
= true;
238 auto M
= std::make_unique
<Module
>(Filename
, Context
);
239 if (auto LayoutOverride
= DataLayoutCallback(M
->getTargetTriple()))
240 M
->setDataLayout(*LayoutOverride
);
244 std::unique_ptr
<Module
> M
;
245 // Parse the block scalar manually so that we can return unique pointer
246 // without having to go trough YAML traits.
247 if (const auto *BSN
=
248 dyn_cast_or_null
<yaml::BlockScalarNode
>(In
.getCurrentNode())) {
250 M
= parseAssembly(MemoryBufferRef(BSN
->getValue(), Filename
), Error
,
251 Context
, &IRSlots
, DataLayoutCallback
);
253 reportDiagnostic(diagFromBlockStringDiag(Error
, BSN
->getSourceRange()));
257 if (!In
.setCurrentDocument())
258 NoMIRDocuments
= true;
260 // Create an new, empty module.
261 M
= std::make_unique
<Module
>(Filename
, Context
);
262 if (auto LayoutOverride
= DataLayoutCallback(M
->getTargetTriple()))
263 M
->setDataLayout(*LayoutOverride
);
269 bool MIRParserImpl::parseMachineFunctions(Module
&M
, MachineModuleInfo
&MMI
) {
273 // Parse the machine functions.
275 if (parseMachineFunction(M
, MMI
))
278 } while (In
.setCurrentDocument());
283 Function
*MIRParserImpl::createDummyFunction(StringRef Name
, Module
&M
) {
284 auto &Context
= M
.getContext();
286 Function::Create(FunctionType::get(Type::getVoidTy(Context
), false),
287 Function::ExternalLinkage
, Name
, M
);
288 BasicBlock
*BB
= BasicBlock::Create(Context
, "entry", F
);
289 new UnreachableInst(Context
, BB
);
291 if (ProcessIRFunction
)
292 ProcessIRFunction(*F
);
297 bool MIRParserImpl::parseMachineFunction(Module
&M
, MachineModuleInfo
&MMI
) {
299 yaml::MachineFunction YamlMF
;
300 yaml::EmptyContext Ctx
;
302 const LLVMTargetMachine
&TM
= MMI
.getTarget();
303 YamlMF
.MachineFuncInfo
= std::unique_ptr
<yaml::MachineFunctionInfo
>(
304 TM
.createDefaultFuncInfoYAML());
306 yaml::yamlize(In
, YamlMF
, false, Ctx
);
310 // Search for the corresponding IR function.
311 StringRef FunctionName
= YamlMF
.Name
;
312 Function
*F
= M
.getFunction(FunctionName
);
315 F
= createDummyFunction(FunctionName
, M
);
317 return error(Twine("function '") + FunctionName
+
318 "' isn't defined in the provided LLVM IR");
321 if (MMI
.getMachineFunction(*F
) != nullptr)
322 return error(Twine("redefinition of machine function '") + FunctionName
+
325 // Create the MachineFunction.
326 MachineFunction
&MF
= MMI
.getOrCreateMachineFunction(*F
);
327 if (initializeMachineFunction(YamlMF
, MF
))
333 static bool isSSA(const MachineFunction
&MF
) {
334 const MachineRegisterInfo
&MRI
= MF
.getRegInfo();
335 for (unsigned I
= 0, E
= MRI
.getNumVirtRegs(); I
!= E
; ++I
) {
336 Register Reg
= Register::index2VirtReg(I
);
337 if (!MRI
.hasOneDef(Reg
) && !MRI
.def_empty(Reg
))
340 // Subregister defs are invalid in SSA.
341 const MachineOperand
*RegDef
= MRI
.getOneDef(Reg
);
342 if (RegDef
&& RegDef
->getSubReg() != 0)
348 void MIRParserImpl::computeFunctionProperties(MachineFunction
&MF
) {
349 MachineFunctionProperties
&Properties
= MF
.getProperties();
352 bool HasInlineAsm
= false;
353 for (const MachineBasicBlock
&MBB
: MF
) {
354 for (const MachineInstr
&MI
: MBB
) {
357 if (MI
.isInlineAsm())
362 Properties
.set(MachineFunctionProperties::Property::NoPHIs
);
363 MF
.setHasInlineAsm(HasInlineAsm
);
366 Properties
.set(MachineFunctionProperties::Property::IsSSA
);
368 Properties
.reset(MachineFunctionProperties::Property::IsSSA
);
370 const MachineRegisterInfo
&MRI
= MF
.getRegInfo();
371 if (MRI
.getNumVirtRegs() == 0)
372 Properties
.set(MachineFunctionProperties::Property::NoVRegs
);
375 bool MIRParserImpl::initializeCallSiteInfo(
376 PerFunctionMIParsingState
&PFS
, const yaml::MachineFunction
&YamlMF
) {
377 MachineFunction
&MF
= PFS
.MF
;
379 const LLVMTargetMachine
&TM
= MF
.getTarget();
380 for (auto YamlCSInfo
: YamlMF
.CallSitesInfo
) {
381 yaml::CallSiteInfo::MachineInstrLoc MILoc
= YamlCSInfo
.CallLocation
;
382 if (MILoc
.BlockNum
>= MF
.size())
383 return error(Twine(MF
.getName()) +
384 Twine(" call instruction block out of range.") +
385 " Unable to reference bb:" + Twine(MILoc
.BlockNum
));
386 auto CallB
= std::next(MF
.begin(), MILoc
.BlockNum
);
387 if (MILoc
.Offset
>= CallB
->size())
388 return error(Twine(MF
.getName()) +
389 Twine(" call instruction offset out of range.") +
390 " Unable to reference instruction at bb: " +
391 Twine(MILoc
.BlockNum
) + " at offset:" + Twine(MILoc
.Offset
));
392 auto CallI
= std::next(CallB
->instr_begin(), MILoc
.Offset
);
393 if (!CallI
->isCall(MachineInstr::IgnoreBundle
))
394 return error(Twine(MF
.getName()) +
395 Twine(" call site info should reference call "
396 "instruction. Instruction at bb:") +
397 Twine(MILoc
.BlockNum
) + " at offset:" + Twine(MILoc
.Offset
) +
398 " is not a call instruction");
399 MachineFunction::CallSiteInfo CSInfo
;
400 for (auto ArgRegPair
: YamlCSInfo
.ArgForwardingRegs
) {
402 if (parseNamedRegisterReference(PFS
, Reg
, ArgRegPair
.Reg
.Value
, Error
))
403 return error(Error
, ArgRegPair
.Reg
.SourceRange
);
404 CSInfo
.emplace_back(Reg
, ArgRegPair
.ArgNo
);
407 if (TM
.Options
.EmitCallSiteInfo
)
408 MF
.addCallArgsForwardingRegs(&*CallI
, std::move(CSInfo
));
411 if (YamlMF
.CallSitesInfo
.size() && !TM
.Options
.EmitCallSiteInfo
)
412 return error(Twine("Call site info provided but not used"));
416 void MIRParserImpl::setupDebugValueTracking(
417 MachineFunction
&MF
, PerFunctionMIParsingState
&PFS
,
418 const yaml::MachineFunction
&YamlMF
) {
419 // Compute the value of the "next instruction number" field.
420 unsigned MaxInstrNum
= 0;
423 MaxInstrNum
= std::max((unsigned)MI
.peekDebugInstrNum(), MaxInstrNum
);
424 MF
.setDebugInstrNumberingCount(MaxInstrNum
);
426 // Load any substitutions.
427 for (auto &Sub
: YamlMF
.DebugValueSubstitutions
) {
428 MF
.makeDebugValueSubstitution({Sub
.SrcInst
, Sub
.SrcOp
},
429 {Sub
.DstInst
, Sub
.DstOp
}, Sub
.Subreg
);
434 MIRParserImpl::initializeMachineFunction(const yaml::MachineFunction
&YamlMF
,
435 MachineFunction
&MF
) {
436 // TODO: Recreate the machine function.
438 // Avoid clearing state if we're using the same subtarget again.
439 Target
->setTarget(MF
.getSubtarget());
441 Target
.reset(new PerTargetMIParsingState(MF
.getSubtarget()));
444 MF
.setAlignment(YamlMF
.Alignment
.valueOrOne());
445 MF
.setExposesReturnsTwice(YamlMF
.ExposesReturnsTwice
);
446 MF
.setHasWinCFI(YamlMF
.HasWinCFI
);
448 if (YamlMF
.Legalized
)
449 MF
.getProperties().set(MachineFunctionProperties::Property::Legalized
);
450 if (YamlMF
.RegBankSelected
)
451 MF
.getProperties().set(
452 MachineFunctionProperties::Property::RegBankSelected
);
454 MF
.getProperties().set(MachineFunctionProperties::Property::Selected
);
455 if (YamlMF
.FailedISel
)
456 MF
.getProperties().set(MachineFunctionProperties::Property::FailedISel
);
458 PerFunctionMIParsingState
PFS(MF
, SM
, IRSlots
, *Target
);
459 if (parseRegisterInfo(PFS
, YamlMF
))
461 if (!YamlMF
.Constants
.empty()) {
462 auto *ConstantPool
= MF
.getConstantPool();
463 assert(ConstantPool
&& "Constant pool must be created");
464 if (initializeConstantPool(PFS
, *ConstantPool
, YamlMF
))
467 if (!YamlMF
.MachineMetadataNodes
.empty() &&
468 parseMachineMetadataNodes(PFS
, MF
, YamlMF
))
471 StringRef BlockStr
= YamlMF
.Body
.Value
.Value
;
474 BlockSM
.AddNewSourceBuffer(
475 MemoryBuffer::getMemBuffer(BlockStr
, "",/*RequiresNullTerminator=*/false),
478 if (parseMachineBasicBlockDefinitions(PFS
, BlockStr
, Error
)) {
480 diagFromBlockStringDiag(Error
, YamlMF
.Body
.Value
.SourceRange
));
483 // Check Basic Block Section Flags.
484 if (MF
.getTarget().getBBSectionsType() == BasicBlockSection::Labels
) {
485 MF
.setBBSectionsType(BasicBlockSection::Labels
);
486 } else if (MF
.hasBBSections()) {
487 MF
.assignBeginEndSections();
491 // Initialize the frame information after creating all the MBBs so that the
492 // MBB references in the frame information can be resolved.
493 if (initializeFrameInfo(PFS
, YamlMF
))
495 // Initialize the jump table after creating all the MBBs so that the MBB
496 // references can be resolved.
497 if (!YamlMF
.JumpTableInfo
.Entries
.empty() &&
498 initializeJumpTableInfo(PFS
, YamlMF
.JumpTableInfo
))
500 // Parse the machine instructions after creating all of the MBBs so that the
501 // parser can resolve the MBB references.
502 StringRef InsnStr
= YamlMF
.Body
.Value
.Value
;
504 InsnSM
.AddNewSourceBuffer(
505 MemoryBuffer::getMemBuffer(InsnStr
, "", /*RequiresNullTerminator=*/false),
508 if (parseMachineInstructions(PFS
, InsnStr
, Error
)) {
510 diagFromBlockStringDiag(Error
, YamlMF
.Body
.Value
.SourceRange
));
515 if (setupRegisterInfo(PFS
, YamlMF
))
518 if (YamlMF
.MachineFuncInfo
) {
519 const LLVMTargetMachine
&TM
= MF
.getTarget();
520 // Note this is called after the initial constructor of the
521 // MachineFunctionInfo based on the MachineFunction, which may depend on the
525 if (TM
.parseMachineFunctionInfo(*YamlMF
.MachineFuncInfo
, PFS
, Error
,
527 return error(Error
, SrcRange
);
531 // Set the reserved registers after parsing MachineFuncInfo. The target may
532 // have been recording information used to select the reserved registers
534 // FIXME: This is a temporary workaround until the reserved registers can be
536 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
537 MRI
.freezeReservedRegs(MF
);
539 computeFunctionProperties(MF
);
541 if (initializeCallSiteInfo(PFS
, YamlMF
))
544 setupDebugValueTracking(MF
, PFS
, YamlMF
);
546 MF
.getSubtarget().mirFileLoaded(MF
);
552 bool MIRParserImpl::parseRegisterInfo(PerFunctionMIParsingState
&PFS
,
553 const yaml::MachineFunction
&YamlMF
) {
554 MachineFunction
&MF
= PFS
.MF
;
555 MachineRegisterInfo
&RegInfo
= MF
.getRegInfo();
556 assert(RegInfo
.tracksLiveness());
557 if (!YamlMF
.TracksRegLiveness
)
558 RegInfo
.invalidateLiveness();
561 // Parse the virtual register information.
562 for (const auto &VReg
: YamlMF
.VirtualRegisters
) {
563 VRegInfo
&Info
= PFS
.getVRegInfo(VReg
.ID
.Value
);
565 return error(VReg
.ID
.SourceRange
.Start
,
566 Twine("redefinition of virtual register '%") +
567 Twine(VReg
.ID
.Value
) + "'");
568 Info
.Explicit
= true;
570 if (StringRef(VReg
.Class
.Value
).equals("_")) {
571 Info
.Kind
= VRegInfo::GENERIC
;
572 Info
.D
.RegBank
= nullptr;
574 const auto *RC
= Target
->getRegClass(VReg
.Class
.Value
);
576 Info
.Kind
= VRegInfo::NORMAL
;
579 const RegisterBank
*RegBank
= Target
->getRegBank(VReg
.Class
.Value
);
582 VReg
.Class
.SourceRange
.Start
,
583 Twine("use of undefined register class or register bank '") +
584 VReg
.Class
.Value
+ "'");
585 Info
.Kind
= VRegInfo::REGBANK
;
586 Info
.D
.RegBank
= RegBank
;
590 if (!VReg
.PreferredRegister
.Value
.empty()) {
591 if (Info
.Kind
!= VRegInfo::NORMAL
)
592 return error(VReg
.Class
.SourceRange
.Start
,
593 Twine("preferred register can only be set for normal vregs"));
595 if (parseRegisterReference(PFS
, Info
.PreferredReg
,
596 VReg
.PreferredRegister
.Value
, Error
))
597 return error(Error
, VReg
.PreferredRegister
.SourceRange
);
601 // Parse the liveins.
602 for (const auto &LiveIn
: YamlMF
.LiveIns
) {
604 if (parseNamedRegisterReference(PFS
, Reg
, LiveIn
.Register
.Value
, Error
))
605 return error(Error
, LiveIn
.Register
.SourceRange
);
607 if (!LiveIn
.VirtualRegister
.Value
.empty()) {
609 if (parseVirtualRegisterReference(PFS
, Info
, LiveIn
.VirtualRegister
.Value
,
611 return error(Error
, LiveIn
.VirtualRegister
.SourceRange
);
614 RegInfo
.addLiveIn(Reg
, VReg
);
617 // Parse the callee saved registers (Registers that will
618 // be saved for the caller).
619 if (YamlMF
.CalleeSavedRegisters
) {
620 SmallVector
<MCPhysReg
, 16> CalleeSavedRegisters
;
621 for (const auto &RegSource
: YamlMF
.CalleeSavedRegisters
.getValue()) {
623 if (parseNamedRegisterReference(PFS
, Reg
, RegSource
.Value
, Error
))
624 return error(Error
, RegSource
.SourceRange
);
625 CalleeSavedRegisters
.push_back(Reg
);
627 RegInfo
.setCalleeSavedRegs(CalleeSavedRegisters
);
633 bool MIRParserImpl::setupRegisterInfo(const PerFunctionMIParsingState
&PFS
,
634 const yaml::MachineFunction
&YamlMF
) {
635 MachineFunction
&MF
= PFS
.MF
;
636 MachineRegisterInfo
&MRI
= MF
.getRegInfo();
639 auto populateVRegInfo
= [&] (const VRegInfo
&Info
, Twine Name
) {
640 Register Reg
= Info
.VReg
;
642 case VRegInfo::UNKNOWN
:
643 error(Twine("Cannot determine class/bank of virtual register ") +
644 Name
+ " in function '" + MF
.getName() + "'");
647 case VRegInfo::NORMAL
:
648 MRI
.setRegClass(Reg
, Info
.D
.RC
);
649 if (Info
.PreferredReg
!= 0)
650 MRI
.setSimpleHint(Reg
, Info
.PreferredReg
);
652 case VRegInfo::GENERIC
:
654 case VRegInfo::REGBANK
:
655 MRI
.setRegBank(Reg
, *Info
.D
.RegBank
);
660 for (const auto &P
: PFS
.VRegInfosNamed
) {
661 const VRegInfo
&Info
= *P
.second
;
662 populateVRegInfo(Info
, Twine(P
.first()));
665 for (auto P
: PFS
.VRegInfos
) {
666 const VRegInfo
&Info
= *P
.second
;
667 populateVRegInfo(Info
, Twine(P
.first
));
670 // Compute MachineRegisterInfo::UsedPhysRegMask
671 for (const MachineBasicBlock
&MBB
: MF
) {
672 // Make sure MRI knows about registers clobbered by unwinder.
673 const TargetRegisterInfo
*TRI
= MF
.getSubtarget().getRegisterInfo();
675 if (auto *RegMask
= TRI
->getCustomEHPadPreservedMask(MF
))
676 MRI
.addPhysRegsUsedFromRegMask(RegMask
);
678 for (const MachineInstr
&MI
: MBB
) {
679 for (const MachineOperand
&MO
: MI
.operands()) {
682 MRI
.addPhysRegsUsedFromRegMask(MO
.getRegMask());
690 bool MIRParserImpl::initializeFrameInfo(PerFunctionMIParsingState
&PFS
,
691 const yaml::MachineFunction
&YamlMF
) {
692 MachineFunction
&MF
= PFS
.MF
;
693 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
694 const TargetFrameLowering
*TFI
= MF
.getSubtarget().getFrameLowering();
695 const Function
&F
= MF
.getFunction();
696 const yaml::MachineFrameInfo
&YamlMFI
= YamlMF
.FrameInfo
;
697 MFI
.setFrameAddressIsTaken(YamlMFI
.IsFrameAddressTaken
);
698 MFI
.setReturnAddressIsTaken(YamlMFI
.IsReturnAddressTaken
);
699 MFI
.setHasStackMap(YamlMFI
.HasStackMap
);
700 MFI
.setHasPatchPoint(YamlMFI
.HasPatchPoint
);
701 MFI
.setStackSize(YamlMFI
.StackSize
);
702 MFI
.setOffsetAdjustment(YamlMFI
.OffsetAdjustment
);
703 if (YamlMFI
.MaxAlignment
)
704 MFI
.ensureMaxAlignment(Align(YamlMFI
.MaxAlignment
));
705 MFI
.setAdjustsStack(YamlMFI
.AdjustsStack
);
706 MFI
.setHasCalls(YamlMFI
.HasCalls
);
707 if (YamlMFI
.MaxCallFrameSize
!= ~0u)
708 MFI
.setMaxCallFrameSize(YamlMFI
.MaxCallFrameSize
);
709 MFI
.setCVBytesOfCalleeSavedRegisters(YamlMFI
.CVBytesOfCalleeSavedRegisters
);
710 MFI
.setHasOpaqueSPAdjustment(YamlMFI
.HasOpaqueSPAdjustment
);
711 MFI
.setHasVAStart(YamlMFI
.HasVAStart
);
712 MFI
.setHasMustTailInVarArgFunc(YamlMFI
.HasMustTailInVarArgFunc
);
713 MFI
.setHasTailCall(YamlMFI
.HasTailCall
);
714 MFI
.setLocalFrameSize(YamlMFI
.LocalFrameSize
);
715 if (!YamlMFI
.SavePoint
.Value
.empty()) {
716 MachineBasicBlock
*MBB
= nullptr;
717 if (parseMBBReference(PFS
, MBB
, YamlMFI
.SavePoint
))
719 MFI
.setSavePoint(MBB
);
721 if (!YamlMFI
.RestorePoint
.Value
.empty()) {
722 MachineBasicBlock
*MBB
= nullptr;
723 if (parseMBBReference(PFS
, MBB
, YamlMFI
.RestorePoint
))
725 MFI
.setRestorePoint(MBB
);
728 std::vector
<CalleeSavedInfo
> CSIInfo
;
729 // Initialize the fixed frame objects.
730 for (const auto &Object
: YamlMF
.FixedStackObjects
) {
732 if (Object
.Type
!= yaml::FixedMachineStackObject::SpillSlot
)
733 ObjectIdx
= MFI
.CreateFixedObject(Object
.Size
, Object
.Offset
,
734 Object
.IsImmutable
, Object
.IsAliased
);
736 ObjectIdx
= MFI
.CreateFixedSpillStackObject(Object
.Size
, Object
.Offset
);
738 if (!TFI
->isSupportedStackID(Object
.StackID
))
739 return error(Object
.ID
.SourceRange
.Start
,
740 Twine("StackID is not supported by target"));
741 MFI
.setStackID(ObjectIdx
, Object
.StackID
);
742 MFI
.setObjectAlignment(ObjectIdx
, Object
.Alignment
.valueOrOne());
743 if (!PFS
.FixedStackObjectSlots
.insert(std::make_pair(Object
.ID
.Value
,
746 return error(Object
.ID
.SourceRange
.Start
,
747 Twine("redefinition of fixed stack object '%fixed-stack.") +
748 Twine(Object
.ID
.Value
) + "'");
749 if (parseCalleeSavedRegister(PFS
, CSIInfo
, Object
.CalleeSavedRegister
,
750 Object
.CalleeSavedRestored
, ObjectIdx
))
752 if (parseStackObjectsDebugInfo(PFS
, Object
, ObjectIdx
))
756 // Initialize the ordinary frame objects.
757 for (const auto &Object
: YamlMF
.StackObjects
) {
759 const AllocaInst
*Alloca
= nullptr;
760 const yaml::StringValue
&Name
= Object
.Name
;
761 if (!Name
.Value
.empty()) {
762 Alloca
= dyn_cast_or_null
<AllocaInst
>(
763 F
.getValueSymbolTable()->lookup(Name
.Value
));
765 return error(Name
.SourceRange
.Start
,
766 "alloca instruction named '" + Name
.Value
+
767 "' isn't defined in the function '" + F
.getName() +
770 if (!TFI
->isSupportedStackID(Object
.StackID
))
771 return error(Object
.ID
.SourceRange
.Start
,
772 Twine("StackID is not supported by target"));
773 if (Object
.Type
== yaml::MachineStackObject::VariableSized
)
775 MFI
.CreateVariableSizedObject(Object
.Alignment
.valueOrOne(), Alloca
);
777 ObjectIdx
= MFI
.CreateStackObject(
778 Object
.Size
, Object
.Alignment
.valueOrOne(),
779 Object
.Type
== yaml::MachineStackObject::SpillSlot
, Alloca
,
781 MFI
.setObjectOffset(ObjectIdx
, Object
.Offset
);
783 if (!PFS
.StackObjectSlots
.insert(std::make_pair(Object
.ID
.Value
, ObjectIdx
))
785 return error(Object
.ID
.SourceRange
.Start
,
786 Twine("redefinition of stack object '%stack.") +
787 Twine(Object
.ID
.Value
) + "'");
788 if (parseCalleeSavedRegister(PFS
, CSIInfo
, Object
.CalleeSavedRegister
,
789 Object
.CalleeSavedRestored
, ObjectIdx
))
791 if (Object
.LocalOffset
)
792 MFI
.mapLocalFrameObject(ObjectIdx
, Object
.LocalOffset
.getValue());
793 if (parseStackObjectsDebugInfo(PFS
, Object
, ObjectIdx
))
796 MFI
.setCalleeSavedInfo(CSIInfo
);
797 if (!CSIInfo
.empty())
798 MFI
.setCalleeSavedInfoValid(true);
800 // Initialize the various stack object references after initializing the
802 if (!YamlMFI
.StackProtector
.Value
.empty()) {
805 if (parseStackObjectReference(PFS
, FI
, YamlMFI
.StackProtector
.Value
, Error
))
806 return error(Error
, YamlMFI
.StackProtector
.SourceRange
);
807 MFI
.setStackProtectorIndex(FI
);
812 bool MIRParserImpl::parseCalleeSavedRegister(PerFunctionMIParsingState
&PFS
,
813 std::vector
<CalleeSavedInfo
> &CSIInfo
,
814 const yaml::StringValue
&RegisterSource
, bool IsRestored
, int FrameIdx
) {
815 if (RegisterSource
.Value
.empty())
819 if (parseNamedRegisterReference(PFS
, Reg
, RegisterSource
.Value
, Error
))
820 return error(Error
, RegisterSource
.SourceRange
);
821 CalleeSavedInfo
CSI(Reg
, FrameIdx
);
822 CSI
.setRestored(IsRestored
);
823 CSIInfo
.push_back(CSI
);
827 /// Verify that given node is of a certain type. Return true on error.
828 template <typename T
>
829 static bool typecheckMDNode(T
*&Result
, MDNode
*Node
,
830 const yaml::StringValue
&Source
,
831 StringRef TypeString
, MIRParserImpl
&Parser
) {
834 Result
= dyn_cast
<T
>(Node
);
836 return Parser
.error(Source
.SourceRange
.Start
,
837 "expected a reference to a '" + TypeString
+
842 template <typename T
>
843 bool MIRParserImpl::parseStackObjectsDebugInfo(PerFunctionMIParsingState
&PFS
,
844 const T
&Object
, int FrameIdx
) {
845 // Debug information can only be attached to stack objects; Fixed stack
846 // objects aren't supported.
847 MDNode
*Var
= nullptr, *Expr
= nullptr, *Loc
= nullptr;
848 if (parseMDNode(PFS
, Var
, Object
.DebugVar
) ||
849 parseMDNode(PFS
, Expr
, Object
.DebugExpr
) ||
850 parseMDNode(PFS
, Loc
, Object
.DebugLoc
))
852 if (!Var
&& !Expr
&& !Loc
)
854 DILocalVariable
*DIVar
= nullptr;
855 DIExpression
*DIExpr
= nullptr;
856 DILocation
*DILoc
= nullptr;
857 if (typecheckMDNode(DIVar
, Var
, Object
.DebugVar
, "DILocalVariable", *this) ||
858 typecheckMDNode(DIExpr
, Expr
, Object
.DebugExpr
, "DIExpression", *this) ||
859 typecheckMDNode(DILoc
, Loc
, Object
.DebugLoc
, "DILocation", *this))
861 PFS
.MF
.setVariableDbgInfo(DIVar
, DIExpr
, FrameIdx
, DILoc
);
865 bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState
&PFS
,
866 MDNode
*&Node
, const yaml::StringValue
&Source
) {
867 if (Source
.Value
.empty())
870 if (llvm::parseMDNode(PFS
, Node
, Source
.Value
, Error
))
871 return error(Error
, Source
.SourceRange
);
875 bool MIRParserImpl::initializeConstantPool(PerFunctionMIParsingState
&PFS
,
876 MachineConstantPool
&ConstantPool
, const yaml::MachineFunction
&YamlMF
) {
877 DenseMap
<unsigned, unsigned> &ConstantPoolSlots
= PFS
.ConstantPoolSlots
;
878 const MachineFunction
&MF
= PFS
.MF
;
879 const auto &M
= *MF
.getFunction().getParent();
881 for (const auto &YamlConstant
: YamlMF
.Constants
) {
882 if (YamlConstant
.IsTargetSpecific
)
883 // FIXME: Support target-specific constant pools
884 return error(YamlConstant
.Value
.SourceRange
.Start
,
885 "Can't parse target-specific constant pool entries yet");
886 const Constant
*Value
= dyn_cast_or_null
<Constant
>(
887 parseConstantValue(YamlConstant
.Value
.Value
, Error
, M
));
889 return error(Error
, YamlConstant
.Value
.SourceRange
);
890 const Align PrefTypeAlign
=
891 M
.getDataLayout().getPrefTypeAlign(Value
->getType());
892 const Align Alignment
= YamlConstant
.Alignment
.getValueOr(PrefTypeAlign
);
893 unsigned Index
= ConstantPool
.getConstantPoolIndex(Value
, Alignment
);
894 if (!ConstantPoolSlots
.insert(std::make_pair(YamlConstant
.ID
.Value
, Index
))
896 return error(YamlConstant
.ID
.SourceRange
.Start
,
897 Twine("redefinition of constant pool item '%const.") +
898 Twine(YamlConstant
.ID
.Value
) + "'");
903 bool MIRParserImpl::initializeJumpTableInfo(PerFunctionMIParsingState
&PFS
,
904 const yaml::MachineJumpTable
&YamlJTI
) {
905 MachineJumpTableInfo
*JTI
= PFS
.MF
.getOrCreateJumpTableInfo(YamlJTI
.Kind
);
906 for (const auto &Entry
: YamlJTI
.Entries
) {
907 std::vector
<MachineBasicBlock
*> Blocks
;
908 for (const auto &MBBSource
: Entry
.Blocks
) {
909 MachineBasicBlock
*MBB
= nullptr;
910 if (parseMBBReference(PFS
, MBB
, MBBSource
.Value
))
912 Blocks
.push_back(MBB
);
914 unsigned Index
= JTI
->createJumpTableIndex(Blocks
);
915 if (!PFS
.JumpTableSlots
.insert(std::make_pair(Entry
.ID
.Value
, Index
))
917 return error(Entry
.ID
.SourceRange
.Start
,
918 Twine("redefinition of jump table entry '%jump-table.") +
919 Twine(Entry
.ID
.Value
) + "'");
924 bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState
&PFS
,
925 MachineBasicBlock
*&MBB
,
926 const yaml::StringValue
&Source
) {
928 if (llvm::parseMBBReference(PFS
, MBB
, Source
.Value
, Error
))
929 return error(Error
, Source
.SourceRange
);
933 bool MIRParserImpl::parseMachineMetadata(PerFunctionMIParsingState
&PFS
,
934 const yaml::StringValue
&Source
) {
936 if (llvm::parseMachineMetadata(PFS
, Source
.Value
, Source
.SourceRange
, Error
))
937 return error(Error
, Source
.SourceRange
);
941 bool MIRParserImpl::parseMachineMetadataNodes(
942 PerFunctionMIParsingState
&PFS
, MachineFunction
&MF
,
943 const yaml::MachineFunction
&YMF
) {
944 for (auto &MDS
: YMF
.MachineMetadataNodes
) {
945 if (parseMachineMetadata(PFS
, MDS
))
948 // Report missing definitions from forward referenced nodes.
949 if (!PFS
.MachineForwardRefMDNodes
.empty())
950 return error(PFS
.MachineForwardRefMDNodes
.begin()->second
.second
,
951 "use of undefined metadata '!" +
952 Twine(PFS
.MachineForwardRefMDNodes
.begin()->first
) + "'");
956 SMDiagnostic
MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic
&Error
,
957 SMRange SourceRange
) {
958 assert(SourceRange
.isValid() && "Invalid source range");
959 SMLoc Loc
= SourceRange
.Start
;
960 bool HasQuote
= Loc
.getPointer() < SourceRange
.End
.getPointer() &&
961 *Loc
.getPointer() == '\'';
962 // Translate the location of the error from the location in the MI string to
963 // the corresponding location in the MIR file.
964 Loc
= Loc
.getFromPointer(Loc
.getPointer() + Error
.getColumnNo() +
967 // TODO: Translate any source ranges as well.
968 return SM
.GetMessage(Loc
, Error
.getKind(), Error
.getMessage(), None
,
972 SMDiagnostic
MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic
&Error
,
973 SMRange SourceRange
) {
974 assert(SourceRange
.isValid());
976 // Translate the location of the error from the location in the llvm IR string
977 // to the corresponding location in the MIR file.
978 auto LineAndColumn
= SM
.getLineAndColumn(SourceRange
.Start
);
979 unsigned Line
= LineAndColumn
.first
+ Error
.getLineNo() - 1;
980 unsigned Column
= Error
.getColumnNo();
981 StringRef LineStr
= Error
.getLineContents();
982 SMLoc Loc
= Error
.getLoc();
984 // Get the full line and adjust the column number by taking the indentation of
985 // LLVM IR into account.
986 for (line_iterator
L(*SM
.getMemoryBuffer(SM
.getMainFileID()), false), E
;
988 if (L
.line_number() == Line
) {
990 Loc
= SMLoc::getFromPointer(LineStr
.data());
991 auto Indent
= LineStr
.find(Error
.getLineContents());
992 if (Indent
!= StringRef::npos
)
998 return SMDiagnostic(SM
, Loc
, Filename
, Line
, Column
, Error
.getKind(),
999 Error
.getMessage(), LineStr
, Error
.getRanges(),
1003 MIRParser::MIRParser(std::unique_ptr
<MIRParserImpl
> Impl
)
1004 : Impl(std::move(Impl
)) {}
1006 MIRParser::~MIRParser() {}
1008 std::unique_ptr
<Module
>
1009 MIRParser::parseIRModule(DataLayoutCallbackTy DataLayoutCallback
) {
1010 return Impl
->parseIRModule(DataLayoutCallback
);
1013 bool MIRParser::parseMachineFunctions(Module
&M
, MachineModuleInfo
&MMI
) {
1014 return Impl
->parseMachineFunctions(M
, MMI
);
1017 std::unique_ptr
<MIRParser
> llvm::createMIRParserFromFile(
1018 StringRef Filename
, SMDiagnostic
&Error
, LLVMContext
&Context
,
1019 std::function
<void(Function
&)> ProcessIRFunction
) {
1020 auto FileOrErr
= MemoryBuffer::getFileOrSTDIN(Filename
, /*IsText=*/true);
1021 if (std::error_code EC
= FileOrErr
.getError()) {
1022 Error
= SMDiagnostic(Filename
, SourceMgr::DK_Error
,
1023 "Could not open input file: " + EC
.message());
1026 return createMIRParser(std::move(FileOrErr
.get()), Context
,
1030 std::unique_ptr
<MIRParser
>
1031 llvm::createMIRParser(std::unique_ptr
<MemoryBuffer
> Contents
,
1032 LLVMContext
&Context
,
1033 std::function
<void(Function
&)> ProcessIRFunction
) {
1034 auto Filename
= Contents
->getBufferIdentifier();
1035 if (Context
.shouldDiscardValueNames()) {
1036 Context
.diagnose(DiagnosticInfoMIRParser(
1039 Filename
, SourceMgr::DK_Error
,
1040 "Can't read MIR with a Context that discards named Values")));
1043 return std::make_unique
<MIRParser
>(std::make_unique
<MIRParserImpl
>(
1044 std::move(Contents
), Filename
, Context
, ProcessIRFunction
));