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.
11//
12//===----------------------------------------------------------------------===//
13
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>
42
43using namespace llvm;
44
45namespace llvm {
46class MDNode;
47class RegisterBank;
48
49/// This class implements the parsing of LLVM IR that's embedded inside a MIR
50/// file.
51class MIRParserImpl {
52 SourceMgr SM;
53 LLVMContext &Context;
54 yaml::Input In;
55 StringRef Filename;
56 SlotMapping IRSlots;
57 std::unique_ptr<PerTargetMIParsingState> Target;
58
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;
65
66 std::function<void(Function &)> ProcessIRFunction;
67
68public:
69 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
70 LLVMContext &Context,
71 std::function<void(Function &)> ProcessIRFunction);
72
73 void reportDiagnostic(const SMDiagnostic &Diag);
74
75 /// Report an error with the given message at unknown location.
76 ///
77 /// Always returns true.
78 bool error(const Twine &Message);
79
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);
84
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);
90
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);
97
98 /// Create an empty function with the given name.
99 Function *createDummyFunction(StringRef Name, Module &M);
100
101 bool parseMachineFunctions(Module &M, MachineModuleInfo &MMI,
102 ModuleAnalysisManager *FAM = nullptr);
103
104 /// Parse the machine function in the current YAML document.
105 ///
106 ///
107 /// Return true if an error occurred.
108 bool parseMachineFunction(Module &M, MachineModuleInfo &MMI,
109 ModuleAnalysisManager *FAM,
110 Module::iterator &FirstUnvisitedFunction);
111
112 /// Initialize the machine function to the state that's described in the MIR
113 /// file.
114 ///
115 /// Return true if error occurred.
116 bool initializeMachineFunction(const yaml::MachineFunction &YamlMF,
117 MachineFunction &MF);
118
119 bool initializeCallSiteInfo(PerFunctionMIParsingState &PFS,
120 const yaml::MachineFunction &YamlMF);
121
122 bool initializePrefetchTargets(PerFunctionMIParsingState &PFS,
123 const yaml::MachineFunction &YamlMF);
124
125 bool parseRegisterInfo(PerFunctionMIParsingState &PFS,
126 const yaml::MachineFunction &YamlMF);
127
128 bool setupRegisterInfo(const PerFunctionMIParsingState &PFS,
129 const yaml::MachineFunction &YamlMF);
130
131 bool initializeFrameInfo(PerFunctionMIParsingState &PFS,
132 const yaml::MachineFunction &YamlMF);
133
134 bool initializeSaveRestorePoints(
135 PerFunctionMIParsingState &PFS,
136 const std::vector<yaml::SaveRestorePointEntry> &YamlSRPoints,
137 llvm::SaveRestorePoints &SaveRestorePoints);
138
139 bool parseCalleeSavedRegister(PerFunctionMIParsingState &PFS,
140 std::vector<CalleeSavedInfo> &CSIInfo,
141 const yaml::StringValue &RegisterSource,
142 bool IsRestored, int FrameIdx);
143
144 struct VarExprLoc {
145 DILocalVariable *DIVar = nullptr;
146 DIExpression *DIExpr = nullptr;
147 DILocation *DILoc = nullptr;
148 };
149
150 std::optional<VarExprLoc> parseVarExprLoc(PerFunctionMIParsingState &PFS,
151 const yaml::StringValue &VarStr,
152 const yaml::StringValue &ExprStr,
153 const yaml::StringValue &LocStr);
154 template <typename T>
155 bool parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
156 const T &Object,
157 int FrameIdx);
158
159 bool initializeConstantPool(PerFunctionMIParsingState &PFS,
160 MachineConstantPool &ConstantPool,
161 const yaml::MachineFunction &YamlMF);
162
163 bool initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
164 const yaml::MachineJumpTable &YamlJTI);
165
166 bool parseMachineMetadataNodes(PerFunctionMIParsingState &PFS,
167 MachineFunction &MF,
168 const yaml::MachineFunction &YMF);
169
170 bool parseCalledGlobals(PerFunctionMIParsingState &PFS, MachineFunction &MF,
171 const yaml::MachineFunction &YMF);
172
173private:
174 bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node,
175 const yaml::StringValue &Source);
176
177 bool parseMBBReference(PerFunctionMIParsingState &PFS,
178 MachineBasicBlock *&MBB,
179 const yaml::StringValue &Source);
180
181 /// Return a MIR diagnostic converted from an MI string diagnostic.
182 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
183 SMRange SourceRange);
184
185 /// Return a MIR diagnostic converted from a diagnostic located in a YAML
186 /// block scalar string.
187 SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error,
188 SMRange SourceRange);
189
190 bool computeFunctionProperties(MachineFunction &MF,
191 const yaml::MachineFunction &YamlMF);
192
193 void setupDebugValueTracking(MachineFunction &MF,
194 PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF);
195
196 bool parseMachineInst(MachineFunction &MF, yaml::MachineInstrLoc MILoc,
197 MachineInstr const *&MI);
198};
199
200} // end namespace llvm
201
202static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
203 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
204}
205
206MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
207 StringRef Filename, LLVMContext &Context,
208 std::function<void(Function &)> Callback)
209 : Context(Context),
210 In(SM.getMemoryBuffer(i: SM.AddNewSourceBuffer(F: std::move(Contents), IncludeLoc: SMLoc()))
211 ->getBuffer(),
212 nullptr, handleYAMLDiag, this),
213 Filename(Filename), ProcessIRFunction(Callback) {
214 In.setContext(&In);
215}
216
217bool MIRParserImpl::error(const Twine &Message) {
218 Context.diagnose(DI: DiagnosticInfoMIRParser(
219 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
220 return true;
221}
222
223bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
224 Context.diagnose(DI: DiagnosticInfoMIRParser(
225 DS_Error, SM.GetMessage(Loc, Kind: SourceMgr::DK_Error, Msg: Message)));
226 return true;
227}
228
229bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
230 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
231 reportDiagnostic(Diag: diagFromMIStringDiag(Error, SourceRange));
232 return true;
233}
234
235void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
236 DiagnosticSeverity Kind;
237 switch (Diag.getKind()) {
238 case SourceMgr::DK_Error:
239 Kind = DS_Error;
240 break;
241 case SourceMgr::DK_Warning:
242 Kind = DS_Warning;
243 break;
244 case SourceMgr::DK_Note:
245 Kind = DS_Note;
246 break;
247 case SourceMgr::DK_Remark:
248 llvm_unreachable("remark unexpected");
249 break;
250 }
251 Context.diagnose(DI: DiagnosticInfoMIRParser(Kind, Diag));
252}
253
254std::unique_ptr<Module>
255MIRParserImpl::parseIRModule(DataLayoutCallbackTy DataLayoutCallback) {
256 if (!In.setCurrentDocument()) {
257 if (In.error())
258 return nullptr;
259 // Create an empty module when the MIR file is empty.
260 NoMIRDocuments = true;
261 auto M = std::make_unique<Module>(args&: Filename, args&: Context);
262 if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple().str(),
263 M->getDataLayoutStr()))
264 M->setDataLayout(*LayoutOverride);
265 return M;
266 }
267
268 std::unique_ptr<Module> M;
269 // Parse the block scalar manually so that we can return unique pointer
270 // without having to go trough YAML traits.
271 if (const auto *BSN =
272 dyn_cast_or_null<yaml::BlockScalarNode>(Val: In.getCurrentNode())) {
273 SMDiagnostic Error;
274 M = parseAssembly(F: MemoryBufferRef(BSN->getValue(), Filename), Err&: Error,
275 Context, Slots: &IRSlots, DataLayoutCallback);
276 if (!M) {
277 reportDiagnostic(Diag: diagFromBlockStringDiag(Error, SourceRange: BSN->getSourceRange()));
278 return nullptr;
279 }
280 In.nextDocument();
281 if (!In.setCurrentDocument())
282 NoMIRDocuments = true;
283 } else {
284 // Create an new, empty module.
285 M = std::make_unique<Module>(args&: Filename, args&: Context);
286 if (auto LayoutOverride = DataLayoutCallback(M->getTargetTriple().str(),
287 M->getDataLayoutStr()))
288 M->setDataLayout(*LayoutOverride);
289 NoLLVMIR = true;
290 }
291 return M;
292}
293
294bool MIRParserImpl::parseMachineFunctions(Module &M, MachineModuleInfo &MMI,
295 ModuleAnalysisManager *MAM) {
296 if (NoMIRDocuments)
297 return false;
298
299 // Parse the machine functions.
300 auto FirstUnvisitedFunction = M.begin();
301 do {
302 if (parseMachineFunction(M, MMI, FAM: MAM, FirstUnvisitedFunction))
303 return true;
304 In.nextDocument();
305 } while (In.setCurrentDocument());
306
307 return false;
308}
309
310Function *MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
311 auto &Context = M.getContext();
312 Function *F =
313 Function::Create(Ty: FunctionType::get(Result: Type::getVoidTy(C&: Context), isVarArg: false),
314 Linkage: Function::ExternalLinkage, N: Name, M);
315 BasicBlock *BB = BasicBlock::Create(Context, Name: "entry", Parent: F);
316 new UnreachableInst(Context, BB);
317
318 if (ProcessIRFunction)
319 ProcessIRFunction(*F);
320
321 return F;
322}
323
324static Function *
325getNextUnusedUnnamedFunction(const Module &M,
326 Module::iterator &FirstUnvisitedFunction) {
327 for (; FirstUnvisitedFunction != M.end(); ++FirstUnvisitedFunction)
328 if (!FirstUnvisitedFunction->hasName())
329 return &*FirstUnvisitedFunction++;
330
331 return nullptr;
332}
333
334bool MIRParserImpl::parseMachineFunction(
335 Module &M, MachineModuleInfo &MMI, ModuleAnalysisManager *MAM,
336 Module::iterator &FirstUnvisitedFunction) {
337 // Parse the yaml.
338 yaml::MachineFunction YamlMF;
339 yaml::EmptyContext Ctx;
340
341 const TargetMachine &TM = MMI.getTarget();
342 YamlMF.MachineFuncInfo = std::unique_ptr<yaml::MachineFunctionInfo>(
343 TM.createDefaultFuncInfoYAML());
344
345 yaml::yamlize(io&: In, Val&: YamlMF, false, Ctx);
346 if (In.error())
347 return true;
348
349 // Search for the corresponding IR function.
350 StringRef FunctionName = YamlMF.Name;
351 Function *F = M.getFunction(Name: FunctionName);
352 if (!F) {
353 if (NoLLVMIR) {
354 F = createDummyFunction(Name: FunctionName, M);
355 } else if (!FunctionName.empty() ||
356 !(F = getNextUnusedUnnamedFunction(M, FirstUnvisitedFunction))) {
357 return error(Message: Twine("function '") + FunctionName +
358 "' isn't defined in the provided LLVM IR");
359 }
360 }
361
362 if (!MAM) {
363 if (MMI.getMachineFunction(F: *F) != nullptr)
364 return error(Message: Twine("redefinition of machine function '") + FunctionName +
365 "'");
366
367 // Create the MachineFunction.
368 MachineFunction &MF = MMI.getOrCreateMachineFunction(F&: *F);
369 if (initializeMachineFunction(YamlMF, MF))
370 return true;
371 } else {
372 auto &FAM =
373 MAM->getResult<FunctionAnalysisManagerModuleProxy>(IR&: M).getManager();
374 if (FAM.getCachedResult<MachineFunctionAnalysis>(IR&: *F))
375 return error(Message: Twine("redefinition of machine function '") + FunctionName +
376 "'");
377
378 // Create the MachineFunction.
379 MachineFunction &MF = FAM.getResult<MachineFunctionAnalysis>(IR&: *F).getMF();
380 if (initializeMachineFunction(YamlMF, MF))
381 return true;
382 }
383
384 return false;
385}
386
387static bool isSSA(const MachineFunction &MF) {
388 const MachineRegisterInfo &MRI = MF.getRegInfo();
389 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
390 Register Reg = Register::index2VirtReg(Index: I);
391 if (!MRI.hasOneDef(RegNo: Reg) && !MRI.def_empty(RegNo: Reg))
392 return false;
393
394 // Subregister defs are invalid in SSA.
395 const MachineOperand *RegDef = MRI.getOneDef(Reg);
396 if (RegDef && RegDef->getSubReg() != 0)
397 return false;
398 }
399 return true;
400}
401
402bool MIRParserImpl::computeFunctionProperties(
403 MachineFunction &MF, const yaml::MachineFunction &YamlMF) {
404 MachineFunctionProperties &Properties = MF.getProperties();
405
406 bool HasPHI = false;
407 bool HasInlineAsm = false;
408 bool HasFakeUses = false;
409 bool AllTiedOpsRewritten = true, HasTiedOps = false;
410 for (const MachineBasicBlock &MBB : MF) {
411 for (const MachineInstr &MI : MBB) {
412 if (MI.isPHI())
413 HasPHI = true;
414 if (MI.isInlineAsm())
415 HasInlineAsm = true;
416 if (MI.isFakeUse())
417 HasFakeUses = true;
418 for (unsigned I = 0; I < MI.getNumOperands(); ++I) {
419 const MachineOperand &MO = MI.getOperand(i: I);
420 if (!MO.isReg() || !MO.getReg())
421 continue;
422 unsigned DefIdx;
423 if (MO.isUse() && MI.isRegTiedToDefOperand(UseOpIdx: I, DefOpIdx: &DefIdx)) {
424 HasTiedOps = true;
425 if (MO.getReg() != MI.getOperand(i: DefIdx).getReg())
426 AllTiedOpsRewritten = false;
427 }
428 }
429 }
430 }
431
432 // Helper function to sanity-check and set properties that are computed, but
433 // may be explicitly set from the input MIR
434 auto ComputedPropertyHelper =
435 [&Properties](std::optional<bool> ExplicitProp, bool ComputedProp,
436 MachineFunctionProperties::Property P) -> bool {
437 // Prefer explicitly given values over the computed properties
438 if (ExplicitProp.value_or(u&: ComputedProp))
439 Properties.set(P);
440 else
441 Properties.reset(P);
442
443 // Check for conflict between the explicit values and the computed ones
444 return ExplicitProp && *ExplicitProp && !ComputedProp;
445 };
446
447 if (ComputedPropertyHelper(YamlMF.NoPHIs, !HasPHI,
448 MachineFunctionProperties::Property::NoPHIs)) {
449 return error(Message: MF.getName() +
450 " has explicit property NoPhi, but contains at least one PHI");
451 }
452
453 MF.setHasInlineAsm(HasInlineAsm);
454
455 if (HasTiedOps && AllTiedOpsRewritten)
456 Properties.setTiedOpsRewritten();
457
458 if (ComputedPropertyHelper(YamlMF.IsSSA, isSSA(MF),
459 MachineFunctionProperties::Property::IsSSA)) {
460 return error(Message: MF.getName() +
461 " has explicit property IsSSA, but is not valid SSA");
462 }
463
464 const MachineRegisterInfo &MRI = MF.getRegInfo();
465 if (ComputedPropertyHelper(YamlMF.NoVRegs, MRI.getNumVirtRegs() == 0,
466 MachineFunctionProperties::Property::NoVRegs)) {
467 return error(
468 Message: MF.getName() +
469 " has explicit property NoVRegs, but contains virtual registers");
470 }
471
472 // For hasFakeUses we follow similar logic to the ComputedPropertyHelper,
473 // except for caring about the inverse case only, i.e. when the property is
474 // explicitly set to false and Fake Uses are present; having HasFakeUses=true
475 // on a function without fake uses is harmless.
476 if (YamlMF.HasFakeUses && !*YamlMF.HasFakeUses && HasFakeUses)
477 return error(
478 Message: MF.getName() +
479 " has explicit property hasFakeUses=false, but contains fake uses");
480 MF.setHasFakeUses(YamlMF.HasFakeUses.value_or(u&: HasFakeUses));
481
482 return false;
483}
484
485bool MIRParserImpl::parseMachineInst(MachineFunction &MF,
486 yaml::MachineInstrLoc MILoc,
487 MachineInstr const *&MI) {
488 if (MILoc.BlockNum >= MF.size()) {
489 return error(Message: Twine(MF.getName()) +
490 Twine(" instruction block out of range.") +
491 " Unable to reference bb:" + Twine(MILoc.BlockNum));
492 }
493 auto BB = std::next(x: MF.begin(), n: MILoc.BlockNum);
494 if (MILoc.Offset >= BB->size())
495 return error(
496 Message: Twine(MF.getName()) + Twine(" instruction offset out of range.") +
497 " Unable to reference instruction at bb: " + Twine(MILoc.BlockNum) +
498 " at offset:" + Twine(MILoc.Offset));
499 MI = &*std::next(x: BB->instr_begin(), n: MILoc.Offset);
500 return false;
501}
502
503bool MIRParserImpl::initializeCallSiteInfo(
504 PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF) {
505 MachineFunction &MF = PFS.MF;
506 SMDiagnostic Error;
507 const TargetMachine &TM = MF.getTarget();
508 for (auto &YamlCSInfo : YamlMF.CallSitesInfo) {
509 yaml::MachineInstrLoc MILoc = YamlCSInfo.CallLocation;
510 const MachineInstr *CallI;
511 if (parseMachineInst(MF, MILoc, MI&: CallI))
512 return true;
513 if (!CallI->isCall(Type: MachineInstr::IgnoreBundle))
514 return error(Message: Twine(MF.getName()) +
515 Twine(" call site info should reference call "
516 "instruction. Instruction at bb:") +
517 Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset) +
518 " is not a call instruction");
519 MachineFunction::CallSiteInfo CSInfo;
520 for (auto ArgRegPair : YamlCSInfo.ArgForwardingRegs) {
521 Register Reg;
522 if (parseNamedRegisterReference(PFS, Reg, Src: ArgRegPair.Reg.Value, Error))
523 return error(Error, SourceRange: ArgRegPair.Reg.SourceRange);
524 CSInfo.ArgRegPairs.emplace_back(Args&: Reg, Args&: ArgRegPair.ArgNo);
525 }
526 if (!YamlCSInfo.CalleeTypeIds.empty()) {
527 for (auto CalleeTypeId : YamlCSInfo.CalleeTypeIds) {
528 IntegerType *Int64Ty = Type::getInt64Ty(C&: Context);
529 CSInfo.CalleeTypeIds.push_back(Elt: ConstantInt::get(Ty: Int64Ty, V: CalleeTypeId,
530 /*isSigned=*/IsSigned: false));
531 }
532 }
533
534 if (TM.Options.EmitCallSiteInfo || TM.Options.EmitCallGraphSection)
535 MF.addCallSiteInfo(CallI: &*CallI, CallInfo: std::move(CSInfo));
536 }
537
538 if (!YamlMF.CallSitesInfo.empty() &&
539 !(TM.Options.EmitCallSiteInfo || TM.Options.EmitCallGraphSection))
540 return error(Message: "call site info provided but not used");
541 return false;
542}
543
544void MIRParserImpl::setupDebugValueTracking(
545 MachineFunction &MF, PerFunctionMIParsingState &PFS,
546 const yaml::MachineFunction &YamlMF) {
547 // Compute the value of the "next instruction number" field.
548 unsigned MaxInstrNum = 0;
549 for (auto &MBB : MF)
550 for (auto &MI : MBB)
551 MaxInstrNum = std::max(a: MI.peekDebugInstrNum(), b: MaxInstrNum);
552 MF.setDebugInstrNumberingCount(MaxInstrNum);
553
554 // Load any substitutions.
555 for (const auto &Sub : YamlMF.DebugValueSubstitutions) {
556 MF.makeDebugValueSubstitution({Sub.SrcInst, Sub.SrcOp},
557 {Sub.DstInst, Sub.DstOp}, SubReg: Sub.Subreg);
558 }
559
560 // Flag for whether we're supposed to be using DBG_INSTR_REF.
561 MF.setUseDebugInstrRef(YamlMF.UseDebugInstrRef);
562}
563
564bool
565MIRParserImpl::initializeMachineFunction(const yaml::MachineFunction &YamlMF,
566 MachineFunction &MF) {
567 // TODO: Recreate the machine function.
568 if (Target) {
569 // Avoid clearing state if we're using the same subtarget again.
570 Target->setTarget(MF.getSubtarget());
571 } else {
572 Target.reset(p: new PerTargetMIParsingState(MF.getSubtarget()));
573 }
574
575 MF.setAlignment(YamlMF.Alignment.valueOrOne());
576 MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
577 MF.setHasWinCFI(YamlMF.HasWinCFI);
578
579 MF.setCallsEHReturn(YamlMF.CallsEHReturn);
580 MF.setCallsUnwindInit(YamlMF.CallsUnwindInit);
581 MF.setHasEHContTarget(YamlMF.HasEHContTarget);
582 MF.setHasEHScopes(YamlMF.HasEHScopes);
583 MF.setHasEHFunclets(YamlMF.HasEHFunclets);
584 MF.setIsOutlined(YamlMF.IsOutlined);
585
586 MachineFunctionProperties &Props = MF.getProperties();
587 if (YamlMF.Legalized)
588 Props.setLegalized();
589 if (YamlMF.RegBankSelected)
590 Props.setRegBankSelected();
591 if (YamlMF.Selected)
592 Props.setSelected();
593 if (YamlMF.FailedISel)
594 Props.setFailedISel();
595 if (YamlMF.FailsVerification)
596 Props.setFailsVerification();
597 if (YamlMF.TracksDebugUserValues)
598 Props.setTracksDebugUserValues();
599
600 PerFunctionMIParsingState PFS(MF, SM, IRSlots, *Target);
601 if (parseRegisterInfo(PFS, YamlMF))
602 return true;
603 if (initializePrefetchTargets(PFS, YamlMF))
604 return true;
605 if (!YamlMF.Constants.empty()) {
606 auto *ConstantPool = MF.getConstantPool();
607 assert(ConstantPool && "Constant pool must be created");
608 if (initializeConstantPool(PFS, ConstantPool&: *ConstantPool, YamlMF))
609 return true;
610 }
611 if (!YamlMF.MachineMetadataNodes.empty() &&
612 parseMachineMetadataNodes(PFS, MF, YMF: YamlMF))
613 return true;
614
615 StringRef BlockStr = YamlMF.Body.Value.Value;
616 SMDiagnostic Error;
617 SourceMgr BlockSM;
618 BlockSM.AddNewSourceBuffer(
619 F: MemoryBuffer::getMemBuffer(InputData: BlockStr, BufferName: "",/*RequiresNullTerminator=*/false),
620 IncludeLoc: SMLoc());
621 PFS.SM = &BlockSM;
622 if (parseMachineBasicBlockDefinitions(PFS, Src: BlockStr, Error)) {
623 reportDiagnostic(
624 Diag: diagFromBlockStringDiag(Error, SourceRange: YamlMF.Body.Value.SourceRange));
625 return true;
626 }
627 // Check Basic Block Section Flags.
628 if (MF.hasBBSections()) {
629 MF.assignBeginEndSections();
630 }
631 PFS.SM = &SM;
632
633 // Initialize the frame information after creating all the MBBs so that the
634 // MBB references in the frame information can be resolved.
635 if (initializeFrameInfo(PFS, YamlMF))
636 return true;
637 // Initialize the jump table after creating all the MBBs so that the MBB
638 // references can be resolved.
639 if (!YamlMF.JumpTableInfo.Entries.empty() &&
640 initializeJumpTableInfo(PFS, YamlJTI: YamlMF.JumpTableInfo))
641 return true;
642 // Parse the machine instructions after creating all of the MBBs so that the
643 // parser can resolve the MBB references.
644 StringRef InsnStr = YamlMF.Body.Value.Value;
645 SourceMgr InsnSM;
646 InsnSM.AddNewSourceBuffer(
647 F: MemoryBuffer::getMemBuffer(InputData: InsnStr, BufferName: "", /*RequiresNullTerminator=*/false),
648 IncludeLoc: SMLoc());
649 PFS.SM = &InsnSM;
650 if (parseMachineInstructions(PFS, Src: InsnStr, Error)) {
651 reportDiagnostic(
652 Diag: diagFromBlockStringDiag(Error, SourceRange: YamlMF.Body.Value.SourceRange));
653 return true;
654 }
655 PFS.SM = &SM;
656
657 if (setupRegisterInfo(PFS, YamlMF))
658 return true;
659
660 if (YamlMF.MachineFuncInfo) {
661 const TargetMachine &TM = MF.getTarget();
662 // Note this is called after the initial constructor of the
663 // MachineFunctionInfo based on the MachineFunction, which may depend on the
664 // IR.
665
666 SMRange SrcRange;
667 if (TM.parseMachineFunctionInfo(*YamlMF.MachineFuncInfo, PFS, Error,
668 SourceRange&: SrcRange)) {
669 return error(Error, SourceRange: SrcRange);
670 }
671 }
672
673 // Set the reserved registers after parsing MachineFuncInfo. The target may
674 // have been recording information used to select the reserved registers
675 // there.
676 // FIXME: This is a temporary workaround until the reserved registers can be
677 // serialized.
678 MachineRegisterInfo &MRI = MF.getRegInfo();
679 MRI.freezeReservedRegs();
680
681 if (computeFunctionProperties(MF, YamlMF))
682 return true;
683
684 if (initializeCallSiteInfo(PFS, YamlMF))
685 return true;
686
687 if (parseCalledGlobals(PFS, MF, YMF: YamlMF))
688 return true;
689
690 if (initializePrefetchTargets(PFS, YamlMF))
691 return true;
692
693 setupDebugValueTracking(MF, PFS, YamlMF);
694
695 MF.getSubtarget().mirFileLoaded(MF);
696
697 MF.verify(p: nullptr, Banner: nullptr, OS: &errs());
698 return false;
699}
700
701bool MIRParserImpl::initializePrefetchTargets(
702 PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF) {
703 MachineFunction &MF = PFS.MF;
704 SMDiagnostic Error;
705 DenseMap<UniqueBBID, SmallVector<unsigned>> Targets;
706 for (const auto &YamlTarget : YamlMF.PrefetchTargets) {
707 CallsiteID Target;
708 if (llvm::parsePrefetchTarget(PFS, Target, Src: YamlTarget.Value, Error))
709 return error(Error, SourceRange: YamlTarget.SourceRange);
710 Targets[Target.BBID].push_back(Elt: Target.CallsiteIndex);
711 }
712 MF.setPrefetchTargets(Targets);
713 return false;
714}
715
716bool MIRParserImpl::parseRegisterInfo(PerFunctionMIParsingState &PFS,
717 const yaml::MachineFunction &YamlMF) {
718 MachineFunction &MF = PFS.MF;
719 MachineRegisterInfo &RegInfo = MF.getRegInfo();
720 assert(RegInfo.tracksLiveness());
721 if (!YamlMF.TracksRegLiveness)
722 RegInfo.invalidateLiveness();
723
724 SMDiagnostic Error;
725 // Parse the virtual register information.
726 for (const auto &VReg : YamlMF.VirtualRegisters) {
727 VRegInfo &Info = PFS.getVRegInfo(Num: VReg.ID.Value);
728 if (Info.Explicit)
729 return error(Loc: VReg.ID.SourceRange.Start,
730 Message: Twine("redefinition of virtual register '%") +
731 Twine(VReg.ID.Value) + "'");
732 Info.Explicit = true;
733
734 if (VReg.Class.Value == "_") {
735 Info.Kind = VRegInfo::GENERIC;
736 Info.D.RegBank = nullptr;
737 } else {
738 const auto *RC = Target->getRegClass(Name: VReg.Class.Value);
739 if (RC) {
740 Info.Kind = VRegInfo::NORMAL;
741 Info.D.RC = RC;
742 } else {
743 const RegisterBank *RegBank = Target->getRegBank(Name: VReg.Class.Value);
744 if (!RegBank)
745 return error(
746 Loc: VReg.Class.SourceRange.Start,
747 Message: Twine("use of undefined register class or register bank '") +
748 VReg.Class.Value + "'");
749 Info.Kind = VRegInfo::REGBANK;
750 Info.D.RegBank = RegBank;
751 }
752 }
753
754 if (!VReg.PreferredRegister.Value.empty()) {
755 if (Info.Kind != VRegInfo::NORMAL)
756 return error(Loc: VReg.Class.SourceRange.Start,
757 Message: Twine("preferred register can only be set for normal vregs"));
758
759 if (parseRegisterReference(PFS, Reg&: Info.PreferredReg,
760 Src: VReg.PreferredRegister.Value, Error))
761 return error(Error, SourceRange: VReg.PreferredRegister.SourceRange);
762 }
763
764 for (const auto &FlagStringValue : VReg.RegisterFlags) {
765 uint8_t FlagValue;
766 if (Target->getVRegFlagValue(FlagName: FlagStringValue.Value, FlagValue))
767 return error(Loc: FlagStringValue.SourceRange.Start,
768 Message: Twine("use of undefined register flag '") +
769 FlagStringValue.Value + "'");
770 Info.Flags |= FlagValue;
771 }
772 if (!VReg.AntiHints.empty() && Info.Kind != VRegInfo::NORMAL)
773 return error(Loc: VReg.AntiHints.front().SourceRange.Start,
774 Message: "anti-hints can only be set for normal vregs");
775
776 for (const auto &AntiHintValue : VReg.AntiHints) {
777 Register AntiHintReg;
778 if (parseRegisterReference(PFS, Reg&: AntiHintReg, Src: AntiHintValue.Value, Error))
779 return error(Error, SourceRange: AntiHintValue.SourceRange);
780
781 if (!AntiHintReg.isVirtual()) {
782 return error(Loc: AntiHintValue.SourceRange.Start,
783 Message: "anti-hint '" + Twine(AntiHintValue.Value) +
784 "' must be a virtual register");
785 }
786
787 Info.AntiHints.push_back(Elt: AntiHintReg);
788 }
789 RegInfo.noteNewVirtualRegister(Reg: Info.VReg);
790 }
791
792 // Parse the liveins.
793 for (const auto &LiveIn : YamlMF.LiveIns) {
794 Register Reg;
795 if (parseNamedRegisterReference(PFS, Reg, Src: LiveIn.Register.Value, Error))
796 return error(Error, SourceRange: LiveIn.Register.SourceRange);
797 Register VReg;
798 if (!LiveIn.VirtualRegister.Value.empty()) {
799 VRegInfo *Info;
800 if (parseVirtualRegisterReference(PFS, Info, Src: LiveIn.VirtualRegister.Value,
801 Error))
802 return error(Error, SourceRange: LiveIn.VirtualRegister.SourceRange);
803 VReg = Info->VReg;
804 }
805 RegInfo.addLiveIn(Reg, vreg: VReg);
806 }
807
808 // Parse the callee saved registers (Registers that will
809 // be saved for the caller).
810 if (YamlMF.CalleeSavedRegisters) {
811 SmallVector<MCPhysReg, 16> CalleeSavedRegisters;
812 for (const auto &RegSource : *YamlMF.CalleeSavedRegisters) {
813 Register Reg;
814 if (parseNamedRegisterReference(PFS, Reg, Src: RegSource.Value, Error))
815 return error(Error, SourceRange: RegSource.SourceRange);
816 CalleeSavedRegisters.push_back(Elt: Reg.id());
817 }
818 RegInfo.setCalleeSavedRegs(CalleeSavedRegisters);
819 }
820
821 // Stash any VirtRegMap state on MRI.
822 // VirtRegMap::init() will use that information to get pre-populated
823 // on the first analysis run.
824 for (const auto &VReg : YamlMF.VirtualRegisters) {
825 if (VReg.SplitFrom.Value.empty() && VReg.AssignedPhys.Value.empty())
826 continue;
827
828 auto It = PFS.VRegInfos.find(Val: VReg.ID.Value);
829 if (It == PFS.VRegInfos.end())
830 continue;
831 Register ChildReg = It->second->VReg;
832
833 MachineRegisterInfo::PendingVirtRegMapEntry Pending;
834 Pending.VReg = ChildReg;
835
836 if (!VReg.SplitFrom.Value.empty()) {
837 VRegInfo *Parent = nullptr;
838 if (parseVirtualRegisterReference(PFS, Info&: Parent, Src: VReg.SplitFrom.Value,
839 Error))
840 return error(Error, SourceRange: VReg.SplitFrom.SourceRange);
841 if (Parent->VReg == ChildReg)
842 return error(Loc: VReg.SplitFrom.SourceRange.Start,
843 Message: Twine("'split-from' references the same vreg as 'id' (%") +
844 Twine(VReg.ID.Value) + ")");
845 Pending.SplitFrom = Parent->VReg;
846 }
847 if (!VReg.AssignedPhys.Value.empty()) {
848 Register Phys;
849 if (parseRegisterReference(PFS, Reg&: Phys, Src: VReg.AssignedPhys.Value, Error))
850 return error(Error, SourceRange: VReg.AssignedPhys.SourceRange);
851 if (!Phys.isPhysical())
852 return error(
853 Loc: VReg.AssignedPhys.SourceRange.Start,
854 Message: Twine("'assigned-phys' must be a physical register, got '") +
855 VReg.AssignedPhys.Value + "'");
856 Pending.AssignedPhys = Phys.asMCReg();
857 }
858 RegInfo.addPendingVirtRegMapEntry(Entry: Pending);
859 }
860
861 return false;
862}
863
864bool MIRParserImpl::setupRegisterInfo(const PerFunctionMIParsingState &PFS,
865 const yaml::MachineFunction &YamlMF) {
866 MachineFunction &MF = PFS.MF;
867 MachineRegisterInfo &MRI = MF.getRegInfo();
868 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
869
870 SmallVector<std::string> Errors;
871
872 // Create VRegs
873 auto populateVRegInfo = [&](const VRegInfo &Info, const Twine &Name) {
874 Register Reg = Info.VReg;
875 switch (Info.Kind) {
876 case VRegInfo::UNKNOWN:
877 Errors.push_back(
878 Elt: (Twine("Cannot determine class/bank of virtual register ") + Name +
879 " in function '" + MF.getName() + "'")
880 .str());
881 break;
882 case VRegInfo::NORMAL:
883 if (!Info.D.RC->isAllocatable()) {
884 Errors.push_back(Elt: (Twine("Cannot use non-allocatable class '") +
885 TRI->getRegClassName(Class: Info.D.RC) +
886 "' for virtual register " + Name + " in function '" +
887 MF.getName() + "'")
888 .str());
889 break;
890 }
891
892 MRI.setRegClass(Reg, RC: Info.D.RC);
893 if (Info.PreferredReg != 0)
894 MRI.setSimpleHint(VReg: Reg, PrefReg: Info.PreferredReg);
895 if (!Info.AntiHints.empty())
896 MRI.addRegAllocationAntiHints(VReg: Reg, AntiHintVRegs: Info.AntiHints);
897 break;
898 case VRegInfo::GENERIC:
899 break;
900 case VRegInfo::REGBANK:
901 MRI.setRegBank(Reg, RegBank: *Info.D.RegBank);
902 break;
903 }
904 };
905
906 for (const auto &P : PFS.VRegInfosNamed) {
907 const VRegInfo &Info = *P.second;
908 populateVRegInfo(Info, Twine(P.first()));
909 }
910
911 for (auto P : PFS.VRegInfos) {
912 const VRegInfo &Info = *P.second;
913 populateVRegInfo(Info, Twine(P.first.id()));
914 }
915
916 // Compute MachineRegisterInfo::UsedPhysRegMask
917 for (const MachineBasicBlock &MBB : MF) {
918 // Make sure MRI knows about registers clobbered by unwinder.
919 if (MBB.isEHPad())
920 if (auto *RegMask = TRI->getCustomEHPadPreservedMask(MF))
921 MRI.addPhysRegsUsedFromRegMask(RegMask);
922
923 for (const MachineInstr &MI : MBB) {
924 for (const MachineOperand &MO : MI.operands()) {
925 if (!MO.isRegMask())
926 continue;
927 MRI.addPhysRegsUsedFromRegMask(RegMask: MO.getRegMask());
928 }
929 }
930 }
931
932 if (Errors.empty())
933 return false;
934
935 // Report errors in a deterministic order.
936 sort(C&: Errors);
937 for (auto &E : Errors)
938 error(Message: E);
939 return true;
940}
941
942bool MIRParserImpl::initializeFrameInfo(PerFunctionMIParsingState &PFS,
943 const yaml::MachineFunction &YamlMF) {
944 MachineFunction &MF = PFS.MF;
945 MachineFrameInfo &MFI = MF.getFrameInfo();
946 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
947 const Function &F = MF.getFunction();
948 const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
949 MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
950 MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
951 MFI.setHasStackMap(YamlMFI.HasStackMap);
952 MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
953 MFI.setStackSize(YamlMFI.StackSize);
954 MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
955 if (YamlMFI.MaxAlignment)
956 MFI.ensureMaxAlignment(Alignment: Align(YamlMFI.MaxAlignment));
957 MFI.setAdjustsStack(YamlMFI.AdjustsStack);
958 MFI.setHasCalls(YamlMFI.HasCalls);
959 if (YamlMFI.FramePointerPolicy != FramePointerKind::None)
960 MFI.setFramePointerPolicy(YamlMFI.FramePointerPolicy);
961 if (YamlMFI.MaxCallFrameSize != ~0u)
962 MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
963 MFI.setCVBytesOfCalleeSavedRegisters(YamlMFI.CVBytesOfCalleeSavedRegisters);
964 MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
965 MFI.setHasVAStart(YamlMFI.HasVAStart);
966 MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
967 MFI.setHasTailCall(YamlMFI.HasTailCall);
968 MFI.setCalleeSavedInfoValid(YamlMFI.IsCalleeSavedInfoValid);
969 MFI.setLocalFrameSize(YamlMFI.LocalFrameSize);
970 llvm::SaveRestorePoints SavePoints;
971 if (initializeSaveRestorePoints(PFS, YamlSRPoints: YamlMFI.SavePoints, SaveRestorePoints&: SavePoints))
972 return true;
973 MFI.setSavePoints(SavePoints);
974 llvm::SaveRestorePoints RestorePoints;
975 if (initializeSaveRestorePoints(PFS, YamlSRPoints: YamlMFI.RestorePoints, SaveRestorePoints&: RestorePoints))
976 return true;
977 MFI.setRestorePoints(RestorePoints);
978
979 std::vector<CalleeSavedInfo> CSIInfo;
980 // Initialize the fixed frame objects.
981 for (const auto &Object : YamlMF.FixedStackObjects) {
982 int ObjectIdx;
983 if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
984 ObjectIdx = MFI.CreateFixedObject(Size: Object.Size, SPOffset: Object.Offset,
985 IsImmutable: Object.IsImmutable, isAliased: Object.IsAliased);
986 else
987 ObjectIdx = MFI.CreateFixedSpillStackObject(Size: Object.Size, SPOffset: Object.Offset);
988
989 if (!TFI->isSupportedStackID(ID: Object.StackID))
990 return error(Loc: Object.ID.SourceRange.Start,
991 Message: Twine("StackID is not supported by target"));
992 MFI.setStackID(ObjectIdx, ID: Object.StackID);
993 MFI.setObjectAlignment(ObjectIdx, Alignment: Object.Alignment.valueOrOne());
994 if (!PFS.FixedStackObjectSlots.insert(KV: std::make_pair(x: Object.ID.Value,
995 y&: ObjectIdx))
996 .second)
997 return error(Loc: Object.ID.SourceRange.Start,
998 Message: Twine("redefinition of fixed stack object '%fixed-stack.") +
999 Twine(Object.ID.Value) + "'");
1000 if (parseCalleeSavedRegister(PFS, CSIInfo, RegisterSource: Object.CalleeSavedRegister,
1001 IsRestored: Object.CalleeSavedRestored, FrameIdx: ObjectIdx))
1002 return true;
1003 if (parseStackObjectsDebugInfo(PFS, Object, FrameIdx: ObjectIdx))
1004 return true;
1005 }
1006
1007 for (const auto &Object : YamlMF.EntryValueObjects) {
1008 SMDiagnostic Error;
1009 Register Reg;
1010 if (parseNamedRegisterReference(PFS, Reg, Src: Object.EntryValueRegister.Value,
1011 Error))
1012 return error(Error, SourceRange: Object.EntryValueRegister.SourceRange);
1013 if (!Reg.isPhysical())
1014 return error(Loc: Object.EntryValueRegister.SourceRange.Start,
1015 Message: "Expected physical register for entry value field");
1016 std::optional<VarExprLoc> MaybeInfo = parseVarExprLoc(
1017 PFS, VarStr: Object.DebugVar, ExprStr: Object.DebugExpr, LocStr: Object.DebugLoc);
1018 if (!MaybeInfo)
1019 return true;
1020 if (MaybeInfo->DIVar || MaybeInfo->DIExpr || MaybeInfo->DILoc)
1021 PFS.MF.setVariableDbgInfo(Var: MaybeInfo->DIVar, Expr: MaybeInfo->DIExpr,
1022 Reg: Reg.asMCReg(), Loc: MaybeInfo->DILoc);
1023 }
1024
1025 // Initialize the ordinary frame objects.
1026 for (const auto &Object : YamlMF.StackObjects) {
1027 int ObjectIdx;
1028 const AllocaInst *Alloca = nullptr;
1029 const yaml::StringValue &Name = Object.Name;
1030 if (!Name.Value.empty()) {
1031 Alloca = dyn_cast_or_null<AllocaInst>(
1032 Val: F.getValueSymbolTable()->lookup(Name: Name.Value));
1033 if (!Alloca)
1034 return error(Loc: Name.SourceRange.Start,
1035 Message: "alloca instruction named '" + Name.Value +
1036 "' isn't defined in the function '" + F.getName() +
1037 "'");
1038 }
1039 if (!TFI->isSupportedStackID(ID: Object.StackID))
1040 return error(Loc: Object.ID.SourceRange.Start,
1041 Message: Twine("StackID is not supported by target"));
1042 if (Object.Type == yaml::MachineStackObject::VariableSized)
1043 ObjectIdx =
1044 MFI.CreateVariableSizedObject(Alignment: Object.Alignment.valueOrOne(), Alloca);
1045 else
1046 ObjectIdx = MFI.CreateStackObject(
1047 Size: Object.Size, Alignment: Object.Alignment.valueOrOne(),
1048 isSpillSlot: Object.Type == yaml::MachineStackObject::SpillSlot, Alloca,
1049 ID: Object.StackID);
1050 MFI.setObjectOffset(ObjectIdx, SPOffset: Object.Offset);
1051
1052 if (!PFS.StackObjectSlots.insert(KV: std::make_pair(x: Object.ID.Value, y&: ObjectIdx))
1053 .second)
1054 return error(Loc: Object.ID.SourceRange.Start,
1055 Message: Twine("redefinition of stack object '%stack.") +
1056 Twine(Object.ID.Value) + "'");
1057 if (parseCalleeSavedRegister(PFS, CSIInfo, RegisterSource: Object.CalleeSavedRegister,
1058 IsRestored: Object.CalleeSavedRestored, FrameIdx: ObjectIdx))
1059 return true;
1060 if (Object.LocalOffset)
1061 MFI.mapLocalFrameObject(ObjectIndex: ObjectIdx, Offset: *Object.LocalOffset);
1062 if (parseStackObjectsDebugInfo(PFS, Object, FrameIdx: ObjectIdx))
1063 return true;
1064 }
1065 MFI.setCalleeSavedInfo(CSIInfo);
1066 if (!CSIInfo.empty())
1067 MFI.setCalleeSavedInfoValid(true);
1068
1069 // Initialize the various stack object references after initializing the
1070 // stack objects.
1071 if (!YamlMFI.StackProtector.Value.empty()) {
1072 SMDiagnostic Error;
1073 int FI;
1074 if (parseStackObjectReference(PFS, FI, Src: YamlMFI.StackProtector.Value, Error))
1075 return error(Error, SourceRange: YamlMFI.StackProtector.SourceRange);
1076 MFI.setStackProtectorIndex(FI);
1077 }
1078
1079 if (!YamlMFI.FunctionContext.Value.empty()) {
1080 SMDiagnostic Error;
1081 int FI;
1082 if (parseStackObjectReference(PFS, FI, Src: YamlMFI.FunctionContext.Value, Error))
1083 return error(Error, SourceRange: YamlMFI.FunctionContext.SourceRange);
1084 MFI.setFunctionContextIndex(FI);
1085 }
1086
1087 return false;
1088}
1089
1090bool MIRParserImpl::parseCalleeSavedRegister(PerFunctionMIParsingState &PFS,
1091 std::vector<CalleeSavedInfo> &CSIInfo,
1092 const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx) {
1093 if (RegisterSource.Value.empty())
1094 return false;
1095 Register Reg;
1096 SMDiagnostic Error;
1097 if (parseNamedRegisterReference(PFS, Reg, Src: RegisterSource.Value, Error))
1098 return error(Error, SourceRange: RegisterSource.SourceRange);
1099 CalleeSavedInfo CSI(Reg, FrameIdx);
1100 CSI.setRestored(IsRestored);
1101 CSIInfo.push_back(x: CSI);
1102 return false;
1103}
1104
1105/// Verify that given node is of a certain type. Return true on error.
1106template <typename T>
1107static bool typecheckMDNode(T *&Result, MDNode *Node,
1108 const yaml::StringValue &Source,
1109 StringRef TypeString, MIRParserImpl &Parser) {
1110 if (!Node)
1111 return false;
1112 Result = dyn_cast<T>(Node);
1113 if (!Result)
1114 return Parser.error(Loc: Source.SourceRange.Start,
1115 Message: "expected a reference to a '" + TypeString +
1116 "' metadata node");
1117 return false;
1118}
1119
1120std::optional<MIRParserImpl::VarExprLoc> MIRParserImpl::parseVarExprLoc(
1121 PerFunctionMIParsingState &PFS, const yaml::StringValue &VarStr,
1122 const yaml::StringValue &ExprStr, const yaml::StringValue &LocStr) {
1123 MDNode *Var = nullptr;
1124 MDNode *Expr = nullptr;
1125 MDNode *Loc = nullptr;
1126 if (parseMDNode(PFS, Node&: Var, Source: VarStr) || parseMDNode(PFS, Node&: Expr, Source: ExprStr) ||
1127 parseMDNode(PFS, Node&: Loc, Source: LocStr))
1128 return std::nullopt;
1129 DILocalVariable *DIVar = nullptr;
1130 DIExpression *DIExpr = nullptr;
1131 DILocation *DILoc = nullptr;
1132 if (typecheckMDNode(Result&: DIVar, Node: Var, Source: VarStr, TypeString: "DILocalVariable", Parser&: *this) ||
1133 typecheckMDNode(Result&: DIExpr, Node: Expr, Source: ExprStr, TypeString: "DIExpression", Parser&: *this) ||
1134 typecheckMDNode(Result&: DILoc, Node: Loc, Source: LocStr, TypeString: "DILocation", Parser&: *this))
1135 return std::nullopt;
1136 return VarExprLoc{.DIVar: DIVar, .DIExpr: DIExpr, .DILoc: DILoc};
1137}
1138
1139template <typename T>
1140bool MIRParserImpl::parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
1141 const T &Object, int FrameIdx) {
1142 std::optional<VarExprLoc> MaybeInfo =
1143 parseVarExprLoc(PFS, VarStr: Object.DebugVar, ExprStr: Object.DebugExpr, LocStr: Object.DebugLoc);
1144 if (!MaybeInfo)
1145 return true;
1146 // Debug information can only be attached to stack objects; Fixed stack
1147 // objects aren't supported.
1148 if (MaybeInfo->DIVar || MaybeInfo->DIExpr || MaybeInfo->DILoc)
1149 PFS.MF.setVariableDbgInfo(Var: MaybeInfo->DIVar, Expr: MaybeInfo->DIExpr, Slot: FrameIdx,
1150 Loc: MaybeInfo->DILoc);
1151 return false;
1152}
1153
1154bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState &PFS,
1155 MDNode *&Node, const yaml::StringValue &Source) {
1156 if (Source.Value.empty())
1157 return false;
1158 SMDiagnostic Error;
1159 if (llvm::parseMDNode(PFS, Node, Src: Source.Value, Error))
1160 return error(Error, SourceRange: Source.SourceRange);
1161 return false;
1162}
1163
1164bool MIRParserImpl::initializeConstantPool(PerFunctionMIParsingState &PFS,
1165 MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF) {
1166 DenseMap<unsigned, unsigned> &ConstantPoolSlots = PFS.ConstantPoolSlots;
1167 const MachineFunction &MF = PFS.MF;
1168 const auto &M = *MF.getFunction().getParent();
1169 SMDiagnostic Error;
1170 for (const auto &YamlConstant : YamlMF.Constants) {
1171 if (YamlConstant.IsTargetSpecific)
1172 // FIXME: Support target-specific constant pools
1173 return error(Loc: YamlConstant.Value.SourceRange.Start,
1174 Message: "Can't parse target-specific constant pool entries yet");
1175 const Constant *Value = dyn_cast_or_null<Constant>(
1176 Val: parseConstantValue(Asm: YamlConstant.Value.Value, Err&: Error, M));
1177 if (!Value)
1178 return error(Error, SourceRange: YamlConstant.Value.SourceRange);
1179 const Align PrefTypeAlign =
1180 M.getDataLayout().getPrefTypeAlign(Ty: Value->getType());
1181 const Align Alignment = YamlConstant.Alignment.value_or(u: PrefTypeAlign);
1182 unsigned Index = ConstantPool.getConstantPoolIndex(C: Value, Alignment);
1183 if (!ConstantPoolSlots.insert(KV: std::make_pair(x: YamlConstant.ID.Value, y&: Index))
1184 .second)
1185 return error(Loc: YamlConstant.ID.SourceRange.Start,
1186 Message: Twine("redefinition of constant pool item '%const.") +
1187 Twine(YamlConstant.ID.Value) + "'");
1188 }
1189 return false;
1190}
1191
1192// Return true if basic block was incorrectly specified in MIR
1193bool MIRParserImpl::initializeSaveRestorePoints(
1194 PerFunctionMIParsingState &PFS,
1195 const std::vector<yaml::SaveRestorePointEntry> &YamlSRPoints,
1196 llvm::SaveRestorePoints &SaveRestorePoints) {
1197 SMDiagnostic Error;
1198 MachineBasicBlock *MBB = nullptr;
1199 for (const yaml::SaveRestorePointEntry &Entry : YamlSRPoints) {
1200 if (parseMBBReference(PFS, MBB, Source: Entry.Point.Value))
1201 return true;
1202
1203 std::vector<CalleeSavedInfo> Registers;
1204 for (auto &RegStr : Entry.Registers) {
1205 Register Reg;
1206 if (parseNamedRegisterReference(PFS, Reg, Src: RegStr.Value, Error))
1207 return error(Error, SourceRange: RegStr.SourceRange);
1208 Registers.push_back(x: CalleeSavedInfo(Reg));
1209 }
1210 SaveRestorePoints.try_emplace(Key: MBB, Args: std::move(Registers));
1211 }
1212 return false;
1213}
1214
1215bool MIRParserImpl::initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
1216 const yaml::MachineJumpTable &YamlJTI) {
1217 MachineJumpTableInfo *JTI = PFS.MF.getOrCreateJumpTableInfo(JTEntryKind: YamlJTI.Kind);
1218 for (const auto &Entry : YamlJTI.Entries) {
1219 std::vector<MachineBasicBlock *> Blocks;
1220 for (const auto &MBBSource : Entry.Blocks) {
1221 MachineBasicBlock *MBB = nullptr;
1222 if (parseMBBReference(PFS, MBB, Source: MBBSource.Value))
1223 return true;
1224 Blocks.push_back(x: MBB);
1225 }
1226 unsigned Index = JTI->createJumpTableIndex(DestBBs: Blocks);
1227 if (!PFS.JumpTableSlots.insert(KV: std::make_pair(x: Entry.ID.Value, y&: Index))
1228 .second)
1229 return error(Loc: Entry.ID.SourceRange.Start,
1230 Message: Twine("redefinition of jump table entry '%jump-table.") +
1231 Twine(Entry.ID.Value) + "'");
1232 }
1233 return false;
1234}
1235
1236bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState &PFS,
1237 MachineBasicBlock *&MBB,
1238 const yaml::StringValue &Source) {
1239 SMDiagnostic Error;
1240 if (llvm::parseMBBReference(PFS, MBB, Src: Source.Value, Error))
1241 return error(Error, SourceRange: Source.SourceRange);
1242 return false;
1243}
1244
1245bool MIRParserImpl::parseMachineMetadataNodes(
1246 PerFunctionMIParsingState &PFS, MachineFunction &MF,
1247 const yaml::MachineFunction &YMF) {
1248 SmallVector<StringRef> Definitions;
1249 for (const auto &MDS : YMF.MachineMetadataNodes)
1250 Definitions.push_back(Elt: MDS.Value);
1251
1252 SlotMapping Slots = PFS.IRSlots;
1253 SMDiagnostic Error;
1254 unsigned ErrorDefinitionIndex = 0;
1255 if (parseMetadataDefinitions(Definitions, Err&: Error,
1256 M: *MF.getFunction().getParent(), Slots,
1257 ErrorDefinitionIndex)) {
1258 const yaml::StringValue &Source =
1259 YMF.MachineMetadataNodes[ErrorDefinitionIndex];
1260 if (StringRef(Source.Value).contains(C: '\n')) {
1261 reportDiagnostic(Diag: diagFromBlockStringDiag(Error, SourceRange: Source.SourceRange));
1262 return true;
1263 }
1264 return error(Error, SourceRange: Source.SourceRange);
1265 }
1266
1267 for (auto &[ID, MD] : Slots.MetadataNodes)
1268 if (PFS.IRSlots.MetadataNodes.find(x: ID) == PFS.IRSlots.MetadataNodes.end())
1269 PFS.MachineMetadataNodes.try_emplace(k: ID, args&: MD);
1270 return false;
1271}
1272
1273bool MIRParserImpl::parseCalledGlobals(PerFunctionMIParsingState &PFS,
1274 MachineFunction &MF,
1275 const yaml::MachineFunction &YMF) {
1276 Function &F = MF.getFunction();
1277 for (const auto &YamlCG : YMF.CalledGlobals) {
1278 yaml::MachineInstrLoc MILoc = YamlCG.CallSite;
1279 const MachineInstr *CallI;
1280 if (parseMachineInst(MF, MILoc, MI&: CallI))
1281 return true;
1282 if (!CallI->isCall(Type: MachineInstr::IgnoreBundle))
1283 return error(Message: Twine(MF.getName()) +
1284 Twine(" called global should reference call "
1285 "instruction. Instruction at bb:") +
1286 Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset) +
1287 " is not a call instruction");
1288
1289 auto Callee =
1290 F.getParent()->getValueSymbolTable().lookup(Name: YamlCG.Callee.Value);
1291 if (!Callee)
1292 return error(Loc: YamlCG.Callee.SourceRange.Start,
1293 Message: "use of undefined global '" + YamlCG.Callee.Value + "'");
1294 if (!isa<GlobalValue>(Val: Callee))
1295 return error(Loc: YamlCG.Callee.SourceRange.Start,
1296 Message: "use of non-global value '" + YamlCG.Callee.Value + "'");
1297
1298 MF.addCalledGlobal(MI: CallI, Details: {.Callee: cast<GlobalValue>(Val: Callee), .TargetFlags: YamlCG.Flags});
1299 }
1300
1301 return false;
1302}
1303
1304SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
1305 SMRange SourceRange) {
1306 assert(SourceRange.isValid() && "Invalid source range");
1307 SMLoc Loc = SourceRange.Start;
1308 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
1309 *Loc.getPointer() == '\'';
1310 // Translate the location of the error from the location in the MI string to
1311 // the corresponding location in the MIR file.
1312 Loc = Loc.getFromPointer(Ptr: Loc.getPointer() + Error.getColumnNo() +
1313 (HasQuote ? 1 : 0));
1314
1315 // TODO: Translate any source ranges as well.
1316 return SM.GetMessage(Loc, Kind: Error.getKind(), Msg: Error.getMessage(), Ranges: {},
1317 FixIts: Error.getFixIts());
1318}
1319
1320SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
1321 SMRange SourceRange) {
1322 assert(SourceRange.isValid());
1323
1324 // Translate the location of the error from the location in the llvm IR string
1325 // to the corresponding location in the MIR file.
1326 auto LineAndColumn = SM.getLineAndColumn(Loc: SourceRange.Start);
1327 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
1328 unsigned Column = Error.getColumnNo();
1329 StringRef LineStr = Error.getLineContents();
1330 SMLoc Loc = Error.getLoc();
1331
1332 // Get the full line and adjust the column number by taking the indentation of
1333 // LLVM IR into account.
1334 for (line_iterator L(*SM.getMemoryBuffer(i: SM.getMainFileID()), false), E;
1335 L != E; ++L) {
1336 if (L.line_number() == Line) {
1337 LineStr = *L;
1338 Loc = SMLoc::getFromPointer(Ptr: LineStr.data());
1339 auto Indent = LineStr.find(Str: Error.getLineContents());
1340 if (Indent != StringRef::npos)
1341 Column += Indent;
1342 break;
1343 }
1344 }
1345
1346 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
1347 Error.getMessage(), LineStr, Error.getRanges(),
1348 Error.getFixIts());
1349}
1350
1351MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
1352 : Impl(std::move(Impl)) {}
1353
1354MIRParser::~MIRParser() = default;
1355
1356std::unique_ptr<Module>
1357MIRParser::parseIRModule(DataLayoutCallbackTy DataLayoutCallback) {
1358 return Impl->parseIRModule(DataLayoutCallback);
1359}
1360
1361bool MIRParser::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) {
1362 return Impl->parseMachineFunctions(M, MMI);
1363}
1364
1365bool MIRParser::parseMachineFunctions(Module &M, ModuleAnalysisManager &MAM) {
1366 auto &MMI = MAM.getResult<MachineModuleAnalysis>(IR&: M).getMMI();
1367 return Impl->parseMachineFunctions(M, MMI, MAM: &MAM);
1368}
1369
1370std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(
1371 StringRef Filename, SMDiagnostic &Error, LLVMContext &Context,
1372 std::function<void(Function &)> ProcessIRFunction) {
1373 auto FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true);
1374 if (std::error_code EC = FileOrErr.getError()) {
1375 Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
1376 "could not open input file: " + EC.message());
1377 return nullptr;
1378 }
1379 return createMIRParser(Contents: std::move(FileOrErr.get()), Context,
1380 ProcessIRFunction);
1381}
1382
1383std::unique_ptr<MIRParser>
1384llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
1385 LLVMContext &Context,
1386 std::function<void(Function &)> ProcessIRFunction) {
1387 auto Filename = Contents->getBufferIdentifier();
1388 if (Context.shouldDiscardValueNames()) {
1389 Context.diagnose(DI: DiagnosticInfoMIRParser(
1390 DS_Error,
1391 SMDiagnostic(
1392 Filename, SourceMgr::DK_Error,
1393 "cannot read MIR with a Context that discards named Values")));
1394 return nullptr;
1395 }
1396 return std::make_unique<MIRParser>(args: std::make_unique<MIRParserImpl>(
1397 args: std::move(Contents), args&: Filename, args&: Context, args&: ProcessIRFunction));
1398}
1399