[lldb] Fix "exact match" debug_names type queries (#118465)
[llvm-project.git] / llvm / lib / CodeGen / MIRParser / MIRParser.cpp
blobe2543f883f91ce0fbf66c2722ae37bcc6529fd94
1 //===- MIRParser.cpp - MIR serialization format parser implementation -----===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
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/StringRef.h"
17 #include "llvm/AsmParser/Parser.h"
18 #include "llvm/AsmParser/SlotMapping.h"
19 #include "llvm/CodeGen/MIRParser/MIParser.h"
20 #include "llvm/CodeGen/MIRYamlMapping.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/TargetFrameLowering.h"
28 #include "llvm/IR/BasicBlock.h"
29 #include "llvm/IR/DebugInfoMetadata.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/LLVMContext.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/ValueSymbolTable.h"
35 #include "llvm/Support/LineIterator.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/SMLoc.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/YAMLTraits.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include <memory>
43 using namespace llvm;
45 namespace llvm {
46 class MDNode;
47 class RegisterBank;
49 /// This class implements the parsing of LLVM IR that's embedded inside a MIR
50 /// file.
51 class MIRParserImpl {
52 SourceMgr SM;
53 LLVMContext &Context;
54 yaml::Input In;
55 StringRef Filename;
56 SlotMapping IRSlots;
57 std::unique_ptr<PerTargetMIParsingState> Target;
59 /// True when the MIR file doesn't have LLVM IR. Dummy IR functions are
60 /// created and inserted into the given module when this is true.
61 bool NoLLVMIR = false;
62 /// True when a well formed MIR file does not contain any MIR/machine function
63 /// parts.
64 bool NoMIRDocuments = false;
66 std::function<void(Function &)> ProcessIRFunction;
68 public:
69 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
70 LLVMContext &Context,
71 std::function<void(Function &)> ProcessIRFunction);
73 void reportDiagnostic(const SMDiagnostic &Diag);
75 /// Report an error with the given message at unknown location.
76 ///
77 /// Always returns true.
78 bool error(const Twine &Message);
80 /// Report an error with the given message at the given location.
81 ///
82 /// Always returns true.
83 bool error(SMLoc Loc, const Twine &Message);
85 /// Report a given error with the location translated from the location in an
86 /// embedded string literal to a location in the MIR file.
87 ///
88 /// Always returns true.
89 bool error(const SMDiagnostic &Error, SMRange SourceRange);
91 /// Try to parse the optional LLVM module and the machine functions in the MIR
92 /// file.
93 ///
94 /// Return null if an error occurred.
95 std::unique_ptr<Module>
96 parseIRModule(DataLayoutCallbackTy DataLayoutCallback);
98 /// Create an empty function with the given name.
99 Function *createDummyFunction(StringRef Name, Module &M);
101 bool parseMachineFunctions(Module &M, MachineModuleInfo &MMI,
102 ModuleAnalysisManager *FAM = nullptr);
104 /// Parse the machine function in the current YAML document.
107 /// Return true if an error occurred.
108 bool parseMachineFunction(Module &M, MachineModuleInfo &MMI,
109 ModuleAnalysisManager *FAM);
111 /// Initialize the machine function to the state that's described in the MIR
112 /// file.
114 /// Return true if error occurred.
115 bool initializeMachineFunction(const yaml::MachineFunction &YamlMF,
116 MachineFunction &MF);
118 bool parseRegisterInfo(PerFunctionMIParsingState &PFS,
119 const yaml::MachineFunction &YamlMF);
121 bool setupRegisterInfo(const PerFunctionMIParsingState &PFS,
122 const yaml::MachineFunction &YamlMF);
124 bool initializeFrameInfo(PerFunctionMIParsingState &PFS,
125 const yaml::MachineFunction &YamlMF);
127 bool initializeCallSiteInfo(PerFunctionMIParsingState &PFS,
128 const yaml::MachineFunction &YamlMF);
130 bool parseCalleeSavedRegister(PerFunctionMIParsingState &PFS,
131 std::vector<CalleeSavedInfo> &CSIInfo,
132 const yaml::StringValue &RegisterSource,
133 bool IsRestored, int FrameIdx);
135 struct VarExprLoc {
136 DILocalVariable *DIVar = nullptr;
137 DIExpression *DIExpr = nullptr;
138 DILocation *DILoc = nullptr;
141 std::optional<VarExprLoc> parseVarExprLoc(PerFunctionMIParsingState &PFS,
142 const yaml::StringValue &VarStr,
143 const yaml::StringValue &ExprStr,
144 const yaml::StringValue &LocStr);
145 template <typename T>
146 bool parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
147 const T &Object,
148 int FrameIdx);
150 bool initializeConstantPool(PerFunctionMIParsingState &PFS,
151 MachineConstantPool &ConstantPool,
152 const yaml::MachineFunction &YamlMF);
154 bool initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
155 const yaml::MachineJumpTable &YamlJTI);
157 bool parseMachineMetadataNodes(PerFunctionMIParsingState &PFS,
158 MachineFunction &MF,
159 const yaml::MachineFunction &YMF);
161 private:
162 bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node,
163 const yaml::StringValue &Source);
165 bool parseMBBReference(PerFunctionMIParsingState &PFS,
166 MachineBasicBlock *&MBB,
167 const yaml::StringValue &Source);
169 bool parseMachineMetadata(PerFunctionMIParsingState &PFS,
170 const yaml::StringValue &Source);
172 /// Return a MIR diagnostic converted from an MI string diagnostic.
173 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
174 SMRange SourceRange);
176 /// Return a MIR diagnostic converted from a diagnostic located in a YAML
177 /// block scalar string.
178 SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error,
179 SMRange SourceRange);
181 bool computeFunctionProperties(MachineFunction &MF,
182 const yaml::MachineFunction &YamlMF);
184 void setupDebugValueTracking(MachineFunction &MF,
185 PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF);
188 } // end namespace llvm
190 static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
191 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
194 MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
195 StringRef Filename, LLVMContext &Context,
196 std::function<void(Function &)> Callback)
197 : Context(Context),
198 In(SM.getMemoryBuffer(SM.AddNewSourceBuffer(std::move(Contents), SMLoc()))
199 ->getBuffer(),
200 nullptr, handleYAMLDiag, this),
201 Filename(Filename), ProcessIRFunction(Callback) {
202 In.setContext(&In);
205 bool MIRParserImpl::error(const Twine &Message) {
206 Context.diagnose(DiagnosticInfoMIRParser(
207 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
208 return true;
211 bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
212 Context.diagnose(DiagnosticInfoMIRParser(
213 DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
214 return true;
217 bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
218 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
219 reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
220 return true;
223 void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
224 DiagnosticSeverity Kind;
225 switch (Diag.getKind()) {
226 case SourceMgr::DK_Error:
227 Kind = DS_Error;
228 break;
229 case SourceMgr::DK_Warning:
230 Kind = DS_Warning;
231 break;
232 case SourceMgr::DK_Note:
233 Kind = DS_Note;
234 break;
235 case SourceMgr::DK_Remark:
236 llvm_unreachable("remark unexpected");
237 break;
239 Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
242 std::unique_ptr<Module>
243 MIRParserImpl::parseIRModule(DataLayoutCallbackTy DataLayoutCallback) {
244 if (!In.setCurrentDocument()) {
245 if (In.error())
246 return nullptr;
247 // Create an empty module when the MIR file is empty.
248 NoMIRDocuments = true;
249 auto M = std::make_unique<Module>(Filename, Context);
250 if (auto LayoutOverride =
251 DataLayoutCallback(M->getTargetTriple(), M->getDataLayoutStr()))
252 M->setDataLayout(*LayoutOverride);
253 return M;
256 std::unique_ptr<Module> M;
257 // Parse the block scalar manually so that we can return unique pointer
258 // without having to go trough YAML traits.
259 if (const auto *BSN =
260 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
261 SMDiagnostic Error;
262 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
263 Context, &IRSlots, DataLayoutCallback);
264 if (!M) {
265 reportDiagnostic(diagFromBlockStringDiag(Error, BSN->getSourceRange()));
266 return nullptr;
268 In.nextDocument();
269 if (!In.setCurrentDocument())
270 NoMIRDocuments = true;
271 } else {
272 // Create an new, empty module.
273 M = std::make_unique<Module>(Filename, Context);
274 if (auto LayoutOverride =
275 DataLayoutCallback(M->getTargetTriple(), M->getDataLayoutStr()))
276 M->setDataLayout(*LayoutOverride);
277 NoLLVMIR = true;
279 return M;
282 bool MIRParserImpl::parseMachineFunctions(Module &M, MachineModuleInfo &MMI,
283 ModuleAnalysisManager *MAM) {
284 if (NoMIRDocuments)
285 return false;
287 // Parse the machine functions.
288 do {
289 if (parseMachineFunction(M, MMI, MAM))
290 return true;
291 In.nextDocument();
292 } while (In.setCurrentDocument());
294 return false;
297 Function *MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
298 auto &Context = M.getContext();
299 Function *F =
300 Function::Create(FunctionType::get(Type::getVoidTy(Context), false),
301 Function::ExternalLinkage, Name, M);
302 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
303 new UnreachableInst(Context, BB);
305 if (ProcessIRFunction)
306 ProcessIRFunction(*F);
308 return F;
311 bool MIRParserImpl::parseMachineFunction(Module &M, MachineModuleInfo &MMI,
312 ModuleAnalysisManager *MAM) {
313 // Parse the yaml.
314 yaml::MachineFunction YamlMF;
315 yaml::EmptyContext Ctx;
317 const TargetMachine &TM = MMI.getTarget();
318 YamlMF.MachineFuncInfo = std::unique_ptr<yaml::MachineFunctionInfo>(
319 TM.createDefaultFuncInfoYAML());
321 yaml::yamlize(In, YamlMF, false, Ctx);
322 if (In.error())
323 return true;
325 // Search for the corresponding IR function.
326 StringRef FunctionName = YamlMF.Name;
327 Function *F = M.getFunction(FunctionName);
328 if (!F) {
329 if (NoLLVMIR) {
330 F = createDummyFunction(FunctionName, M);
331 } else {
332 return error(Twine("function '") + FunctionName +
333 "' isn't defined in the provided LLVM IR");
337 if (!MAM) {
338 if (MMI.getMachineFunction(*F) != nullptr)
339 return error(Twine("redefinition of machine function '") + FunctionName +
340 "'");
342 // Create the MachineFunction.
343 MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
344 if (initializeMachineFunction(YamlMF, MF))
345 return true;
346 } else {
347 auto &FAM =
348 MAM->getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
349 if (FAM.getCachedResult<MachineFunctionAnalysis>(*F))
350 return error(Twine("redefinition of machine function '") + FunctionName +
351 "'");
353 // Create the MachineFunction.
354 MachineFunction &MF = FAM.getResult<MachineFunctionAnalysis>(*F).getMF();
355 if (initializeMachineFunction(YamlMF, MF))
356 return true;
359 return false;
362 static bool isSSA(const MachineFunction &MF) {
363 const MachineRegisterInfo &MRI = MF.getRegInfo();
364 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
365 Register Reg = Register::index2VirtReg(I);
366 if (!MRI.hasOneDef(Reg) && !MRI.def_empty(Reg))
367 return false;
369 // Subregister defs are invalid in SSA.
370 const MachineOperand *RegDef = MRI.getOneDef(Reg);
371 if (RegDef && RegDef->getSubReg() != 0)
372 return false;
374 return true;
377 bool MIRParserImpl::computeFunctionProperties(
378 MachineFunction &MF, const yaml::MachineFunction &YamlMF) {
379 MachineFunctionProperties &Properties = MF.getProperties();
381 bool HasPHI = false;
382 bool HasInlineAsm = false;
383 bool HasFakeUses = false;
384 bool AllTiedOpsRewritten = true, HasTiedOps = false;
385 for (const MachineBasicBlock &MBB : MF) {
386 for (const MachineInstr &MI : MBB) {
387 if (MI.isPHI())
388 HasPHI = true;
389 if (MI.isInlineAsm())
390 HasInlineAsm = true;
391 if (MI.isFakeUse())
392 HasFakeUses = true;
393 for (unsigned I = 0; I < MI.getNumOperands(); ++I) {
394 const MachineOperand &MO = MI.getOperand(I);
395 if (!MO.isReg() || !MO.getReg())
396 continue;
397 unsigned DefIdx;
398 if (MO.isUse() && MI.isRegTiedToDefOperand(I, &DefIdx)) {
399 HasTiedOps = true;
400 if (MO.getReg() != MI.getOperand(DefIdx).getReg())
401 AllTiedOpsRewritten = false;
407 // Helper function to sanity-check and set properties that are computed, but
408 // may be explicitly set from the input MIR
409 auto ComputedPropertyHelper =
410 [&Properties](std::optional<bool> ExplicitProp, bool ComputedProp,
411 MachineFunctionProperties::Property P) -> bool {
412 // Prefer explicitly given values over the computed properties
413 if (ExplicitProp.value_or(ComputedProp))
414 Properties.set(P);
415 else
416 Properties.reset(P);
418 // Check for conflict between the explicit values and the computed ones
419 return ExplicitProp && *ExplicitProp && !ComputedProp;
422 if (ComputedPropertyHelper(YamlMF.NoPHIs, !HasPHI,
423 MachineFunctionProperties::Property::NoPHIs)) {
424 return error(MF.getName() +
425 " has explicit property NoPhi, but contains at least one PHI");
428 MF.setHasInlineAsm(HasInlineAsm);
430 if (HasTiedOps && AllTiedOpsRewritten)
431 Properties.set(MachineFunctionProperties::Property::TiedOpsRewritten);
433 if (ComputedPropertyHelper(YamlMF.IsSSA, isSSA(MF),
434 MachineFunctionProperties::Property::IsSSA)) {
435 return error(MF.getName() +
436 " has explicit property IsSSA, but is not valid SSA");
439 const MachineRegisterInfo &MRI = MF.getRegInfo();
440 if (ComputedPropertyHelper(YamlMF.NoVRegs, MRI.getNumVirtRegs() == 0,
441 MachineFunctionProperties::Property::NoVRegs)) {
442 return error(
443 MF.getName() +
444 " has explicit property NoVRegs, but contains virtual registers");
447 // For hasFakeUses we follow similar logic to the ComputedPropertyHelper,
448 // except for caring about the inverse case only, i.e. when the property is
449 // explicitly set to false and Fake Uses are present; having HasFakeUses=true
450 // on a function without fake uses is harmless.
451 if (YamlMF.HasFakeUses && !*YamlMF.HasFakeUses && HasFakeUses)
452 return error(
453 MF.getName() +
454 " has explicit property hasFakeUses=false, but contains fake uses");
455 MF.setHasFakeUses(YamlMF.HasFakeUses.value_or(HasFakeUses));
457 return false;
460 bool MIRParserImpl::initializeCallSiteInfo(
461 PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF) {
462 MachineFunction &MF = PFS.MF;
463 SMDiagnostic Error;
464 const TargetMachine &TM = MF.getTarget();
465 for (auto &YamlCSInfo : YamlMF.CallSitesInfo) {
466 yaml::CallSiteInfo::MachineInstrLoc MILoc = YamlCSInfo.CallLocation;
467 if (MILoc.BlockNum >= MF.size())
468 return error(Twine(MF.getName()) +
469 Twine(" call instruction block out of range.") +
470 " Unable to reference bb:" + Twine(MILoc.BlockNum));
471 auto CallB = std::next(MF.begin(), MILoc.BlockNum);
472 if (MILoc.Offset >= CallB->size())
473 return error(Twine(MF.getName()) +
474 Twine(" call instruction offset out of range.") +
475 " Unable to reference instruction at bb: " +
476 Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset));
477 auto CallI = std::next(CallB->instr_begin(), MILoc.Offset);
478 if (!CallI->isCall(MachineInstr::IgnoreBundle))
479 return error(Twine(MF.getName()) +
480 Twine(" call site info should reference call "
481 "instruction. Instruction at bb:") +
482 Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset) +
483 " is not a call instruction");
484 MachineFunction::CallSiteInfo CSInfo;
485 for (auto ArgRegPair : YamlCSInfo.ArgForwardingRegs) {
486 Register Reg;
487 if (parseNamedRegisterReference(PFS, Reg, ArgRegPair.Reg.Value, Error))
488 return error(Error, ArgRegPair.Reg.SourceRange);
489 CSInfo.ArgRegPairs.emplace_back(Reg, ArgRegPair.ArgNo);
492 if (TM.Options.EmitCallSiteInfo)
493 MF.addCallSiteInfo(&*CallI, std::move(CSInfo));
496 if (YamlMF.CallSitesInfo.size() && !TM.Options.EmitCallSiteInfo)
497 return error(Twine("Call site info provided but not used"));
498 return false;
501 void MIRParserImpl::setupDebugValueTracking(
502 MachineFunction &MF, PerFunctionMIParsingState &PFS,
503 const yaml::MachineFunction &YamlMF) {
504 // Compute the value of the "next instruction number" field.
505 unsigned MaxInstrNum = 0;
506 for (auto &MBB : MF)
507 for (auto &MI : MBB)
508 MaxInstrNum = std::max((unsigned)MI.peekDebugInstrNum(), MaxInstrNum);
509 MF.setDebugInstrNumberingCount(MaxInstrNum);
511 // Load any substitutions.
512 for (const auto &Sub : YamlMF.DebugValueSubstitutions) {
513 MF.makeDebugValueSubstitution({Sub.SrcInst, Sub.SrcOp},
514 {Sub.DstInst, Sub.DstOp}, Sub.Subreg);
517 // Flag for whether we're supposed to be using DBG_INSTR_REF.
518 MF.setUseDebugInstrRef(YamlMF.UseDebugInstrRef);
521 bool
522 MIRParserImpl::initializeMachineFunction(const yaml::MachineFunction &YamlMF,
523 MachineFunction &MF) {
524 // TODO: Recreate the machine function.
525 if (Target) {
526 // Avoid clearing state if we're using the same subtarget again.
527 Target->setTarget(MF.getSubtarget());
528 } else {
529 Target.reset(new PerTargetMIParsingState(MF.getSubtarget()));
532 MF.setAlignment(YamlMF.Alignment.valueOrOne());
533 MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
534 MF.setHasWinCFI(YamlMF.HasWinCFI);
536 MF.setCallsEHReturn(YamlMF.CallsEHReturn);
537 MF.setCallsUnwindInit(YamlMF.CallsUnwindInit);
538 MF.setHasEHCatchret(YamlMF.HasEHCatchret);
539 MF.setHasEHScopes(YamlMF.HasEHScopes);
540 MF.setHasEHFunclets(YamlMF.HasEHFunclets);
541 MF.setIsOutlined(YamlMF.IsOutlined);
543 if (YamlMF.Legalized)
544 MF.getProperties().set(MachineFunctionProperties::Property::Legalized);
545 if (YamlMF.RegBankSelected)
546 MF.getProperties().set(
547 MachineFunctionProperties::Property::RegBankSelected);
548 if (YamlMF.Selected)
549 MF.getProperties().set(MachineFunctionProperties::Property::Selected);
550 if (YamlMF.FailedISel)
551 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
552 if (YamlMF.FailsVerification)
553 MF.getProperties().set(
554 MachineFunctionProperties::Property::FailsVerification);
555 if (YamlMF.TracksDebugUserValues)
556 MF.getProperties().set(
557 MachineFunctionProperties::Property::TracksDebugUserValues);
559 PerFunctionMIParsingState PFS(MF, SM, IRSlots, *Target);
560 if (parseRegisterInfo(PFS, YamlMF))
561 return true;
562 if (!YamlMF.Constants.empty()) {
563 auto *ConstantPool = MF.getConstantPool();
564 assert(ConstantPool && "Constant pool must be created");
565 if (initializeConstantPool(PFS, *ConstantPool, YamlMF))
566 return true;
568 if (!YamlMF.MachineMetadataNodes.empty() &&
569 parseMachineMetadataNodes(PFS, MF, YamlMF))
570 return true;
572 StringRef BlockStr = YamlMF.Body.Value.Value;
573 SMDiagnostic Error;
574 SourceMgr BlockSM;
575 BlockSM.AddNewSourceBuffer(
576 MemoryBuffer::getMemBuffer(BlockStr, "",/*RequiresNullTerminator=*/false),
577 SMLoc());
578 PFS.SM = &BlockSM;
579 if (parseMachineBasicBlockDefinitions(PFS, BlockStr, Error)) {
580 reportDiagnostic(
581 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
582 return true;
584 // Check Basic Block Section Flags.
585 if (MF.hasBBSections()) {
586 MF.assignBeginEndSections();
588 PFS.SM = &SM;
590 // Initialize the frame information after creating all the MBBs so that the
591 // MBB references in the frame information can be resolved.
592 if (initializeFrameInfo(PFS, YamlMF))
593 return true;
594 // Initialize the jump table after creating all the MBBs so that the MBB
595 // references can be resolved.
596 if (!YamlMF.JumpTableInfo.Entries.empty() &&
597 initializeJumpTableInfo(PFS, YamlMF.JumpTableInfo))
598 return true;
599 // Parse the machine instructions after creating all of the MBBs so that the
600 // parser can resolve the MBB references.
601 StringRef InsnStr = YamlMF.Body.Value.Value;
602 SourceMgr InsnSM;
603 InsnSM.AddNewSourceBuffer(
604 MemoryBuffer::getMemBuffer(InsnStr, "", /*RequiresNullTerminator=*/false),
605 SMLoc());
606 PFS.SM = &InsnSM;
607 if (parseMachineInstructions(PFS, InsnStr, Error)) {
608 reportDiagnostic(
609 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
610 return true;
612 PFS.SM = &SM;
614 if (setupRegisterInfo(PFS, YamlMF))
615 return true;
617 if (YamlMF.MachineFuncInfo) {
618 const TargetMachine &TM = MF.getTarget();
619 // Note this is called after the initial constructor of the
620 // MachineFunctionInfo based on the MachineFunction, which may depend on the
621 // IR.
623 SMRange SrcRange;
624 if (TM.parseMachineFunctionInfo(*YamlMF.MachineFuncInfo, PFS, Error,
625 SrcRange)) {
626 return error(Error, SrcRange);
630 // Set the reserved registers after parsing MachineFuncInfo. The target may
631 // have been recording information used to select the reserved registers
632 // there.
633 // FIXME: This is a temporary workaround until the reserved registers can be
634 // serialized.
635 MachineRegisterInfo &MRI = MF.getRegInfo();
636 MRI.freezeReservedRegs();
638 if (computeFunctionProperties(MF, YamlMF))
639 return true;
641 if (initializeCallSiteInfo(PFS, YamlMF))
642 return true;
644 setupDebugValueTracking(MF, PFS, YamlMF);
646 MF.getSubtarget().mirFileLoaded(MF);
648 MF.verify(nullptr, nullptr, &errs());
649 return false;
652 bool MIRParserImpl::parseRegisterInfo(PerFunctionMIParsingState &PFS,
653 const yaml::MachineFunction &YamlMF) {
654 MachineFunction &MF = PFS.MF;
655 MachineRegisterInfo &RegInfo = MF.getRegInfo();
656 assert(RegInfo.tracksLiveness());
657 if (!YamlMF.TracksRegLiveness)
658 RegInfo.invalidateLiveness();
660 SMDiagnostic Error;
661 // Parse the virtual register information.
662 for (const auto &VReg : YamlMF.VirtualRegisters) {
663 VRegInfo &Info = PFS.getVRegInfo(VReg.ID.Value);
664 if (Info.Explicit)
665 return error(VReg.ID.SourceRange.Start,
666 Twine("redefinition of virtual register '%") +
667 Twine(VReg.ID.Value) + "'");
668 Info.Explicit = true;
670 if (VReg.Class.Value == "_") {
671 Info.Kind = VRegInfo::GENERIC;
672 Info.D.RegBank = nullptr;
673 } else {
674 const auto *RC = Target->getRegClass(VReg.Class.Value);
675 if (RC) {
676 Info.Kind = VRegInfo::NORMAL;
677 Info.D.RC = RC;
678 } else {
679 const RegisterBank *RegBank = Target->getRegBank(VReg.Class.Value);
680 if (!RegBank)
681 return error(
682 VReg.Class.SourceRange.Start,
683 Twine("use of undefined register class or register bank '") +
684 VReg.Class.Value + "'");
685 Info.Kind = VRegInfo::REGBANK;
686 Info.D.RegBank = RegBank;
690 if (!VReg.PreferredRegister.Value.empty()) {
691 if (Info.Kind != VRegInfo::NORMAL)
692 return error(VReg.Class.SourceRange.Start,
693 Twine("preferred register can only be set for normal vregs"));
695 if (parseRegisterReference(PFS, Info.PreferredReg,
696 VReg.PreferredRegister.Value, Error))
697 return error(Error, VReg.PreferredRegister.SourceRange);
700 for (const auto &FlagStringValue : VReg.RegisterFlags) {
701 uint8_t FlagValue;
702 if (Target->getVRegFlagValue(FlagStringValue.Value, FlagValue))
703 return error(FlagStringValue.SourceRange.Start,
704 Twine("use of undefined register flag '") +
705 FlagStringValue.Value + "'");
706 Info.Flags |= FlagValue;
708 RegInfo.noteNewVirtualRegister(Info.VReg);
711 // Parse the liveins.
712 for (const auto &LiveIn : YamlMF.LiveIns) {
713 Register Reg;
714 if (parseNamedRegisterReference(PFS, Reg, LiveIn.Register.Value, Error))
715 return error(Error, LiveIn.Register.SourceRange);
716 Register VReg;
717 if (!LiveIn.VirtualRegister.Value.empty()) {
718 VRegInfo *Info;
719 if (parseVirtualRegisterReference(PFS, Info, LiveIn.VirtualRegister.Value,
720 Error))
721 return error(Error, LiveIn.VirtualRegister.SourceRange);
722 VReg = Info->VReg;
724 RegInfo.addLiveIn(Reg, VReg);
727 // Parse the callee saved registers (Registers that will
728 // be saved for the caller).
729 if (YamlMF.CalleeSavedRegisters) {
730 SmallVector<MCPhysReg, 16> CalleeSavedRegisters;
731 for (const auto &RegSource : *YamlMF.CalleeSavedRegisters) {
732 Register Reg;
733 if (parseNamedRegisterReference(PFS, Reg, RegSource.Value, Error))
734 return error(Error, RegSource.SourceRange);
735 CalleeSavedRegisters.push_back(Reg);
737 RegInfo.setCalleeSavedRegs(CalleeSavedRegisters);
740 return false;
743 bool MIRParserImpl::setupRegisterInfo(const PerFunctionMIParsingState &PFS,
744 const yaml::MachineFunction &YamlMF) {
745 MachineFunction &MF = PFS.MF;
746 MachineRegisterInfo &MRI = MF.getRegInfo();
747 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
749 bool Error = false;
750 // Create VRegs
751 auto populateVRegInfo = [&](const VRegInfo &Info, Twine Name) {
752 Register Reg = Info.VReg;
753 switch (Info.Kind) {
754 case VRegInfo::UNKNOWN:
755 error(Twine("Cannot determine class/bank of virtual register ") +
756 Name + " in function '" + MF.getName() + "'");
757 Error = true;
758 break;
759 case VRegInfo::NORMAL:
760 if (!Info.D.RC->isAllocatable()) {
761 error(Twine("Cannot use non-allocatable class '") +
762 TRI->getRegClassName(Info.D.RC) + "' for virtual register " +
763 Name + " in function '" + MF.getName() + "'");
764 Error = true;
765 break;
768 MRI.setRegClass(Reg, Info.D.RC);
769 if (Info.PreferredReg != 0)
770 MRI.setSimpleHint(Reg, Info.PreferredReg);
771 break;
772 case VRegInfo::GENERIC:
773 break;
774 case VRegInfo::REGBANK:
775 MRI.setRegBank(Reg, *Info.D.RegBank);
776 break;
780 for (const auto &P : PFS.VRegInfosNamed) {
781 const VRegInfo &Info = *P.second;
782 populateVRegInfo(Info, Twine(P.first()));
785 for (auto P : PFS.VRegInfos) {
786 const VRegInfo &Info = *P.second;
787 populateVRegInfo(Info, Twine(P.first));
790 // Compute MachineRegisterInfo::UsedPhysRegMask
791 for (const MachineBasicBlock &MBB : MF) {
792 // Make sure MRI knows about registers clobbered by unwinder.
793 if (MBB.isEHPad())
794 if (auto *RegMask = TRI->getCustomEHPadPreservedMask(MF))
795 MRI.addPhysRegsUsedFromRegMask(RegMask);
797 for (const MachineInstr &MI : MBB) {
798 for (const MachineOperand &MO : MI.operands()) {
799 if (!MO.isRegMask())
800 continue;
801 MRI.addPhysRegsUsedFromRegMask(MO.getRegMask());
806 return Error;
809 bool MIRParserImpl::initializeFrameInfo(PerFunctionMIParsingState &PFS,
810 const yaml::MachineFunction &YamlMF) {
811 MachineFunction &MF = PFS.MF;
812 MachineFrameInfo &MFI = MF.getFrameInfo();
813 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
814 const Function &F = MF.getFunction();
815 const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
816 MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
817 MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
818 MFI.setHasStackMap(YamlMFI.HasStackMap);
819 MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
820 MFI.setStackSize(YamlMFI.StackSize);
821 MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
822 if (YamlMFI.MaxAlignment)
823 MFI.ensureMaxAlignment(Align(YamlMFI.MaxAlignment));
824 MFI.setAdjustsStack(YamlMFI.AdjustsStack);
825 MFI.setHasCalls(YamlMFI.HasCalls);
826 if (YamlMFI.MaxCallFrameSize != ~0u)
827 MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
828 MFI.setCVBytesOfCalleeSavedRegisters(YamlMFI.CVBytesOfCalleeSavedRegisters);
829 MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
830 MFI.setHasVAStart(YamlMFI.HasVAStart);
831 MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
832 MFI.setHasTailCall(YamlMFI.HasTailCall);
833 MFI.setCalleeSavedInfoValid(YamlMFI.IsCalleeSavedInfoValid);
834 MFI.setLocalFrameSize(YamlMFI.LocalFrameSize);
835 if (!YamlMFI.SavePoint.Value.empty()) {
836 MachineBasicBlock *MBB = nullptr;
837 if (parseMBBReference(PFS, MBB, YamlMFI.SavePoint))
838 return true;
839 MFI.setSavePoint(MBB);
841 if (!YamlMFI.RestorePoint.Value.empty()) {
842 MachineBasicBlock *MBB = nullptr;
843 if (parseMBBReference(PFS, MBB, YamlMFI.RestorePoint))
844 return true;
845 MFI.setRestorePoint(MBB);
848 std::vector<CalleeSavedInfo> CSIInfo;
849 // Initialize the fixed frame objects.
850 for (const auto &Object : YamlMF.FixedStackObjects) {
851 int ObjectIdx;
852 if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
853 ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
854 Object.IsImmutable, Object.IsAliased);
855 else
856 ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
858 if (!TFI->isSupportedStackID(Object.StackID))
859 return error(Object.ID.SourceRange.Start,
860 Twine("StackID is not supported by target"));
861 MFI.setStackID(ObjectIdx, Object.StackID);
862 MFI.setObjectAlignment(ObjectIdx, Object.Alignment.valueOrOne());
863 if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
864 ObjectIdx))
865 .second)
866 return error(Object.ID.SourceRange.Start,
867 Twine("redefinition of fixed stack object '%fixed-stack.") +
868 Twine(Object.ID.Value) + "'");
869 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
870 Object.CalleeSavedRestored, ObjectIdx))
871 return true;
872 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
873 return true;
876 for (const auto &Object : YamlMF.EntryValueObjects) {
877 SMDiagnostic Error;
878 Register Reg;
879 if (parseNamedRegisterReference(PFS, Reg, Object.EntryValueRegister.Value,
880 Error))
881 return error(Error, Object.EntryValueRegister.SourceRange);
882 if (!Reg.isPhysical())
883 return error(Object.EntryValueRegister.SourceRange.Start,
884 "Expected physical register for entry value field");
885 std::optional<VarExprLoc> MaybeInfo = parseVarExprLoc(
886 PFS, Object.DebugVar, Object.DebugExpr, Object.DebugLoc);
887 if (!MaybeInfo)
888 return true;
889 if (MaybeInfo->DIVar || MaybeInfo->DIExpr || MaybeInfo->DILoc)
890 PFS.MF.setVariableDbgInfo(MaybeInfo->DIVar, MaybeInfo->DIExpr,
891 Reg.asMCReg(), MaybeInfo->DILoc);
894 // Initialize the ordinary frame objects.
895 for (const auto &Object : YamlMF.StackObjects) {
896 int ObjectIdx;
897 const AllocaInst *Alloca = nullptr;
898 const yaml::StringValue &Name = Object.Name;
899 if (!Name.Value.empty()) {
900 Alloca = dyn_cast_or_null<AllocaInst>(
901 F.getValueSymbolTable()->lookup(Name.Value));
902 if (!Alloca)
903 return error(Name.SourceRange.Start,
904 "alloca instruction named '" + Name.Value +
905 "' isn't defined in the function '" + F.getName() +
906 "'");
908 if (!TFI->isSupportedStackID(Object.StackID))
909 return error(Object.ID.SourceRange.Start,
910 Twine("StackID is not supported by target"));
911 if (Object.Type == yaml::MachineStackObject::VariableSized)
912 ObjectIdx =
913 MFI.CreateVariableSizedObject(Object.Alignment.valueOrOne(), Alloca);
914 else
915 ObjectIdx = MFI.CreateStackObject(
916 Object.Size, Object.Alignment.valueOrOne(),
917 Object.Type == yaml::MachineStackObject::SpillSlot, Alloca,
918 Object.StackID);
919 MFI.setObjectOffset(ObjectIdx, Object.Offset);
921 if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
922 .second)
923 return error(Object.ID.SourceRange.Start,
924 Twine("redefinition of stack object '%stack.") +
925 Twine(Object.ID.Value) + "'");
926 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
927 Object.CalleeSavedRestored, ObjectIdx))
928 return true;
929 if (Object.LocalOffset)
930 MFI.mapLocalFrameObject(ObjectIdx, *Object.LocalOffset);
931 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
932 return true;
934 MFI.setCalleeSavedInfo(CSIInfo);
935 if (!CSIInfo.empty())
936 MFI.setCalleeSavedInfoValid(true);
938 // Initialize the various stack object references after initializing the
939 // stack objects.
940 if (!YamlMFI.StackProtector.Value.empty()) {
941 SMDiagnostic Error;
942 int FI;
943 if (parseStackObjectReference(PFS, FI, YamlMFI.StackProtector.Value, Error))
944 return error(Error, YamlMFI.StackProtector.SourceRange);
945 MFI.setStackProtectorIndex(FI);
948 if (!YamlMFI.FunctionContext.Value.empty()) {
949 SMDiagnostic Error;
950 int FI;
951 if (parseStackObjectReference(PFS, FI, YamlMFI.FunctionContext.Value, Error))
952 return error(Error, YamlMFI.FunctionContext.SourceRange);
953 MFI.setFunctionContextIndex(FI);
956 return false;
959 bool MIRParserImpl::parseCalleeSavedRegister(PerFunctionMIParsingState &PFS,
960 std::vector<CalleeSavedInfo> &CSIInfo,
961 const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx) {
962 if (RegisterSource.Value.empty())
963 return false;
964 Register Reg;
965 SMDiagnostic Error;
966 if (parseNamedRegisterReference(PFS, Reg, RegisterSource.Value, Error))
967 return error(Error, RegisterSource.SourceRange);
968 CalleeSavedInfo CSI(Reg, FrameIdx);
969 CSI.setRestored(IsRestored);
970 CSIInfo.push_back(CSI);
971 return false;
974 /// Verify that given node is of a certain type. Return true on error.
975 template <typename T>
976 static bool typecheckMDNode(T *&Result, MDNode *Node,
977 const yaml::StringValue &Source,
978 StringRef TypeString, MIRParserImpl &Parser) {
979 if (!Node)
980 return false;
981 Result = dyn_cast<T>(Node);
982 if (!Result)
983 return Parser.error(Source.SourceRange.Start,
984 "expected a reference to a '" + TypeString +
985 "' metadata node");
986 return false;
989 std::optional<MIRParserImpl::VarExprLoc> MIRParserImpl::parseVarExprLoc(
990 PerFunctionMIParsingState &PFS, const yaml::StringValue &VarStr,
991 const yaml::StringValue &ExprStr, const yaml::StringValue &LocStr) {
992 MDNode *Var = nullptr;
993 MDNode *Expr = nullptr;
994 MDNode *Loc = nullptr;
995 if (parseMDNode(PFS, Var, VarStr) || parseMDNode(PFS, Expr, ExprStr) ||
996 parseMDNode(PFS, Loc, LocStr))
997 return std::nullopt;
998 DILocalVariable *DIVar = nullptr;
999 DIExpression *DIExpr = nullptr;
1000 DILocation *DILoc = nullptr;
1001 if (typecheckMDNode(DIVar, Var, VarStr, "DILocalVariable", *this) ||
1002 typecheckMDNode(DIExpr, Expr, ExprStr, "DIExpression", *this) ||
1003 typecheckMDNode(DILoc, Loc, LocStr, "DILocation", *this))
1004 return std::nullopt;
1005 return VarExprLoc{DIVar, DIExpr, DILoc};
1008 template <typename T>
1009 bool MIRParserImpl::parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
1010 const T &Object, int FrameIdx) {
1011 std::optional<VarExprLoc> MaybeInfo =
1012 parseVarExprLoc(PFS, Object.DebugVar, Object.DebugExpr, Object.DebugLoc);
1013 if (!MaybeInfo)
1014 return true;
1015 // Debug information can only be attached to stack objects; Fixed stack
1016 // objects aren't supported.
1017 if (MaybeInfo->DIVar || MaybeInfo->DIExpr || MaybeInfo->DILoc)
1018 PFS.MF.setVariableDbgInfo(MaybeInfo->DIVar, MaybeInfo->DIExpr, FrameIdx,
1019 MaybeInfo->DILoc);
1020 return false;
1023 bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState &PFS,
1024 MDNode *&Node, const yaml::StringValue &Source) {
1025 if (Source.Value.empty())
1026 return false;
1027 SMDiagnostic Error;
1028 if (llvm::parseMDNode(PFS, Node, Source.Value, Error))
1029 return error(Error, Source.SourceRange);
1030 return false;
1033 bool MIRParserImpl::initializeConstantPool(PerFunctionMIParsingState &PFS,
1034 MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF) {
1035 DenseMap<unsigned, unsigned> &ConstantPoolSlots = PFS.ConstantPoolSlots;
1036 const MachineFunction &MF = PFS.MF;
1037 const auto &M = *MF.getFunction().getParent();
1038 SMDiagnostic Error;
1039 for (const auto &YamlConstant : YamlMF.Constants) {
1040 if (YamlConstant.IsTargetSpecific)
1041 // FIXME: Support target-specific constant pools
1042 return error(YamlConstant.Value.SourceRange.Start,
1043 "Can't parse target-specific constant pool entries yet");
1044 const Constant *Value = dyn_cast_or_null<Constant>(
1045 parseConstantValue(YamlConstant.Value.Value, Error, M));
1046 if (!Value)
1047 return error(Error, YamlConstant.Value.SourceRange);
1048 const Align PrefTypeAlign =
1049 M.getDataLayout().getPrefTypeAlign(Value->getType());
1050 const Align Alignment = YamlConstant.Alignment.value_or(PrefTypeAlign);
1051 unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
1052 if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
1053 .second)
1054 return error(YamlConstant.ID.SourceRange.Start,
1055 Twine("redefinition of constant pool item '%const.") +
1056 Twine(YamlConstant.ID.Value) + "'");
1058 return false;
1061 bool MIRParserImpl::initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
1062 const yaml::MachineJumpTable &YamlJTI) {
1063 MachineJumpTableInfo *JTI = PFS.MF.getOrCreateJumpTableInfo(YamlJTI.Kind);
1064 for (const auto &Entry : YamlJTI.Entries) {
1065 std::vector<MachineBasicBlock *> Blocks;
1066 for (const auto &MBBSource : Entry.Blocks) {
1067 MachineBasicBlock *MBB = nullptr;
1068 if (parseMBBReference(PFS, MBB, MBBSource.Value))
1069 return true;
1070 Blocks.push_back(MBB);
1072 unsigned Index = JTI->createJumpTableIndex(Blocks);
1073 if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
1074 .second)
1075 return error(Entry.ID.SourceRange.Start,
1076 Twine("redefinition of jump table entry '%jump-table.") +
1077 Twine(Entry.ID.Value) + "'");
1079 return false;
1082 bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState &PFS,
1083 MachineBasicBlock *&MBB,
1084 const yaml::StringValue &Source) {
1085 SMDiagnostic Error;
1086 if (llvm::parseMBBReference(PFS, MBB, Source.Value, Error))
1087 return error(Error, Source.SourceRange);
1088 return false;
1091 bool MIRParserImpl::parseMachineMetadata(PerFunctionMIParsingState &PFS,
1092 const yaml::StringValue &Source) {
1093 SMDiagnostic Error;
1094 if (llvm::parseMachineMetadata(PFS, Source.Value, Source.SourceRange, Error))
1095 return error(Error, Source.SourceRange);
1096 return false;
1099 bool MIRParserImpl::parseMachineMetadataNodes(
1100 PerFunctionMIParsingState &PFS, MachineFunction &MF,
1101 const yaml::MachineFunction &YMF) {
1102 for (const auto &MDS : YMF.MachineMetadataNodes) {
1103 if (parseMachineMetadata(PFS, MDS))
1104 return true;
1106 // Report missing definitions from forward referenced nodes.
1107 if (!PFS.MachineForwardRefMDNodes.empty())
1108 return error(PFS.MachineForwardRefMDNodes.begin()->second.second,
1109 "use of undefined metadata '!" +
1110 Twine(PFS.MachineForwardRefMDNodes.begin()->first) + "'");
1111 return false;
1114 SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
1115 SMRange SourceRange) {
1116 assert(SourceRange.isValid() && "Invalid source range");
1117 SMLoc Loc = SourceRange.Start;
1118 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
1119 *Loc.getPointer() == '\'';
1120 // Translate the location of the error from the location in the MI string to
1121 // the corresponding location in the MIR file.
1122 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
1123 (HasQuote ? 1 : 0));
1125 // TODO: Translate any source ranges as well.
1126 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), {},
1127 Error.getFixIts());
1130 SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
1131 SMRange SourceRange) {
1132 assert(SourceRange.isValid());
1134 // Translate the location of the error from the location in the llvm IR string
1135 // to the corresponding location in the MIR file.
1136 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
1137 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
1138 unsigned Column = Error.getColumnNo();
1139 StringRef LineStr = Error.getLineContents();
1140 SMLoc Loc = Error.getLoc();
1142 // Get the full line and adjust the column number by taking the indentation of
1143 // LLVM IR into account.
1144 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
1145 L != E; ++L) {
1146 if (L.line_number() == Line) {
1147 LineStr = *L;
1148 Loc = SMLoc::getFromPointer(LineStr.data());
1149 auto Indent = LineStr.find(Error.getLineContents());
1150 if (Indent != StringRef::npos)
1151 Column += Indent;
1152 break;
1156 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
1157 Error.getMessage(), LineStr, Error.getRanges(),
1158 Error.getFixIts());
1161 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
1162 : Impl(std::move(Impl)) {}
1164 MIRParser::~MIRParser() = default;
1166 std::unique_ptr<Module>
1167 MIRParser::parseIRModule(DataLayoutCallbackTy DataLayoutCallback) {
1168 return Impl->parseIRModule(DataLayoutCallback);
1171 bool MIRParser::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) {
1172 return Impl->parseMachineFunctions(M, MMI);
1175 bool MIRParser::parseMachineFunctions(Module &M, ModuleAnalysisManager &MAM) {
1176 auto &MMI = MAM.getResult<MachineModuleAnalysis>(M).getMMI();
1177 return Impl->parseMachineFunctions(M, MMI, &MAM);
1180 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(
1181 StringRef Filename, SMDiagnostic &Error, LLVMContext &Context,
1182 std::function<void(Function &)> ProcessIRFunction) {
1183 auto FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true);
1184 if (std::error_code EC = FileOrErr.getError()) {
1185 Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
1186 "Could not open input file: " + EC.message());
1187 return nullptr;
1189 return createMIRParser(std::move(FileOrErr.get()), Context,
1190 ProcessIRFunction);
1193 std::unique_ptr<MIRParser>
1194 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
1195 LLVMContext &Context,
1196 std::function<void(Function &)> ProcessIRFunction) {
1197 auto Filename = Contents->getBufferIdentifier();
1198 if (Context.shouldDiscardValueNames()) {
1199 Context.diagnose(DiagnosticInfoMIRParser(
1200 DS_Error,
1201 SMDiagnostic(
1202 Filename, SourceMgr::DK_Error,
1203 "Can't read MIR with a Context that discards named Values")));
1204 return nullptr;
1206 return std::make_unique<MIRParser>(std::make_unique<MIRParserImpl>(
1207 std::move(Contents), Filename, Context, ProcessIRFunction));