LLVM 18.0.0git
MIRParser.cpp
Go to the documentation of this file.
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
15#include "llvm/ADT/DenseMap.h"
16#include "llvm/ADT/StringMap.h"
17#include "llvm/ADT/StringRef.h"
28#include "llvm/IR/BasicBlock.h"
32#include "llvm/IR/LLVMContext.h"
33#include "llvm/IR/Module.h"
37#include "llvm/Support/SMLoc.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.
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,
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.
100
102
103 /// Parse the machine function in the current YAML document.
104 ///
105 ///
106 /// Return true if an error occurred.
108
109 /// Initialize the machine function to the state that's described in the MIR
110 /// file.
111 ///
112 /// Return true if error occurred.
114 MachineFunction &MF);
115
117 const yaml::MachineFunction &YamlMF);
118
120 const yaml::MachineFunction &YamlMF);
121
123 const yaml::MachineFunction &YamlMF);
124
126 const yaml::MachineFunction &YamlMF);
127
129 std::vector<CalleeSavedInfo> &CSIInfo,
130 const yaml::StringValue &RegisterSource,
131 bool IsRestored, int FrameIdx);
132
133 struct VarExprLoc {
136 DILocation *DILoc = nullptr;
137 };
138
139 std::optional<VarExprLoc> parseVarExprLoc(PerFunctionMIParsingState &PFS,
140 const yaml::StringValue &VarStr,
141 const yaml::StringValue &ExprStr,
142 const yaml::StringValue &LocStr);
143 template <typename T>
145 const T &Object,
146 int FrameIdx);
147
150 const yaml::MachineFunction &YamlMF);
151
153 const yaml::MachineJumpTable &YamlJTI);
154
156 MachineFunction &MF,
157 const yaml::MachineFunction &YMF);
158
159private:
160 bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node,
161 const yaml::StringValue &Source);
162
163 bool parseMBBReference(PerFunctionMIParsingState &PFS,
165 const yaml::StringValue &Source);
166
167 bool parseMachineMetadata(PerFunctionMIParsingState &PFS,
168 const yaml::StringValue &Source);
169
170 /// Return a MIR diagnostic converted from an MI string diagnostic.
171 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
172 SMRange SourceRange);
173
174 /// Return a MIR diagnostic converted from a diagnostic located in a YAML
175 /// block scalar string.
176 SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error,
177 SMRange SourceRange);
178
179 void computeFunctionProperties(MachineFunction &MF);
180
181 void setupDebugValueTracking(MachineFunction &MF,
183};
184
185} // end namespace llvm
186
187static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
188 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
189}
190
191MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
192 StringRef Filename, LLVMContext &Context,
193 std::function<void(Function &)> Callback)
194 : Context(Context),
195 In(SM.getMemoryBuffer(SM.AddNewSourceBuffer(std::move(Contents), SMLoc()))
196 ->getBuffer(),
197 nullptr, handleYAMLDiag, this),
198 Filename(Filename), ProcessIRFunction(Callback) {
199 In.setContext(&In);
200}
201
202bool MIRParserImpl::error(const Twine &Message) {
204 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
205 return true;
206}
207
208bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
210 DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
211 return true;
212}
213
215 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
216 reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
217 return true;
218}
219
222 switch (Diag.getKind()) {
224 Kind = DS_Error;
225 break;
227 Kind = DS_Warning;
228 break;
230 Kind = DS_Note;
231 break;
233 llvm_unreachable("remark unexpected");
234 break;
235 }
237}
238
239std::unique_ptr<Module>
241 if (!In.setCurrentDocument()) {
242 if (In.error())
243 return nullptr;
244 // Create an empty module when the MIR file is empty.
245 NoMIRDocuments = true;
246 auto M = std::make_unique<Module>(Filename, Context);
247 if (auto LayoutOverride =
248 DataLayoutCallback(M->getTargetTriple(), M->getDataLayoutStr()))
249 M->setDataLayout(*LayoutOverride);
250 return M;
251 }
252
253 std::unique_ptr<Module> M;
254 // Parse the block scalar manually so that we can return unique pointer
255 // without having to go trough YAML traits.
256 if (const auto *BSN =
257 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
259 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
260 Context, &IRSlots, DataLayoutCallback);
261 if (!M) {
262 reportDiagnostic(diagFromBlockStringDiag(Error, BSN->getSourceRange()));
263 return nullptr;
264 }
265 In.nextDocument();
266 if (!In.setCurrentDocument())
267 NoMIRDocuments = true;
268 } else {
269 // Create an new, empty module.
270 M = std::make_unique<Module>(Filename, Context);
271 if (auto LayoutOverride =
272 DataLayoutCallback(M->getTargetTriple(), M->getDataLayoutStr()))
273 M->setDataLayout(*LayoutOverride);
274 NoLLVMIR = true;
275 }
276 return M;
277}
278
280 if (NoMIRDocuments)
281 return false;
282
283 // Parse the machine functions.
284 do {
285 if (parseMachineFunction(M, MMI))
286 return true;
287 In.nextDocument();
288 } while (In.setCurrentDocument());
289
290 return false;
291}
292
294 auto &Context = M.getContext();
295 Function *F =
298 BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
299 new UnreachableInst(Context, BB);
300
301 if (ProcessIRFunction)
302 ProcessIRFunction(*F);
303
304 return F;
305}
306
308 // Parse the yaml.
310 yaml::EmptyContext Ctx;
311
312 const LLVMTargetMachine &TM = MMI.getTarget();
313 YamlMF.MachineFuncInfo = std::unique_ptr<yaml::MachineFunctionInfo>(
314 TM.createDefaultFuncInfoYAML());
315
316 yaml::yamlize(In, YamlMF, false, Ctx);
317 if (In.error())
318 return true;
319
320 // Search for the corresponding IR function.
321 StringRef FunctionName = YamlMF.Name;
322 Function *F = M.getFunction(FunctionName);
323 if (!F) {
324 if (NoLLVMIR) {
325 F = createDummyFunction(FunctionName, M);
326 } else {
327 return error(Twine("function '") + FunctionName +
328 "' isn't defined in the provided LLVM IR");
329 }
330 }
331 if (MMI.getMachineFunction(*F) != nullptr)
332 return error(Twine("redefinition of machine function '") + FunctionName +
333 "'");
334
335 // Create the MachineFunction.
337 if (initializeMachineFunction(YamlMF, MF))
338 return true;
339
340 return false;
341}
342
343static bool isSSA(const MachineFunction &MF) {
344 const MachineRegisterInfo &MRI = MF.getRegInfo();
345 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
347 if (!MRI.hasOneDef(Reg) && !MRI.def_empty(Reg))
348 return false;
349
350 // Subregister defs are invalid in SSA.
351 const MachineOperand *RegDef = MRI.getOneDef(Reg);
352 if (RegDef && RegDef->getSubReg() != 0)
353 return false;
354 }
355 return true;
356}
357
358void MIRParserImpl::computeFunctionProperties(MachineFunction &MF) {
359 MachineFunctionProperties &Properties = MF.getProperties();
360
361 bool HasPHI = false;
362 bool HasInlineAsm = false;
363 bool AllTiedOpsRewritten = true, HasTiedOps = false;
364 for (const MachineBasicBlock &MBB : MF) {
365 for (const MachineInstr &MI : MBB) {
366 if (MI.isPHI())
367 HasPHI = true;
368 if (MI.isInlineAsm())
369 HasInlineAsm = true;
370 for (unsigned I = 0; I < MI.getNumOperands(); ++I) {
371 const MachineOperand &MO = MI.getOperand(I);
372 if (!MO.isReg() || !MO.getReg())
373 continue;
374 unsigned DefIdx;
375 if (MO.isUse() && MI.isRegTiedToDefOperand(I, &DefIdx)) {
376 HasTiedOps = true;
377 if (MO.getReg() != MI.getOperand(DefIdx).getReg())
378 AllTiedOpsRewritten = false;
379 }
380 }
381 }
382 }
383 if (!HasPHI)
385 MF.setHasInlineAsm(HasInlineAsm);
386
387 if (HasTiedOps && AllTiedOpsRewritten)
389
390 if (isSSA(MF))
392 else
394
395 const MachineRegisterInfo &MRI = MF.getRegInfo();
396 if (MRI.getNumVirtRegs() == 0)
398}
399
402 MachineFunction &MF = PFS.MF;
404 const LLVMTargetMachine &TM = MF.getTarget();
405 for (auto &YamlCSInfo : YamlMF.CallSitesInfo) {
406 yaml::CallSiteInfo::MachineInstrLoc MILoc = YamlCSInfo.CallLocation;
407 if (MILoc.BlockNum >= MF.size())
408 return error(Twine(MF.getName()) +
409 Twine(" call instruction block out of range.") +
410 " Unable to reference bb:" + Twine(MILoc.BlockNum));
411 auto CallB = std::next(MF.begin(), MILoc.BlockNum);
412 if (MILoc.Offset >= CallB->size())
413 return error(Twine(MF.getName()) +
414 Twine(" call instruction offset out of range.") +
415 " Unable to reference instruction at bb: " +
416 Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset));
417 auto CallI = std::next(CallB->instr_begin(), MILoc.Offset);
418 if (!CallI->isCall(MachineInstr::IgnoreBundle))
419 return error(Twine(MF.getName()) +
420 Twine(" call site info should reference call "
421 "instruction. Instruction at bb:") +
422 Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset) +
423 " is not a call instruction");
425 for (auto ArgRegPair : YamlCSInfo.ArgForwardingRegs) {
426 Register Reg;
427 if (parseNamedRegisterReference(PFS, Reg, ArgRegPair.Reg.Value, Error))
428 return error(Error, ArgRegPair.Reg.SourceRange);
429 CSInfo.emplace_back(Reg, ArgRegPair.ArgNo);
430 }
431
432 if (TM.Options.EmitCallSiteInfo)
433 MF.addCallArgsForwardingRegs(&*CallI, std::move(CSInfo));
434 }
435
436 if (YamlMF.CallSitesInfo.size() && !TM.Options.EmitCallSiteInfo)
437 return error(Twine("Call site info provided but not used"));
438 return false;
439}
440
441void MIRParserImpl::setupDebugValueTracking(
443 const yaml::MachineFunction &YamlMF) {
444 // Compute the value of the "next instruction number" field.
445 unsigned MaxInstrNum = 0;
446 for (auto &MBB : MF)
447 for (auto &MI : MBB)
448 MaxInstrNum = std::max((unsigned)MI.peekDebugInstrNum(), MaxInstrNum);
449 MF.setDebugInstrNumberingCount(MaxInstrNum);
450
451 // Load any substitutions.
452 for (const auto &Sub : YamlMF.DebugValueSubstitutions) {
453 MF.makeDebugValueSubstitution({Sub.SrcInst, Sub.SrcOp},
454 {Sub.DstInst, Sub.DstOp}, Sub.Subreg);
455 }
456
457 // Flag for whether we're supposed to be using DBG_INSTR_REF.
458 MF.setUseDebugInstrRef(YamlMF.UseDebugInstrRef);
459}
460
461bool
463 MachineFunction &MF) {
464 // TODO: Recreate the machine function.
465 if (Target) {
466 // Avoid clearing state if we're using the same subtarget again.
467 Target->setTarget(MF.getSubtarget());
468 } else {
470 }
471
472 MF.setAlignment(YamlMF.Alignment.valueOrOne());
474 MF.setHasWinCFI(YamlMF.HasWinCFI);
475
479 MF.setHasEHScopes(YamlMF.HasEHScopes);
481 MF.setIsOutlined(YamlMF.IsOutlined);
482
483 if (YamlMF.Legalized)
485 if (YamlMF.RegBankSelected)
486 MF.getProperties().set(
488 if (YamlMF.Selected)
490 if (YamlMF.FailedISel)
492 if (YamlMF.FailsVerification)
493 MF.getProperties().set(
495 if (YamlMF.TracksDebugUserValues)
496 MF.getProperties().set(
498
499 PerFunctionMIParsingState PFS(MF, SM, IRSlots, *Target);
500 if (parseRegisterInfo(PFS, YamlMF))
501 return true;
502 if (!YamlMF.Constants.empty()) {
503 auto *ConstantPool = MF.getConstantPool();
504 assert(ConstantPool && "Constant pool must be created");
505 if (initializeConstantPool(PFS, *ConstantPool, YamlMF))
506 return true;
507 }
508 if (!YamlMF.MachineMetadataNodes.empty() &&
509 parseMachineMetadataNodes(PFS, MF, YamlMF))
510 return true;
511
512 StringRef BlockStr = YamlMF.Body.Value.Value;
514 SourceMgr BlockSM;
515 BlockSM.AddNewSourceBuffer(
516 MemoryBuffer::getMemBuffer(BlockStr, "",/*RequiresNullTerminator=*/false),
517 SMLoc());
518 PFS.SM = &BlockSM;
519 if (parseMachineBasicBlockDefinitions(PFS, BlockStr, Error)) {
521 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
522 return true;
523 }
524 // Check Basic Block Section Flags.
527 } else if (MF.hasBBSections()) {
529 }
530 PFS.SM = &SM;
531
532 // Initialize the frame information after creating all the MBBs so that the
533 // MBB references in the frame information can be resolved.
534 if (initializeFrameInfo(PFS, YamlMF))
535 return true;
536 // Initialize the jump table after creating all the MBBs so that the MBB
537 // references can be resolved.
538 if (!YamlMF.JumpTableInfo.Entries.empty() &&
540 return true;
541 // Parse the machine instructions after creating all of the MBBs so that the
542 // parser can resolve the MBB references.
543 StringRef InsnStr = YamlMF.Body.Value.Value;
544 SourceMgr InsnSM;
545 InsnSM.AddNewSourceBuffer(
546 MemoryBuffer::getMemBuffer(InsnStr, "", /*RequiresNullTerminator=*/false),
547 SMLoc());
548 PFS.SM = &InsnSM;
549 if (parseMachineInstructions(PFS, InsnStr, Error)) {
551 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
552 return true;
553 }
554 PFS.SM = &SM;
555
556 if (setupRegisterInfo(PFS, YamlMF))
557 return true;
558
559 if (YamlMF.MachineFuncInfo) {
560 const LLVMTargetMachine &TM = MF.getTarget();
561 // Note this is called after the initial constructor of the
562 // MachineFunctionInfo based on the MachineFunction, which may depend on the
563 // IR.
564
565 SMRange SrcRange;
566 if (TM.parseMachineFunctionInfo(*YamlMF.MachineFuncInfo, PFS, Error,
567 SrcRange)) {
568 return error(Error, SrcRange);
569 }
570 }
571
572 // Set the reserved registers after parsing MachineFuncInfo. The target may
573 // have been recording information used to select the reserved registers
574 // there.
575 // FIXME: This is a temporary workaround until the reserved registers can be
576 // serialized.
578 MRI.freezeReservedRegs(MF);
579
580 computeFunctionProperties(MF);
581
582 if (initializeCallSiteInfo(PFS, YamlMF))
583 return false;
584
585 setupDebugValueTracking(MF, PFS, YamlMF);
586
588
589 MF.verify();
590 return false;
591}
592
594 const yaml::MachineFunction &YamlMF) {
595 MachineFunction &MF = PFS.MF;
596 MachineRegisterInfo &RegInfo = MF.getRegInfo();
597 assert(RegInfo.tracksLiveness());
598 if (!YamlMF.TracksRegLiveness)
599 RegInfo.invalidateLiveness();
600
602 // Parse the virtual register information.
603 for (const auto &VReg : YamlMF.VirtualRegisters) {
604 VRegInfo &Info = PFS.getVRegInfo(VReg.ID.Value);
605 if (Info.Explicit)
606 return error(VReg.ID.SourceRange.Start,
607 Twine("redefinition of virtual register '%") +
608 Twine(VReg.ID.Value) + "'");
609 Info.Explicit = true;
610
611 if (StringRef(VReg.Class.Value).equals("_")) {
612 Info.Kind = VRegInfo::GENERIC;
613 Info.D.RegBank = nullptr;
614 } else {
615 const auto *RC = Target->getRegClass(VReg.Class.Value);
616 if (RC) {
617 Info.Kind = VRegInfo::NORMAL;
618 Info.D.RC = RC;
619 } else {
620 const RegisterBank *RegBank = Target->getRegBank(VReg.Class.Value);
621 if (!RegBank)
622 return error(
623 VReg.Class.SourceRange.Start,
624 Twine("use of undefined register class or register bank '") +
625 VReg.Class.Value + "'");
626 Info.Kind = VRegInfo::REGBANK;
627 Info.D.RegBank = RegBank;
628 }
629 }
630
631 if (!VReg.PreferredRegister.Value.empty()) {
632 if (Info.Kind != VRegInfo::NORMAL)
633 return error(VReg.Class.SourceRange.Start,
634 Twine("preferred register can only be set for normal vregs"));
635
636 if (parseRegisterReference(PFS, Info.PreferredReg,
637 VReg.PreferredRegister.Value, Error))
638 return error(Error, VReg.PreferredRegister.SourceRange);
639 }
640 }
641
642 // Parse the liveins.
643 for (const auto &LiveIn : YamlMF.LiveIns) {
644 Register Reg;
645 if (parseNamedRegisterReference(PFS, Reg, LiveIn.Register.Value, Error))
646 return error(Error, LiveIn.Register.SourceRange);
647 Register VReg;
648 if (!LiveIn.VirtualRegister.Value.empty()) {
649 VRegInfo *Info;
650 if (parseVirtualRegisterReference(PFS, Info, LiveIn.VirtualRegister.Value,
651 Error))
652 return error(Error, LiveIn.VirtualRegister.SourceRange);
653 VReg = Info->VReg;
654 }
655 RegInfo.addLiveIn(Reg, VReg);
656 }
657
658 // Parse the callee saved registers (Registers that will
659 // be saved for the caller).
660 if (YamlMF.CalleeSavedRegisters) {
661 SmallVector<MCPhysReg, 16> CalleeSavedRegisters;
662 for (const auto &RegSource : *YamlMF.CalleeSavedRegisters) {
663 Register Reg;
664 if (parseNamedRegisterReference(PFS, Reg, RegSource.Value, Error))
665 return error(Error, RegSource.SourceRange);
666 CalleeSavedRegisters.push_back(Reg);
667 }
668 RegInfo.setCalleeSavedRegs(CalleeSavedRegisters);
669 }
670
671 return false;
672}
673
675 const yaml::MachineFunction &YamlMF) {
676 MachineFunction &MF = PFS.MF;
679
680 bool Error = false;
681 // Create VRegs
682 auto populateVRegInfo = [&](const VRegInfo &Info, Twine Name) {
683 Register Reg = Info.VReg;
684 switch (Info.Kind) {
686 error(Twine("Cannot determine class/bank of virtual register ") +
687 Name + " in function '" + MF.getName() + "'");
688 Error = true;
689 break;
690 case VRegInfo::NORMAL:
691 if (!Info.D.RC->isAllocatable()) {
692 error(Twine("Cannot use non-allocatable class '") +
693 TRI->getRegClassName(Info.D.RC) + "' for virtual register " +
694 Name + " in function '" + MF.getName() + "'");
695 Error = true;
696 break;
697 }
698
699 MRI.setRegClass(Reg, Info.D.RC);
700 if (Info.PreferredReg != 0)
701 MRI.setSimpleHint(Reg, Info.PreferredReg);
702 break;
704 break;
706 MRI.setRegBank(Reg, *Info.D.RegBank);
707 break;
708 }
709 };
710
711 for (const auto &P : PFS.VRegInfosNamed) {
712 const VRegInfo &Info = *P.second;
713 populateVRegInfo(Info, Twine(P.first()));
714 }
715
716 for (auto P : PFS.VRegInfos) {
717 const VRegInfo &Info = *P.second;
718 populateVRegInfo(Info, Twine(P.first));
719 }
720
721 // Compute MachineRegisterInfo::UsedPhysRegMask
722 for (const MachineBasicBlock &MBB : MF) {
723 // Make sure MRI knows about registers clobbered by unwinder.
724 if (MBB.isEHPad())
725 if (auto *RegMask = TRI->getCustomEHPadPreservedMask(MF))
726 MRI.addPhysRegsUsedFromRegMask(RegMask);
727
728 for (const MachineInstr &MI : MBB) {
729 for (const MachineOperand &MO : MI.operands()) {
730 if (!MO.isRegMask())
731 continue;
732 MRI.addPhysRegsUsedFromRegMask(MO.getRegMask());
733 }
734 }
735 }
736
737 return Error;
738}
739
741 const yaml::MachineFunction &YamlMF) {
742 MachineFunction &MF = PFS.MF;
743 MachineFrameInfo &MFI = MF.getFrameInfo();
745 const Function &F = MF.getFunction();
746 const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
749 MFI.setHasStackMap(YamlMFI.HasStackMap);
750 MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
751 MFI.setStackSize(YamlMFI.StackSize);
753 if (YamlMFI.MaxAlignment)
755 MFI.setAdjustsStack(YamlMFI.AdjustsStack);
756 MFI.setHasCalls(YamlMFI.HasCalls);
757 if (YamlMFI.MaxCallFrameSize != ~0u)
761 MFI.setHasVAStart(YamlMFI.HasVAStart);
763 MFI.setHasTailCall(YamlMFI.HasTailCall);
765 if (!YamlMFI.SavePoint.Value.empty()) {
766 MachineBasicBlock *MBB = nullptr;
767 if (parseMBBReference(PFS, MBB, YamlMFI.SavePoint))
768 return true;
769 MFI.setSavePoint(MBB);
770 }
771 if (!YamlMFI.RestorePoint.Value.empty()) {
772 MachineBasicBlock *MBB = nullptr;
773 if (parseMBBReference(PFS, MBB, YamlMFI.RestorePoint))
774 return true;
775 MFI.setRestorePoint(MBB);
776 }
777
778 std::vector<CalleeSavedInfo> CSIInfo;
779 // Initialize the fixed frame objects.
780 for (const auto &Object : YamlMF.FixedStackObjects) {
781 int ObjectIdx;
783 ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
784 Object.IsImmutable, Object.IsAliased);
785 else
786 ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
787
788 if (!TFI->isSupportedStackID(Object.StackID))
789 return error(Object.ID.SourceRange.Start,
790 Twine("StackID is not supported by target"));
791 MFI.setStackID(ObjectIdx, Object.StackID);
792 MFI.setObjectAlignment(ObjectIdx, Object.Alignment.valueOrOne());
793 if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
794 ObjectIdx))
795 .second)
796 return error(Object.ID.SourceRange.Start,
797 Twine("redefinition of fixed stack object '%fixed-stack.") +
798 Twine(Object.ID.Value) + "'");
799 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
800 Object.CalleeSavedRestored, ObjectIdx))
801 return true;
802 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
803 return true;
804 }
805
806 for (const auto &Object : YamlMF.EntryValueObjects) {
808 Register Reg;
809 if (parseNamedRegisterReference(PFS, Reg, Object.EntryValueRegister.Value,
810 Error))
811 return error(Error, Object.EntryValueRegister.SourceRange);
812 if (!Reg.isPhysical())
813 return error(Object.EntryValueRegister.SourceRange.Start,
814 "Expected physical register for entry value field");
815 std::optional<VarExprLoc> MaybeInfo = parseVarExprLoc(
816 PFS, Object.DebugVar, Object.DebugExpr, Object.DebugLoc);
817 if (!MaybeInfo)
818 return true;
819 if (MaybeInfo->DIVar || MaybeInfo->DIExpr || MaybeInfo->DILoc)
820 PFS.MF.setVariableDbgInfo(MaybeInfo->DIVar, MaybeInfo->DIExpr,
821 Reg.asMCReg(), MaybeInfo->DILoc);
822 }
823
824 // Initialize the ordinary frame objects.
825 for (const auto &Object : YamlMF.StackObjects) {
826 int ObjectIdx;
827 const AllocaInst *Alloca = nullptr;
828 const yaml::StringValue &Name = Object.Name;
829 if (!Name.Value.empty()) {
830 Alloca = dyn_cast_or_null<AllocaInst>(
831 F.getValueSymbolTable()->lookup(Name.Value));
832 if (!Alloca)
833 return error(Name.SourceRange.Start,
834 "alloca instruction named '" + Name.Value +
835 "' isn't defined in the function '" + F.getName() +
836 "'");
837 }
838 if (!TFI->isSupportedStackID(Object.StackID))
839 return error(Object.ID.SourceRange.Start,
840 Twine("StackID is not supported by target"));
842 ObjectIdx =
843 MFI.CreateVariableSizedObject(Object.Alignment.valueOrOne(), Alloca);
844 else
845 ObjectIdx = MFI.CreateStackObject(
846 Object.Size, Object.Alignment.valueOrOne(),
847 Object.Type == yaml::MachineStackObject::SpillSlot, Alloca,
848 Object.StackID);
849 MFI.setObjectOffset(ObjectIdx, Object.Offset);
850
851 if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
852 .second)
853 return error(Object.ID.SourceRange.Start,
854 Twine("redefinition of stack object '%stack.") +
855 Twine(Object.ID.Value) + "'");
856 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
857 Object.CalleeSavedRestored, ObjectIdx))
858 return true;
859 if (Object.LocalOffset)
860 MFI.mapLocalFrameObject(ObjectIdx, *Object.LocalOffset);
861 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
862 return true;
863 }
864 MFI.setCalleeSavedInfo(CSIInfo);
865 if (!CSIInfo.empty())
866 MFI.setCalleeSavedInfoValid(true);
867
868 // Initialize the various stack object references after initializing the
869 // stack objects.
870 if (!YamlMFI.StackProtector.Value.empty()) {
872 int FI;
874 return error(Error, YamlMFI.StackProtector.SourceRange);
876 }
877
878 if (!YamlMFI.FunctionContext.Value.empty()) {
880 int FI;
882 return error(Error, YamlMFI.FunctionContext.SourceRange);
884 }
885
886 return false;
887}
888
890 std::vector<CalleeSavedInfo> &CSIInfo,
891 const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx) {
892 if (RegisterSource.Value.empty())
893 return false;
894 Register Reg;
896 if (parseNamedRegisterReference(PFS, Reg, RegisterSource.Value, Error))
897 return error(Error, RegisterSource.SourceRange);
898 CalleeSavedInfo CSI(Reg, FrameIdx);
899 CSI.setRestored(IsRestored);
900 CSIInfo.push_back(CSI);
901 return false;
902}
903
904/// Verify that given node is of a certain type. Return true on error.
905template <typename T>
906static bool typecheckMDNode(T *&Result, MDNode *Node,
907 const yaml::StringValue &Source,
908 StringRef TypeString, MIRParserImpl &Parser) {
909 if (!Node)
910 return false;
911 Result = dyn_cast<T>(Node);
912 if (!Result)
913 return Parser.error(Source.SourceRange.Start,
914 "expected a reference to a '" + TypeString +
915 "' metadata node");
916 return false;
917}
918
919std::optional<MIRParserImpl::VarExprLoc> MIRParserImpl::parseVarExprLoc(
921 const yaml::StringValue &ExprStr, const yaml::StringValue &LocStr) {
922 MDNode *Var = nullptr;
923 MDNode *Expr = nullptr;
924 MDNode *Loc = nullptr;
925 if (parseMDNode(PFS, Var, VarStr) || parseMDNode(PFS, Expr, ExprStr) ||
926 parseMDNode(PFS, Loc, LocStr))
927 return std::nullopt;
928 DILocalVariable *DIVar = nullptr;
929 DIExpression *DIExpr = nullptr;
930 DILocation *DILoc = nullptr;
931 if (typecheckMDNode(DIVar, Var, VarStr, "DILocalVariable", *this) ||
932 typecheckMDNode(DIExpr, Expr, ExprStr, "DIExpression", *this) ||
933 typecheckMDNode(DILoc, Loc, LocStr, "DILocation", *this))
934 return std::nullopt;
935 return VarExprLoc{DIVar, DIExpr, DILoc};
936}
937
938template <typename T>
940 const T &Object, int FrameIdx) {
941 std::optional<VarExprLoc> MaybeInfo =
942 parseVarExprLoc(PFS, Object.DebugVar, Object.DebugExpr, Object.DebugLoc);
943 if (!MaybeInfo)
944 return true;
945 // Debug information can only be attached to stack objects; Fixed stack
946 // objects aren't supported.
947 if (MaybeInfo->DIVar || MaybeInfo->DIExpr || MaybeInfo->DILoc)
948 PFS.MF.setVariableDbgInfo(MaybeInfo->DIVar, MaybeInfo->DIExpr, FrameIdx,
949 MaybeInfo->DILoc);
950 return false;
951}
952
953bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState &PFS,
954 MDNode *&Node, const yaml::StringValue &Source) {
955 if (Source.Value.empty())
956 return false;
958 if (llvm::parseMDNode(PFS, Node, Source.Value, Error))
959 return error(Error, Source.SourceRange);
960 return false;
961}
962
965 DenseMap<unsigned, unsigned> &ConstantPoolSlots = PFS.ConstantPoolSlots;
966 const MachineFunction &MF = PFS.MF;
967 const auto &M = *MF.getFunction().getParent();
969 for (const auto &YamlConstant : YamlMF.Constants) {
970 if (YamlConstant.IsTargetSpecific)
971 // FIXME: Support target-specific constant pools
972 return error(YamlConstant.Value.SourceRange.Start,
973 "Can't parse target-specific constant pool entries yet");
974 const Constant *Value = dyn_cast_or_null<Constant>(
975 parseConstantValue(YamlConstant.Value.Value, Error, M));
976 if (!Value)
977 return error(Error, YamlConstant.Value.SourceRange);
978 const Align PrefTypeAlign =
979 M.getDataLayout().getPrefTypeAlign(Value->getType());
980 const Align Alignment = YamlConstant.Alignment.value_or(PrefTypeAlign);
981 unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
982 if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
983 .second)
984 return error(YamlConstant.ID.SourceRange.Start,
985 Twine("redefinition of constant pool item '%const.") +
986 Twine(YamlConstant.ID.Value) + "'");
987 }
988 return false;
989}
990
992 const yaml::MachineJumpTable &YamlJTI) {
994 for (const auto &Entry : YamlJTI.Entries) {
995 std::vector<MachineBasicBlock *> Blocks;
996 for (const auto &MBBSource : Entry.Blocks) {
997 MachineBasicBlock *MBB = nullptr;
998 if (parseMBBReference(PFS, MBB, MBBSource.Value))
999 return true;
1000 Blocks.push_back(MBB);
1001 }
1002 unsigned Index = JTI->createJumpTableIndex(Blocks);
1003 if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
1004 .second)
1005 return error(Entry.ID.SourceRange.Start,
1006 Twine("redefinition of jump table entry '%jump-table.") +
1007 Twine(Entry.ID.Value) + "'");
1008 }
1009 return false;
1010}
1011
1012bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState &PFS,
1014 const yaml::StringValue &Source) {
1016 if (llvm::parseMBBReference(PFS, MBB, Source.Value, Error))
1017 return error(Error, Source.SourceRange);
1018 return false;
1019}
1020
1021bool MIRParserImpl::parseMachineMetadata(PerFunctionMIParsingState &PFS,
1022 const yaml::StringValue &Source) {
1024 if (llvm::parseMachineMetadata(PFS, Source.Value, Source.SourceRange, Error))
1025 return error(Error, Source.SourceRange);
1026 return false;
1027}
1028
1031 const yaml::MachineFunction &YMF) {
1032 for (const auto &MDS : YMF.MachineMetadataNodes) {
1033 if (parseMachineMetadata(PFS, MDS))
1034 return true;
1035 }
1036 // Report missing definitions from forward referenced nodes.
1037 if (!PFS.MachineForwardRefMDNodes.empty())
1038 return error(PFS.MachineForwardRefMDNodes.begin()->second.second,
1039 "use of undefined metadata '!" +
1040 Twine(PFS.MachineForwardRefMDNodes.begin()->first) + "'");
1041 return false;
1042}
1043
1044SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
1045 SMRange SourceRange) {
1046 assert(SourceRange.isValid() && "Invalid source range");
1047 SMLoc Loc = SourceRange.Start;
1048 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
1049 *Loc.getPointer() == '\'';
1050 // Translate the location of the error from the location in the MI string to
1051 // the corresponding location in the MIR file.
1052 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
1053 (HasQuote ? 1 : 0));
1054
1055 // TODO: Translate any source ranges as well.
1056 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), std::nullopt,
1057 Error.getFixIts());
1058}
1059
1060SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
1061 SMRange SourceRange) {
1062 assert(SourceRange.isValid());
1063
1064 // Translate the location of the error from the location in the llvm IR string
1065 // to the corresponding location in the MIR file.
1066 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
1067 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
1068 unsigned Column = Error.getColumnNo();
1069 StringRef LineStr = Error.getLineContents();
1070 SMLoc Loc = Error.getLoc();
1071
1072 // Get the full line and adjust the column number by taking the indentation of
1073 // LLVM IR into account.
1074 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
1075 L != E; ++L) {
1076 if (L.line_number() == Line) {
1077 LineStr = *L;
1078 Loc = SMLoc::getFromPointer(LineStr.data());
1079 auto Indent = LineStr.find(Error.getLineContents());
1080 if (Indent != StringRef::npos)
1081 Column += Indent;
1082 break;
1083 }
1084 }
1085
1086 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
1087 Error.getMessage(), LineStr, Error.getRanges(),
1088 Error.getFixIts());
1089}
1090
1091MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
1092 : Impl(std::move(Impl)) {}
1093
1094MIRParser::~MIRParser() = default;
1095
1096std::unique_ptr<Module>
1098 return Impl->parseIRModule(DataLayoutCallback);
1099}
1100
1102 return Impl->parseMachineFunctions(M, MMI);
1103}
1104
1105std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(
1106 StringRef Filename, SMDiagnostic &Error, LLVMContext &Context,
1107 std::function<void(Function &)> ProcessIRFunction) {
1108 auto FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true);
1109 if (std::error_code EC = FileOrErr.getError()) {
1111 "Could not open input file: " + EC.message());
1112 return nullptr;
1113 }
1114 return createMIRParser(std::move(FileOrErr.get()), Context,
1115 ProcessIRFunction);
1116}
1117
1118std::unique_ptr<MIRParser>
1119llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
1120 LLVMContext &Context,
1121 std::function<void(Function &)> ProcessIRFunction) {
1122 auto Filename = Contents->getBufferIdentifier();
1125 DS_Error,
1127 Filename, SourceMgr::DK_Error,
1128 "Can't read MIR with a Context that discards named Values")));
1129 return nullptr;
1130 }
1131 return std::make_unique<MIRParser>(std::make_unique<MIRParserImpl>(
1132 std::move(Contents), Filename, Context, ProcessIRFunction));
1133}
unsigned const MachineRegisterInfo * MRI
MachineBasicBlock & MBB
This file defines the StringMap class.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Analysis containing CSE Info
Definition: CSEInfo.cpp:27
This file defines the DenseMap class.
std::string Name
DenseMap< Block *, BlockRelaxAux > Blocks
Definition: ELF_riscv.cpp:496
IRTranslator LLVM IR MI
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
static bool isSSA(const MachineFunction &MF)
Definition: MIRParser.cpp:343
static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context)
Definition: MIRParser.cpp:187
static bool typecheckMDNode(T *&Result, MDNode *Node, const yaml::StringValue &Source, StringRef TypeString, MIRParserImpl &Parser)
Verify that given node is of a certain type. Return true on error.
Definition: MIRParser.cpp:906
This file declares the MachineConstantPool class which is an abstract constant pool to keep track of ...
unsigned const TargetRegisterInfo * TRI
Module.h This file contains the declarations for the Module class.
LLVMContext & Context
#define P(N)
const char LLVMTargetMachineRef TM
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
#define error(X)
an instruction to allocate memory on the stack
Definition: Instructions.h:58
LLVM Basic Block Representation.
Definition: BasicBlock.h:56
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:105
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
This is an important base class in LLVM.
Definition: Constant.h:41
DWARF expression.
Debug location.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:220
Diagnostic information for machine IR parser.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:138
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:652
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:48
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
bool shouldDiscardValueNames() const
Return true if the Context runtime configuration is set to discard all value names.
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
This class describes a target machine that is implemented with the LLVM target-independent code gener...
Metadata node.
Definition: Metadata.h:950
This class implements the parsing of LLVM IR that's embedded inside a MIR file.
Definition: MIRParser.cpp:51
bool error(const Twine &Message)
Report an error with the given message at unknown location.
Definition: MIRParser.cpp:202
void reportDiagnostic(const SMDiagnostic &Diag)
Definition: MIRParser.cpp:220
bool setupRegisterInfo(const PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF)
Definition: MIRParser.cpp:674
bool parseRegisterInfo(PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF)
Definition: MIRParser.cpp:593
bool initializeFrameInfo(PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF)
Definition: MIRParser.cpp:740
Function * createDummyFunction(StringRef Name, Module &M)
Create an empty function with the given name.
Definition: MIRParser.cpp:293
bool parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS, const T &Object, int FrameIdx)
Definition: MIRParser.cpp:939
bool initializeMachineFunction(const yaml::MachineFunction &YamlMF, MachineFunction &MF)
Initialize the machine function to the state that's described in the MIR file.
Definition: MIRParser.cpp:462
std::unique_ptr< Module > parseIRModule(DataLayoutCallbackTy DataLayoutCallback)
Try to parse the optional LLVM module and the machine functions in the MIR file.
Definition: MIRParser.cpp:240
bool initializeJumpTableInfo(PerFunctionMIParsingState &PFS, const yaml::MachineJumpTable &YamlJTI)
Definition: MIRParser.cpp:991
bool parseMachineFunctions(Module &M, MachineModuleInfo &MMI)
Definition: MIRParser.cpp:279
bool initializeConstantPool(PerFunctionMIParsingState &PFS, MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF)
Definition: MIRParser.cpp:963
MIRParserImpl(std::unique_ptr< MemoryBuffer > Contents, StringRef Filename, LLVMContext &Context, std::function< void(Function &)> ProcessIRFunction)
Definition: MIRParser.cpp:191
std::optional< VarExprLoc > parseVarExprLoc(PerFunctionMIParsingState &PFS, const yaml::StringValue &VarStr, const yaml::StringValue &ExprStr, const yaml::StringValue &LocStr)
Definition: MIRParser.cpp:919
bool parseMachineFunction(Module &M, MachineModuleInfo &MMI)
Parse the machine function in the current YAML document.
Definition: MIRParser.cpp:307
bool parseCalleeSavedRegister(PerFunctionMIParsingState &PFS, std::vector< CalleeSavedInfo > &CSIInfo, const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx)
Definition: MIRParser.cpp:889
bool parseMachineMetadataNodes(PerFunctionMIParsingState &PFS, MachineFunction &MF, const yaml::MachineFunction &YMF)
Definition: MIRParser.cpp:1029
bool initializeCallSiteInfo(PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF)
Definition: MIRParser.cpp:400
MIRParser(std::unique_ptr< MIRParserImpl > Impl)
Definition: MIRParser.cpp:1091
std::unique_ptr< Module > parseIRModule(DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
Parses the optional LLVM IR module in the MIR file.
Definition: MIRParser.cpp:1097
bool parseMachineFunctions(Module &M, MachineModuleInfo &MMI)
Parses MachineFunctions in the MIR file and add them to the given MachineModuleInfo MMI.
Definition: MIRParser.cpp:1101
bool isEHPad() const
Returns true if the block is a landing pad.
The MachineConstantPool class keeps track of constants referenced by a function which must be spilled...
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable, bool isAliased=false)
Create a new object at a fixed location on the stack.
void setRestorePoint(MachineBasicBlock *NewRestore)
int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
void ensureMaxAlignment(Align Alignment)
Make sure the function is at least Align bytes aligned.
void setHasPatchPoint(bool s=true)
void setLocalFrameSize(int64_t sz)
Set the size of the local object blob.
void setObjectOffset(int ObjectIdx, int64_t SPOffset)
Set the stack frame offset of the specified object.
void setFrameAddressIsTaken(bool T)
void setHasStackMap(bool s=true)
void setCVBytesOfCalleeSavedRegisters(unsigned S)
void setStackID(int ObjectIdx, uint8_t ID)
void setHasTailCall(bool V=true)
void setStackProtectorIndex(int I)
void setCalleeSavedInfoValid(bool v)
void setReturnAddressIsTaken(bool s)
void mapLocalFrameObject(int ObjectIndex, int64_t Offset)
Map a frame index into the local object block.
void setOffsetAdjustment(int Adj)
Set the correction for frame offsets.
void setHasOpaqueSPAdjustment(bool B)
void setCalleeSavedInfo(std::vector< CalleeSavedInfo > CSI)
Used by prolog/epilog inserter to set the function's callee saved information.
int CreateVariableSizedObject(Align Alignment, const AllocaInst *Alloca)
Notify the MachineFrameInfo object that a variable sized object has been created.
void setSavePoint(MachineBasicBlock *NewSave)
void setMaxCallFrameSize(unsigned S)
int CreateFixedSpillStackObject(uint64_t Size, int64_t SPOffset, bool IsImmutable=false)
Create a spill slot at a fixed location on the stack.
void setStackSize(uint64_t Size)
Set the size of the stack.
void setHasMustTailInVarArgFunc(bool B)
void setObjectAlignment(int ObjectIdx, Align Alignment)
setObjectAlignment - Change the alignment of the specified stack object.
void setFunctionContextIndex(int I)
Properties which a MachineFunction may have at a given point in time.
MachineFunctionProperties & set(Property P)
MachineFunctionProperties & reset(Property P)
void setBBSectionsType(BasicBlockSection V)
void setCallsUnwindInit(bool b)
void setHasEHFunclets(bool V)
void setExposesReturnsTwice(bool B)
setCallsSetJmp - Set a flag that indicates if there's a call to a "returns twice" function.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineJumpTableInfo * getOrCreateJumpTableInfo(unsigned JTEntryKind)
getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it does already exist,...
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
void setHasEHCatchret(bool V)
void setCallsEHReturn(bool b)
void setAlignment(Align A)
setAlignment - Set the alignment of the function.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
bool hasBBSections() const
Returns true if this function has basic block sections enabled.
unsigned size() const
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
void addCallArgsForwardingRegs(const MachineInstr *CallI, CallSiteInfoImpl &&CallInfo)
Start tracking the arguments passed to the call CallI.
Function & getFunction()
Return the LLVM function that this machine code represents.
const LLVMTargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
MachineConstantPool * getConstantPool()
getConstantPool - Return the constant pool object for the current function.
const MachineFunctionProperties & getProperties() const
Get the function properties.
void setVariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr, int Slot, const DILocation *Loc)
Collect information used to emit debugging information of a variable in a stack slot.
bool verify(Pass *p=nullptr, const char *Banner=nullptr, bool AbortOnError=true) const
Run the current MachineFunction through the machine code verifier, useful for debugger use.
void assignBeginEndSections()
Assign IsBeginSection IsEndSection fields for basic blocks in this function.
Representation of each machine instruction.
Definition: MachineInstr.h:68
unsigned createJumpTableIndex(const std::vector< MachineBasicBlock * > &DestBBs)
createJumpTableIndex - Create a new jump table.
This class contains meta information specific to a module.
MachineFunction & getOrCreateMachineFunction(Function &F)
Returns the MachineFunction constructed for the IR function F.
const LLVMTargetMachine & getTarget() const
MachineFunction * getMachineFunction(const Function &F) const
Returns the MachineFunction associated to IR function F if there is one, otherwise nullptr.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isRegMask() const
isRegMask - Tests if this is a MO_RegisterMask operand.
Register getReg() const
getReg - Returns the register number.
const uint32_t * getRegMask() const
getRegMask - Returns a bit mask of registers preserved by this RegMask operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
bool tracksLiveness() const
tracksLiveness - Returns true when tracking register liveness accurately.
void invalidateLiveness()
invalidateLiveness - Indicates that register liveness is no longer being tracked accurately.
void setCalleeSavedRegs(ArrayRef< MCPhysReg > CSRs)
Sets the updated Callee Saved Registers list.
void addLiveIn(MCRegister Reg, Register vreg=Register())
addLiveIn - Add the specified register as a live-in.
static std::unique_ptr< MemoryBuffer > getMemBuffer(StringRef InputData, StringRef BufferName="", bool RequiresNullTerminator=true)
Open the specified memory range as a MemoryBuffer.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
This class implements the register bank concept.
Definition: RegisterBank.h:28
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
static Register index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition: Register.h:84
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition: SourceMgr.h:281
SourceMgr::DiagKind getKind() const
Definition: SourceMgr.h:310
Represents a location in source code.
Definition: SMLoc.h:23
static SMLoc getFromPointer(const char *Ptr)
Definition: SMLoc.h:36
constexpr const char * getPointer() const
Definition: SMLoc.h:34
Represents a range in source code.
Definition: SMLoc.h:48
bool isValid() const
Definition: SMLoc.h:59
SMLoc Start
Definition: SMLoc.h:50
SMLoc End
Definition: SMLoc.h:50
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:941
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling.
Definition: SourceMgr.h:31
unsigned getMainFileID() const
Definition: SourceMgr.h:132
std::pair< unsigned, unsigned > getLineAndColumn(SMLoc Loc, unsigned BufferID=0) const
Find the line and column number for the specified location in the specified file.
Definition: SourceMgr.cpp:192
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition: SourceMgr.h:125
SMDiagnostic GetMessage(SMLoc Loc, DiagKind Kind, const Twine &Msg, ArrayRef< SMRange > Ranges={}, ArrayRef< SMFixIt > FixIts={}) const
Return an SMDiagnostic at the specified location with the specified string.
Definition: SourceMgr.cpp:274
unsigned AddNewSourceBuffer(std::unique_ptr< MemoryBuffer > F, SMLoc IncludeLoc)
Add a new source buffer to this source manager.
Definition: SourceMgr.h:144
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
bool equals(StringRef RHS) const
equals - Check for string equality, this is more efficient than compare() when the relative ordering ...
Definition: StringRef.h:164
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:301
static constexpr size_t npos
Definition: StringRef.h:52
const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:131
Information about stack frame layout on the target.
virtual bool isSupportedStackID(TargetStackID::Value ID) const
llvm::BasicBlockSection getBBSectionsType() const
If basic blocks should be emitted into their own section, corresponding to -fbasic-block-sections.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
virtual void mirFileLoaded(MachineFunction &MF) const
This is called after a .mir file was loaded.
virtual const TargetFrameLowering * getFrameLowering() const
Target - Wrapper for Target specific information.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
static Type * getVoidTy(LLVMContext &C)
This function has undefined behavior.
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
An efficient, type-erasing, non-owning reference to a callable.
A forward iterator which reads text lines from a buffer.
Definition: LineIterator.h:33
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool parseStackObjectReference(PerFunctionMIParsingState &PFS, int &FI, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3618
bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3624
bool parseMachineBasicBlockDefinitions(PerFunctionMIParsingState &PFS, StringRef Src, SMDiagnostic &Error)
Parse the machine basic block definitions, and skip the machine instructions.
Definition: MIParser.cpp:3583
bool parseMBBReference(PerFunctionMIParsingState &PFS, MachineBasicBlock *&MBB, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3594
std::unique_ptr< MIRParser > createMIRParserFromFile(StringRef Filename, SMDiagnostic &Error, LLVMContext &Context, std::function< void(Function &)> ProcessIRFunction=nullptr)
This function is the main interface to the MIR serialization format parser.
Definition: MIRParser.cpp:1105
std::unique_ptr< MIRParser > createMIRParser(std::unique_ptr< MemoryBuffer > Contents, LLVMContext &Context, std::function< void(Function &)> ProcessIRFunction=nullptr)
This function is another interface to the MIR serialization format parser.
Definition: MIRParser.cpp:1119
std::unique_ptr< Module > parseAssembly(MemoryBufferRef F, SMDiagnostic &Err, LLVMContext &Context, SlotMapping *Slots=nullptr, DataLayoutCallbackTy DataLayoutCallback=[](StringRef, StringRef) { return std::nullopt;})
parseAssemblyFile and parseAssemblyString are wrappers around this function.
Definition: Parser.cpp:46
bool parseMachineInstructions(PerFunctionMIParsingState &PFS, StringRef Src, SMDiagnostic &Error)
Parse the machine instructions.
Definition: MIParser.cpp:3589
bool parseRegisterReference(PerFunctionMIParsingState &PFS, Register &Reg, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3600
Constant * parseConstantValue(StringRef Asm, SMDiagnostic &Err, const Module &M, const SlotMapping *Slots=nullptr)
Parse a type and a constant value in the given string.
Definition: Parser.cpp:187
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1854
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
@ DS_Warning
@ DS_Error
bool parseMachineMetadata(PerFunctionMIParsingState &PFS, StringRef Src, SMRange SourceRange, SMDiagnostic &Error)
Definition: MIParser.cpp:3629
bool parseVirtualRegisterReference(PerFunctionMIParsingState &PFS, VRegInfo *&Info, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3612
bool parseNamedRegisterReference(PerFunctionMIParsingState &PFS, Register &Reg, StringRef Src, SMDiagnostic &Error)
Definition: MIParser.cpp:3606
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
Align valueOrOne() const
For convenience, returns a valid alignment or 1 if undefined.
Definition: Alignment.h:141
DenseMap< unsigned, unsigned > JumpTableSlots
Definition: MIParser.h:178
VRegInfo & getVRegInfo(Register Num)
Definition: MIParser.cpp:319
DenseMap< unsigned, int > FixedStackObjectSlots
Definition: MIParser.h:175
DenseMap< unsigned, unsigned > ConstantPoolSlots
Definition: MIParser.h:177
StringMap< VRegInfo * > VRegInfosNamed
Definition: MIParser.h:174
DenseMap< unsigned, int > StackObjectSlots
Definition: MIParser.h:176
std::map< unsigned, std::pair< TempMDTuple, SMLoc > > MachineForwardRefMDNodes
Definition: MIParser.h:170
DenseMap< Register, VRegInfo * > VRegInfos
Definition: MIParser.h:173
This struct contains the mappings from the slot numbers to unnamed metadata nodes,...
Definition: SlotMapping.h:32
Identifies call instruction location in machine function.
Serializable representation of MachineFrameInfo.
unsigned MaxCallFrameSize
~0u means: not computed yet.
std::vector< MachineStackObject > StackObjects
std::vector< StringValue > MachineMetadataNodes
std::optional< std::vector< FlowStringValue > > CalleeSavedRegisters
std::vector< EntryValueObject > EntryValueObjects
std::vector< MachineConstantPoolValue > Constants
std::vector< CallSiteInfo > CallSitesInfo
std::vector< MachineFunctionLiveIn > LiveIns
std::vector< VirtualRegisterDefinition > VirtualRegisters
std::vector< FixedMachineStackObject > FixedStackObjects
std::vector< DebugValueSubstitution > DebugValueSubstitutions
std::unique_ptr< MachineFunctionInfo > MachineFuncInfo
Constant pool.
MachineJumpTable JumpTableInfo
std::vector< Entry > Entries
MachineJumpTableInfo::JTEntryKind Kind
A wrapper around std::string which contains a source range that's being set during parsing.