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