1 //===- MIRParser.cpp - MIR serialization format parser implementation -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the class that parses the optional LLVM IR and machine
11 // functions that are stored in MIR files.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/MIRParser/MIRParser.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/AsmParser/Parser.h"
22 #include "llvm/AsmParser/SlotMapping.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/MIRYamlMapping.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/DiagnosticInfo.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/LLVMContext.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ValueSymbolTable.h"
34 #include "llvm/Support/LineIterator.h"
35 #include "llvm/Support/SMLoc.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/YAMLTraits.h"
45 /// This class implements the parsing of LLVM IR that's embedded inside a MIR
51 StringMap<std::unique_ptr<yaml::MachineFunction>> Functions;
53 /// Maps from register class names to register classes.
54 StringMap<const TargetRegisterClass *> Names2RegClasses;
57 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
58 LLVMContext &Context);
60 void reportDiagnostic(const SMDiagnostic &Diag);
62 /// Report an error with the given message at unknown location.
64 /// Always returns true.
65 bool error(const Twine &Message);
67 /// Report an error with the given message at the given location.
69 /// Always returns true.
70 bool error(SMLoc Loc, const Twine &Message);
72 /// Report a given error with the location translated from the location in an
73 /// embedded string literal to a location in the MIR file.
75 /// Always returns true.
76 bool error(const SMDiagnostic &Error, SMRange SourceRange);
78 /// Try to parse the optional LLVM module and the machine functions in the MIR
81 /// Return null if an error occurred.
82 std::unique_ptr<Module> parse();
84 /// Parse the machine function in the current YAML document.
86 /// \param NoLLVMIR - set to true when the MIR file doesn't have LLVM IR.
87 /// A dummy IR function is created and inserted into the given module when
88 /// this parameter is true.
90 /// Return true if an error occurred.
91 bool parseMachineFunction(yaml::Input &In, Module &M, bool NoLLVMIR);
93 /// Initialize the machine function to the state that's described in the MIR
96 /// Return true if error occurred.
97 bool initializeMachineFunction(MachineFunction &MF);
99 /// Initialize the machine basic block using it's YAML representation.
101 /// Return true if an error occurred.
102 bool initializeMachineBasicBlock(MachineFunction &MF, MachineBasicBlock &MBB,
103 const yaml::MachineBasicBlock &YamlMBB,
104 const PerFunctionMIParsingState &PFS);
106 bool initializeRegisterInfo(MachineFunction &MF,
107 const yaml::MachineFunction &YamlMF,
108 PerFunctionMIParsingState &PFS);
110 void inferRegisterInfo(MachineFunction &MF,
111 const yaml::MachineFunction &YamlMF);
113 bool initializeFrameInfo(MachineFunction &MF,
114 const yaml::MachineFunction &YamlMF,
115 PerFunctionMIParsingState &PFS);
117 bool parseCalleeSavedRegister(MachineFunction &MF,
118 PerFunctionMIParsingState &PFS,
119 std::vector<CalleeSavedInfo> &CSIInfo,
120 const yaml::StringValue &RegisterSource,
123 bool initializeConstantPool(MachineConstantPool &ConstantPool,
124 const yaml::MachineFunction &YamlMF,
125 const MachineFunction &MF,
126 DenseMap<unsigned, unsigned> &ConstantPoolSlots);
128 bool initializeJumpTableInfo(MachineFunction &MF,
129 const yaml::MachineJumpTable &YamlJTI,
130 PerFunctionMIParsingState &PFS);
133 bool parseMBBReference(MachineBasicBlock *&MBB,
134 const yaml::StringValue &Source, MachineFunction &MF,
135 const PerFunctionMIParsingState &PFS);
137 /// Return a MIR diagnostic converted from an MI string diagnostic.
138 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
139 SMRange SourceRange);
141 /// Return a MIR diagnostic converted from an LLVM assembly diagnostic.
142 SMDiagnostic diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
143 SMRange SourceRange);
145 /// Create an empty function with the given name.
146 void createDummyFunction(StringRef Name, Module &M);
148 void initNames2RegClasses(const MachineFunction &MF);
150 /// Check if the given identifier is a name of a register class.
152 /// Return null if the name isn't a register class.
153 const TargetRegisterClass *getRegClass(const MachineFunction &MF,
157 } // end namespace llvm
159 MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
160 StringRef Filename, LLVMContext &Context)
161 : SM(), Filename(Filename), Context(Context) {
162 SM.AddNewSourceBuffer(std::move(Contents), SMLoc());
165 bool MIRParserImpl::error(const Twine &Message) {
166 Context.diagnose(DiagnosticInfoMIRParser(
167 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
171 bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
172 Context.diagnose(DiagnosticInfoMIRParser(
173 DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
177 bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
178 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
179 reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
183 void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
184 DiagnosticSeverity Kind;
185 switch (Diag.getKind()) {
186 case SourceMgr::DK_Error:
189 case SourceMgr::DK_Warning:
192 case SourceMgr::DK_Note:
196 Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
199 static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
200 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
203 std::unique_ptr<Module> MIRParserImpl::parse() {
204 yaml::Input In(SM.getMemoryBuffer(SM.getMainFileID())->getBuffer(),
205 /*Ctxt=*/nullptr, handleYAMLDiag, this);
208 if (!In.setCurrentDocument()) {
211 // Create an empty module when the MIR file is empty.
212 return llvm::make_unique<Module>(Filename, Context);
215 std::unique_ptr<Module> M;
216 bool NoLLVMIR = false;
217 // Parse the block scalar manually so that we can return unique pointer
218 // without having to go trough YAML traits.
219 if (const auto *BSN =
220 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
222 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
225 reportDiagnostic(diagFromLLVMAssemblyDiag(Error, BSN->getSourceRange()));
229 if (!In.setCurrentDocument())
232 // Create an new, empty module.
233 M = llvm::make_unique<Module>(Filename, Context);
237 // Parse the machine functions.
239 if (parseMachineFunction(In, *M, NoLLVMIR))
242 } while (In.setCurrentDocument());
247 bool MIRParserImpl::parseMachineFunction(yaml::Input &In, Module &M,
249 auto MF = llvm::make_unique<yaml::MachineFunction>();
250 yaml::yamlize(In, *MF, false);
253 auto FunctionName = MF->Name;
254 if (Functions.find(FunctionName) != Functions.end())
255 return error(Twine("redefinition of machine function '") + FunctionName +
257 Functions.insert(std::make_pair(FunctionName, std::move(MF)));
259 createDummyFunction(FunctionName, M);
260 else if (!M.getFunction(FunctionName))
261 return error(Twine("function '") + FunctionName +
262 "' isn't defined in the provided LLVM IR");
266 void MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
267 auto &Context = M.getContext();
268 Function *F = cast<Function>(M.getOrInsertFunction(
269 Name, FunctionType::get(Type::getVoidTy(Context), false)));
270 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
271 new UnreachableInst(Context, BB);
274 bool MIRParserImpl::initializeMachineFunction(MachineFunction &MF) {
275 auto It = Functions.find(MF.getName());
276 if (It == Functions.end())
277 return error(Twine("no machine function information for function '") +
278 MF.getName() + "' in the MIR file");
279 // TODO: Recreate the machine function.
280 const yaml::MachineFunction &YamlMF = *It->getValue();
281 if (YamlMF.Alignment)
282 MF.setAlignment(YamlMF.Alignment);
283 MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
284 MF.setHasInlineAsm(YamlMF.HasInlineAsm);
285 PerFunctionMIParsingState PFS;
286 if (initializeRegisterInfo(MF, YamlMF, PFS))
288 if (!YamlMF.Constants.empty()) {
289 auto *ConstantPool = MF.getConstantPool();
290 assert(ConstantPool && "Constant pool must be created");
291 if (initializeConstantPool(*ConstantPool, YamlMF, MF,
292 PFS.ConstantPoolSlots))
296 const auto &F = *MF.getFunction();
297 for (const auto &YamlMBB : YamlMF.BasicBlocks) {
298 const BasicBlock *BB = nullptr;
299 const yaml::StringValue &Name = YamlMBB.Name;
300 const yaml::StringValue &IRBlock = YamlMBB.IRBlock;
301 if (!Name.Value.empty()) {
302 BB = dyn_cast_or_null<BasicBlock>(
303 F.getValueSymbolTable().lookup(Name.Value));
305 return error(Name.SourceRange.Start,
306 Twine("basic block '") + Name.Value +
307 "' is not defined in the function '" + MF.getName() +
310 if (!IRBlock.Value.empty()) {
311 // TODO: Report an error when both name and ir block are specified.
313 if (parseIRBlockReference(BB, SM, MF, IRBlock.Value, PFS, IRSlots, Error))
314 return error(Error, IRBlock.SourceRange);
316 auto *MBB = MF.CreateMachineBasicBlock(BB);
317 MF.insert(MF.end(), MBB);
319 PFS.MBBSlots.insert(std::make_pair(YamlMBB.ID, MBB)).second;
321 return error(Twine("redefinition of machine basic block with id #") +
325 if (YamlMF.BasicBlocks.empty())
326 return error(Twine("machine function '") + Twine(MF.getName()) +
327 "' requires at least one machine basic block in its body");
328 // Initialize the frame information after creating all the MBBs so that the
329 // MBB references in the frame information can be resolved.
330 if (initializeFrameInfo(MF, YamlMF, PFS))
332 // Initialize the jump table after creating all the MBBs so that the MBB
333 // references can be resolved.
334 if (!YamlMF.JumpTableInfo.Entries.empty() &&
335 initializeJumpTableInfo(MF, YamlMF.JumpTableInfo, PFS))
337 // Initialize the machine basic blocks after creating them all so that the
338 // machine instructions parser can resolve the MBB references.
340 for (const auto &YamlMBB : YamlMF.BasicBlocks) {
341 if (initializeMachineBasicBlock(MF, *MF.getBlockNumbered(I++), YamlMBB,
345 inferRegisterInfo(MF, YamlMF);
346 // FIXME: This is a temporary workaround until the reserved registers can be
348 MF.getRegInfo().freezeReservedRegs(MF);
353 bool MIRParserImpl::initializeMachineBasicBlock(
354 MachineFunction &MF, MachineBasicBlock &MBB,
355 const yaml::MachineBasicBlock &YamlMBB,
356 const PerFunctionMIParsingState &PFS) {
357 MBB.setAlignment(YamlMBB.Alignment);
358 if (YamlMBB.AddressTaken)
359 MBB.setHasAddressTaken();
360 MBB.setIsLandingPad(YamlMBB.IsLandingPad);
362 // Parse the successors.
363 const auto &Weights = YamlMBB.SuccessorWeights;
364 bool HasWeights = !Weights.empty();
365 if (HasWeights && Weights.size() != YamlMBB.Successors.size()) {
366 bool IsFew = Weights.size() < YamlMBB.Successors.size();
367 return error(IsFew ? Weights.back().SourceRange.End
368 : Weights[YamlMBB.Successors.size()].SourceRange.Start,
369 Twine("too ") + (IsFew ? "few" : "many") +
370 " successor weights, expected " +
371 Twine(YamlMBB.Successors.size()) + ", have " +
372 Twine(Weights.size()));
374 size_t SuccessorIndex = 0;
375 for (const auto &MBBSource : YamlMBB.Successors) {
376 MachineBasicBlock *SuccMBB = nullptr;
377 if (parseMBBReference(SuccMBB, MBBSource, MF, PFS))
379 // TODO: Report an error when adding the same successor more than once.
380 MBB.addSuccessor(SuccMBB, HasWeights ? Weights[SuccessorIndex++].Value : 0);
382 // Parse the liveins.
383 for (const auto &LiveInSource : YamlMBB.LiveIns) {
385 if (parseNamedRegisterReference(Reg, SM, MF, LiveInSource.Value, PFS,
387 return error(Error, LiveInSource.SourceRange);
390 // Parse the instructions.
391 for (const auto &MISource : YamlMBB.Instructions) {
392 MachineInstr *MI = nullptr;
393 if (parseMachineInstr(MI, SM, MF, MISource.Value, PFS, IRSlots, Error))
394 return error(Error, MISource.SourceRange);
395 MBB.insert(MBB.end(), MI);
400 bool MIRParserImpl::initializeRegisterInfo(MachineFunction &MF,
401 const yaml::MachineFunction &YamlMF,
402 PerFunctionMIParsingState &PFS) {
403 MachineRegisterInfo &RegInfo = MF.getRegInfo();
404 assert(RegInfo.isSSA());
407 assert(RegInfo.tracksLiveness());
408 if (!YamlMF.TracksRegLiveness)
409 RegInfo.invalidateLiveness();
410 RegInfo.enableSubRegLiveness(YamlMF.TracksSubRegLiveness);
413 // Parse the virtual register information.
414 for (const auto &VReg : YamlMF.VirtualRegisters) {
415 const auto *RC = getRegClass(MF, VReg.Class.Value);
417 return error(VReg.Class.SourceRange.Start,
418 Twine("use of undefined register class '") +
419 VReg.Class.Value + "'");
420 unsigned Reg = RegInfo.createVirtualRegister(RC);
421 if (!PFS.VirtualRegisterSlots.insert(std::make_pair(VReg.ID.Value, Reg))
423 return error(VReg.ID.SourceRange.Start,
424 Twine("redefinition of virtual register '%") +
425 Twine(VReg.ID.Value) + "'");
426 if (!VReg.PreferredRegister.Value.empty()) {
427 unsigned PreferredReg = 0;
428 if (parseNamedRegisterReference(PreferredReg, SM, MF,
429 VReg.PreferredRegister.Value, PFS,
431 return error(Error, VReg.PreferredRegister.SourceRange);
432 RegInfo.setSimpleHint(Reg, PreferredReg);
436 // Parse the liveins.
437 for (const auto &LiveIn : YamlMF.LiveIns) {
439 if (parseNamedRegisterReference(Reg, SM, MF, LiveIn.Register.Value, PFS,
441 return error(Error, LiveIn.Register.SourceRange);
443 if (!LiveIn.VirtualRegister.Value.empty()) {
444 if (parseVirtualRegisterReference(
445 VReg, SM, MF, LiveIn.VirtualRegister.Value, PFS, IRSlots, Error))
446 return error(Error, LiveIn.VirtualRegister.SourceRange);
448 RegInfo.addLiveIn(Reg, VReg);
451 // Parse the callee saved register mask.
452 BitVector CalleeSavedRegisterMask(RegInfo.getUsedPhysRegsMask().size());
453 if (!YamlMF.CalleeSavedRegisters)
455 for (const auto &RegSource : YamlMF.CalleeSavedRegisters.getValue()) {
457 if (parseNamedRegisterReference(Reg, SM, MF, RegSource.Value, PFS, IRSlots,
459 return error(Error, RegSource.SourceRange);
460 CalleeSavedRegisterMask[Reg] = true;
462 RegInfo.setUsedPhysRegMask(CalleeSavedRegisterMask.flip());
466 void MIRParserImpl::inferRegisterInfo(MachineFunction &MF,
467 const yaml::MachineFunction &YamlMF) {
468 if (YamlMF.CalleeSavedRegisters)
470 for (const MachineBasicBlock &MBB : MF) {
471 for (const MachineInstr &MI : MBB) {
472 for (const MachineOperand &MO : MI.operands()) {
475 MF.getRegInfo().addPhysRegsUsedFromRegMask(MO.getRegMask());
481 bool MIRParserImpl::initializeFrameInfo(MachineFunction &MF,
482 const yaml::MachineFunction &YamlMF,
483 PerFunctionMIParsingState &PFS) {
484 MachineFrameInfo &MFI = *MF.getFrameInfo();
485 const Function &F = *MF.getFunction();
486 const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
487 MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
488 MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
489 MFI.setHasStackMap(YamlMFI.HasStackMap);
490 MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
491 MFI.setStackSize(YamlMFI.StackSize);
492 MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
493 if (YamlMFI.MaxAlignment)
494 MFI.ensureMaxAlignment(YamlMFI.MaxAlignment);
495 MFI.setAdjustsStack(YamlMFI.AdjustsStack);
496 MFI.setHasCalls(YamlMFI.HasCalls);
497 MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
498 MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
499 MFI.setHasVAStart(YamlMFI.HasVAStart);
500 MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
501 if (!YamlMFI.SavePoint.Value.empty()) {
502 MachineBasicBlock *MBB = nullptr;
503 if (parseMBBReference(MBB, YamlMFI.SavePoint, MF, PFS))
505 MFI.setSavePoint(MBB);
507 if (!YamlMFI.RestorePoint.Value.empty()) {
508 MachineBasicBlock *MBB = nullptr;
509 if (parseMBBReference(MBB, YamlMFI.RestorePoint, MF, PFS))
511 MFI.setRestorePoint(MBB);
514 std::vector<CalleeSavedInfo> CSIInfo;
515 // Initialize the fixed frame objects.
516 for (const auto &Object : YamlMF.FixedStackObjects) {
518 if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
519 ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
520 Object.IsImmutable, Object.IsAliased);
522 ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
523 MFI.setObjectAlignment(ObjectIdx, Object.Alignment);
524 if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
527 return error(Object.ID.SourceRange.Start,
528 Twine("redefinition of fixed stack object '%fixed-stack.") +
529 Twine(Object.ID.Value) + "'");
530 if (parseCalleeSavedRegister(MF, PFS, CSIInfo, Object.CalleeSavedRegister,
535 // Initialize the ordinary frame objects.
536 for (const auto &Object : YamlMF.StackObjects) {
538 const AllocaInst *Alloca = nullptr;
539 const yaml::StringValue &Name = Object.Name;
540 if (!Name.Value.empty()) {
541 Alloca = dyn_cast_or_null<AllocaInst>(
542 F.getValueSymbolTable().lookup(Name.Value));
544 return error(Name.SourceRange.Start,
545 "alloca instruction named '" + Name.Value +
546 "' isn't defined in the function '" + F.getName() +
549 if (Object.Type == yaml::MachineStackObject::VariableSized)
550 ObjectIdx = MFI.CreateVariableSizedObject(Object.Alignment, Alloca);
552 ObjectIdx = MFI.CreateStackObject(
553 Object.Size, Object.Alignment,
554 Object.Type == yaml::MachineStackObject::SpillSlot, Alloca);
555 MFI.setObjectOffset(ObjectIdx, Object.Offset);
556 if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
558 return error(Object.ID.SourceRange.Start,
559 Twine("redefinition of stack object '%stack.") +
560 Twine(Object.ID.Value) + "'");
561 if (parseCalleeSavedRegister(MF, PFS, CSIInfo, Object.CalleeSavedRegister,
565 MFI.setCalleeSavedInfo(CSIInfo);
566 if (!CSIInfo.empty())
567 MFI.setCalleeSavedInfoValid(true);
571 bool MIRParserImpl::parseCalleeSavedRegister(
572 MachineFunction &MF, PerFunctionMIParsingState &PFS,
573 std::vector<CalleeSavedInfo> &CSIInfo,
574 const yaml::StringValue &RegisterSource, int FrameIdx) {
575 if (RegisterSource.Value.empty())
579 if (parseNamedRegisterReference(Reg, SM, MF, RegisterSource.Value, PFS,
581 return error(Error, RegisterSource.SourceRange);
582 CSIInfo.push_back(CalleeSavedInfo(Reg, FrameIdx));
586 bool MIRParserImpl::initializeConstantPool(
587 MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF,
588 const MachineFunction &MF,
589 DenseMap<unsigned, unsigned> &ConstantPoolSlots) {
590 const auto &M = *MF.getFunction()->getParent();
592 for (const auto &YamlConstant : YamlMF.Constants) {
593 const Constant *Value = dyn_cast_or_null<Constant>(
594 parseConstantValue(YamlConstant.Value.Value, Error, M));
596 return error(Error, YamlConstant.Value.SourceRange);
598 YamlConstant.Alignment
599 ? YamlConstant.Alignment
600 : M.getDataLayout().getPrefTypeAlignment(Value->getType());
601 unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
602 if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
604 return error(YamlConstant.ID.SourceRange.Start,
605 Twine("redefinition of constant pool item '%const.") +
606 Twine(YamlConstant.ID.Value) + "'");
611 bool MIRParserImpl::initializeJumpTableInfo(
612 MachineFunction &MF, const yaml::MachineJumpTable &YamlJTI,
613 PerFunctionMIParsingState &PFS) {
614 MachineJumpTableInfo *JTI = MF.getOrCreateJumpTableInfo(YamlJTI.Kind);
615 for (const auto &Entry : YamlJTI.Entries) {
616 std::vector<MachineBasicBlock *> Blocks;
617 for (const auto &MBBSource : Entry.Blocks) {
618 MachineBasicBlock *MBB = nullptr;
619 if (parseMBBReference(MBB, MBBSource.Value, MF, PFS))
621 Blocks.push_back(MBB);
623 unsigned Index = JTI->createJumpTableIndex(Blocks);
624 if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
626 return error(Entry.ID.SourceRange.Start,
627 Twine("redefinition of jump table entry '%jump-table.") +
628 Twine(Entry.ID.Value) + "'");
633 bool MIRParserImpl::parseMBBReference(MachineBasicBlock *&MBB,
634 const yaml::StringValue &Source,
636 const PerFunctionMIParsingState &PFS) {
638 if (llvm::parseMBBReference(MBB, SM, MF, Source.Value, PFS, IRSlots, Error))
639 return error(Error, Source.SourceRange);
643 SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
644 SMRange SourceRange) {
645 assert(SourceRange.isValid() && "Invalid source range");
646 SMLoc Loc = SourceRange.Start;
647 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
648 *Loc.getPointer() == '\'';
649 // Translate the location of the error from the location in the MI string to
650 // the corresponding location in the MIR file.
651 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
654 // TODO: Translate any source ranges as well.
655 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None,
659 SMDiagnostic MIRParserImpl::diagFromLLVMAssemblyDiag(const SMDiagnostic &Error,
660 SMRange SourceRange) {
661 assert(SourceRange.isValid());
663 // Translate the location of the error from the location in the llvm IR string
664 // to the corresponding location in the MIR file.
665 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
666 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
667 unsigned Column = Error.getColumnNo();
668 StringRef LineStr = Error.getLineContents();
669 SMLoc Loc = Error.getLoc();
671 // Get the full line and adjust the column number by taking the indentation of
672 // LLVM IR into account.
673 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
675 if (L.line_number() == Line) {
677 Loc = SMLoc::getFromPointer(LineStr.data());
678 auto Indent = LineStr.find(Error.getLineContents());
679 if (Indent != StringRef::npos)
685 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
686 Error.getMessage(), LineStr, Error.getRanges(),
690 void MIRParserImpl::initNames2RegClasses(const MachineFunction &MF) {
691 if (!Names2RegClasses.empty())
693 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
694 for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; ++I) {
695 const auto *RC = TRI->getRegClass(I);
696 Names2RegClasses.insert(
697 std::make_pair(StringRef(TRI->getRegClassName(RC)).lower(), RC));
701 const TargetRegisterClass *MIRParserImpl::getRegClass(const MachineFunction &MF,
703 initNames2RegClasses(MF);
704 auto RegClassInfo = Names2RegClasses.find(Name);
705 if (RegClassInfo == Names2RegClasses.end())
707 return RegClassInfo->getValue();
710 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
711 : Impl(std::move(Impl)) {}
713 MIRParser::~MIRParser() {}
715 std::unique_ptr<Module> MIRParser::parseLLVMModule() { return Impl->parse(); }
717 bool MIRParser::initializeMachineFunction(MachineFunction &MF) {
718 return Impl->initializeMachineFunction(MF);
721 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(StringRef Filename,
723 LLVMContext &Context) {
724 auto FileOrErr = MemoryBuffer::getFile(Filename);
725 if (std::error_code EC = FileOrErr.getError()) {
726 Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
727 "Could not open input file: " + EC.message());
730 return createMIRParser(std::move(FileOrErr.get()), Context);
733 std::unique_ptr<MIRParser>
734 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
735 LLVMContext &Context) {
736 auto Filename = Contents->getBufferIdentifier();
737 return llvm::make_unique<MIRParser>(
738 llvm::make_unique<MIRParserImpl>(std::move(Contents), Filename, Context));