109467b48Spatrick //===- MIRParser.cpp - MIR serialization format parser implementation -----===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick // This file implements the class that parses the optional LLVM IR and machine
1009467b48Spatrick // functions that are stored in MIR files.
1109467b48Spatrick //
1209467b48Spatrick //===----------------------------------------------------------------------===//
1309467b48Spatrick
1409467b48Spatrick #include "llvm/CodeGen/MIRParser/MIRParser.h"
1509467b48Spatrick #include "llvm/ADT/DenseMap.h"
1609467b48Spatrick #include "llvm/ADT/StringMap.h"
1709467b48Spatrick #include "llvm/ADT/StringRef.h"
1809467b48Spatrick #include "llvm/AsmParser/Parser.h"
1909467b48Spatrick #include "llvm/AsmParser/SlotMapping.h"
2009467b48Spatrick #include "llvm/CodeGen/MIRParser/MIParser.h"
2109467b48Spatrick #include "llvm/CodeGen/MIRYamlMapping.h"
2209467b48Spatrick #include "llvm/CodeGen/MachineConstantPool.h"
2309467b48Spatrick #include "llvm/CodeGen/MachineFrameInfo.h"
2409467b48Spatrick #include "llvm/CodeGen/MachineFunction.h"
2509467b48Spatrick #include "llvm/CodeGen/MachineModuleInfo.h"
2609467b48Spatrick #include "llvm/CodeGen/MachineRegisterInfo.h"
2709467b48Spatrick #include "llvm/CodeGen/TargetFrameLowering.h"
2809467b48Spatrick #include "llvm/IR/BasicBlock.h"
29*d415bd75Srobert #include "llvm/IR/DebugInfoMetadata.h"
3009467b48Spatrick #include "llvm/IR/DiagnosticInfo.h"
3109467b48Spatrick #include "llvm/IR/Instructions.h"
3209467b48Spatrick #include "llvm/IR/LLVMContext.h"
3309467b48Spatrick #include "llvm/IR/Module.h"
3409467b48Spatrick #include "llvm/IR/ValueSymbolTable.h"
3509467b48Spatrick #include "llvm/Support/LineIterator.h"
3609467b48Spatrick #include "llvm/Support/MemoryBuffer.h"
3709467b48Spatrick #include "llvm/Support/SMLoc.h"
3809467b48Spatrick #include "llvm/Support/SourceMgr.h"
3909467b48Spatrick #include "llvm/Support/YAMLTraits.h"
4009467b48Spatrick #include "llvm/Target/TargetMachine.h"
4109467b48Spatrick #include <memory>
4209467b48Spatrick
4309467b48Spatrick using namespace llvm;
4409467b48Spatrick
4509467b48Spatrick namespace llvm {
46*d415bd75Srobert class MDNode;
47*d415bd75Srobert class RegisterBank;
4809467b48Spatrick
4909467b48Spatrick /// This class implements the parsing of LLVM IR that's embedded inside a MIR
5009467b48Spatrick /// file.
5109467b48Spatrick class MIRParserImpl {
5209467b48Spatrick SourceMgr SM;
5373471bf0Spatrick LLVMContext &Context;
5409467b48Spatrick yaml::Input In;
5509467b48Spatrick StringRef Filename;
5609467b48Spatrick SlotMapping IRSlots;
5709467b48Spatrick std::unique_ptr<PerTargetMIParsingState> Target;
5809467b48Spatrick
5909467b48Spatrick /// True when the MIR file doesn't have LLVM IR. Dummy IR functions are
6009467b48Spatrick /// created and inserted into the given module when this is true.
6109467b48Spatrick bool NoLLVMIR = false;
6209467b48Spatrick /// True when a well formed MIR file does not contain any MIR/machine function
6309467b48Spatrick /// parts.
6409467b48Spatrick bool NoMIRDocuments = false;
6509467b48Spatrick
6609467b48Spatrick std::function<void(Function &)> ProcessIRFunction;
6709467b48Spatrick
6809467b48Spatrick public:
6909467b48Spatrick MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename,
7009467b48Spatrick LLVMContext &Context,
7109467b48Spatrick std::function<void(Function &)> ProcessIRFunction);
7209467b48Spatrick
7309467b48Spatrick void reportDiagnostic(const SMDiagnostic &Diag);
7409467b48Spatrick
7509467b48Spatrick /// Report an error with the given message at unknown location.
7609467b48Spatrick ///
7709467b48Spatrick /// Always returns true.
7809467b48Spatrick bool error(const Twine &Message);
7909467b48Spatrick
8009467b48Spatrick /// Report an error with the given message at the given location.
8109467b48Spatrick ///
8209467b48Spatrick /// Always returns true.
8309467b48Spatrick bool error(SMLoc Loc, const Twine &Message);
8409467b48Spatrick
8509467b48Spatrick /// Report a given error with the location translated from the location in an
8609467b48Spatrick /// embedded string literal to a location in the MIR file.
8709467b48Spatrick ///
8809467b48Spatrick /// Always returns true.
8909467b48Spatrick bool error(const SMDiagnostic &Error, SMRange SourceRange);
9009467b48Spatrick
9109467b48Spatrick /// Try to parse the optional LLVM module and the machine functions in the MIR
9209467b48Spatrick /// file.
9309467b48Spatrick ///
9409467b48Spatrick /// Return null if an error occurred.
95097a140dSpatrick std::unique_ptr<Module>
96097a140dSpatrick parseIRModule(DataLayoutCallbackTy DataLayoutCallback);
9709467b48Spatrick
9809467b48Spatrick /// Create an empty function with the given name.
9909467b48Spatrick Function *createDummyFunction(StringRef Name, Module &M);
10009467b48Spatrick
10109467b48Spatrick bool parseMachineFunctions(Module &M, MachineModuleInfo &MMI);
10209467b48Spatrick
10309467b48Spatrick /// Parse the machine function in the current YAML document.
10409467b48Spatrick ///
10509467b48Spatrick ///
10609467b48Spatrick /// Return true if an error occurred.
10709467b48Spatrick bool parseMachineFunction(Module &M, MachineModuleInfo &MMI);
10809467b48Spatrick
10909467b48Spatrick /// Initialize the machine function to the state that's described in the MIR
11009467b48Spatrick /// file.
11109467b48Spatrick ///
11209467b48Spatrick /// Return true if error occurred.
11309467b48Spatrick bool initializeMachineFunction(const yaml::MachineFunction &YamlMF,
11409467b48Spatrick MachineFunction &MF);
11509467b48Spatrick
11609467b48Spatrick bool parseRegisterInfo(PerFunctionMIParsingState &PFS,
11709467b48Spatrick const yaml::MachineFunction &YamlMF);
11809467b48Spatrick
11909467b48Spatrick bool setupRegisterInfo(const PerFunctionMIParsingState &PFS,
12009467b48Spatrick const yaml::MachineFunction &YamlMF);
12109467b48Spatrick
12209467b48Spatrick bool initializeFrameInfo(PerFunctionMIParsingState &PFS,
12309467b48Spatrick const yaml::MachineFunction &YamlMF);
12409467b48Spatrick
12509467b48Spatrick bool initializeCallSiteInfo(PerFunctionMIParsingState &PFS,
12609467b48Spatrick const yaml::MachineFunction &YamlMF);
12709467b48Spatrick
12809467b48Spatrick bool parseCalleeSavedRegister(PerFunctionMIParsingState &PFS,
12909467b48Spatrick std::vector<CalleeSavedInfo> &CSIInfo,
13009467b48Spatrick const yaml::StringValue &RegisterSource,
13109467b48Spatrick bool IsRestored, int FrameIdx);
13209467b48Spatrick
13309467b48Spatrick template <typename T>
13409467b48Spatrick bool parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
13509467b48Spatrick const T &Object,
13609467b48Spatrick int FrameIdx);
13709467b48Spatrick
13809467b48Spatrick bool initializeConstantPool(PerFunctionMIParsingState &PFS,
13909467b48Spatrick MachineConstantPool &ConstantPool,
14009467b48Spatrick const yaml::MachineFunction &YamlMF);
14109467b48Spatrick
14209467b48Spatrick bool initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
14309467b48Spatrick const yaml::MachineJumpTable &YamlJTI);
14409467b48Spatrick
14573471bf0Spatrick bool parseMachineMetadataNodes(PerFunctionMIParsingState &PFS,
14673471bf0Spatrick MachineFunction &MF,
14773471bf0Spatrick const yaml::MachineFunction &YMF);
14873471bf0Spatrick
14909467b48Spatrick private:
15009467b48Spatrick bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node,
15109467b48Spatrick const yaml::StringValue &Source);
15209467b48Spatrick
15309467b48Spatrick bool parseMBBReference(PerFunctionMIParsingState &PFS,
15409467b48Spatrick MachineBasicBlock *&MBB,
15509467b48Spatrick const yaml::StringValue &Source);
15609467b48Spatrick
15773471bf0Spatrick bool parseMachineMetadata(PerFunctionMIParsingState &PFS,
15873471bf0Spatrick const yaml::StringValue &Source);
15973471bf0Spatrick
16009467b48Spatrick /// Return a MIR diagnostic converted from an MI string diagnostic.
16109467b48Spatrick SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error,
16209467b48Spatrick SMRange SourceRange);
16309467b48Spatrick
16409467b48Spatrick /// Return a MIR diagnostic converted from a diagnostic located in a YAML
16509467b48Spatrick /// block scalar string.
16609467b48Spatrick SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error,
16709467b48Spatrick SMRange SourceRange);
16809467b48Spatrick
16909467b48Spatrick void computeFunctionProperties(MachineFunction &MF);
17073471bf0Spatrick
17173471bf0Spatrick void setupDebugValueTracking(MachineFunction &MF,
17273471bf0Spatrick PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF);
17309467b48Spatrick };
17409467b48Spatrick
17509467b48Spatrick } // end namespace llvm
17609467b48Spatrick
handleYAMLDiag(const SMDiagnostic & Diag,void * Context)17709467b48Spatrick static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) {
17809467b48Spatrick reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag);
17909467b48Spatrick }
18009467b48Spatrick
MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,StringRef Filename,LLVMContext & Context,std::function<void (Function &)> Callback)18109467b48Spatrick MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents,
18209467b48Spatrick StringRef Filename, LLVMContext &Context,
18309467b48Spatrick std::function<void(Function &)> Callback)
184*d415bd75Srobert : Context(Context),
18509467b48Spatrick In(SM.getMemoryBuffer(SM.AddNewSourceBuffer(std::move(Contents), SMLoc()))
18609467b48Spatrick ->getBuffer(),
18709467b48Spatrick nullptr, handleYAMLDiag, this),
18873471bf0Spatrick Filename(Filename), ProcessIRFunction(Callback) {
18909467b48Spatrick In.setContext(&In);
19009467b48Spatrick }
19109467b48Spatrick
error(const Twine & Message)19209467b48Spatrick bool MIRParserImpl::error(const Twine &Message) {
19309467b48Spatrick Context.diagnose(DiagnosticInfoMIRParser(
19409467b48Spatrick DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str())));
19509467b48Spatrick return true;
19609467b48Spatrick }
19709467b48Spatrick
error(SMLoc Loc,const Twine & Message)19809467b48Spatrick bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) {
19909467b48Spatrick Context.diagnose(DiagnosticInfoMIRParser(
20009467b48Spatrick DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message)));
20109467b48Spatrick return true;
20209467b48Spatrick }
20309467b48Spatrick
error(const SMDiagnostic & Error,SMRange SourceRange)20409467b48Spatrick bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) {
20509467b48Spatrick assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error");
20609467b48Spatrick reportDiagnostic(diagFromMIStringDiag(Error, SourceRange));
20709467b48Spatrick return true;
20809467b48Spatrick }
20909467b48Spatrick
reportDiagnostic(const SMDiagnostic & Diag)21009467b48Spatrick void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) {
21109467b48Spatrick DiagnosticSeverity Kind;
21209467b48Spatrick switch (Diag.getKind()) {
21309467b48Spatrick case SourceMgr::DK_Error:
21409467b48Spatrick Kind = DS_Error;
21509467b48Spatrick break;
21609467b48Spatrick case SourceMgr::DK_Warning:
21709467b48Spatrick Kind = DS_Warning;
21809467b48Spatrick break;
21909467b48Spatrick case SourceMgr::DK_Note:
22009467b48Spatrick Kind = DS_Note;
22109467b48Spatrick break;
22209467b48Spatrick case SourceMgr::DK_Remark:
22309467b48Spatrick llvm_unreachable("remark unexpected");
22409467b48Spatrick break;
22509467b48Spatrick }
22609467b48Spatrick Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag));
22709467b48Spatrick }
22809467b48Spatrick
229097a140dSpatrick std::unique_ptr<Module>
parseIRModule(DataLayoutCallbackTy DataLayoutCallback)230097a140dSpatrick MIRParserImpl::parseIRModule(DataLayoutCallbackTy DataLayoutCallback) {
23109467b48Spatrick if (!In.setCurrentDocument()) {
23209467b48Spatrick if (In.error())
23309467b48Spatrick return nullptr;
23409467b48Spatrick // Create an empty module when the MIR file is empty.
23509467b48Spatrick NoMIRDocuments = true;
236097a140dSpatrick auto M = std::make_unique<Module>(Filename, Context);
237*d415bd75Srobert if (auto LayoutOverride =
238*d415bd75Srobert DataLayoutCallback(M->getTargetTriple(), M->getDataLayoutStr()))
239097a140dSpatrick M->setDataLayout(*LayoutOverride);
240097a140dSpatrick return M;
24109467b48Spatrick }
24209467b48Spatrick
24309467b48Spatrick std::unique_ptr<Module> M;
24409467b48Spatrick // Parse the block scalar manually so that we can return unique pointer
24509467b48Spatrick // without having to go trough YAML traits.
24609467b48Spatrick if (const auto *BSN =
24709467b48Spatrick dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) {
24809467b48Spatrick SMDiagnostic Error;
24909467b48Spatrick M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error,
250097a140dSpatrick Context, &IRSlots, DataLayoutCallback);
25109467b48Spatrick if (!M) {
25209467b48Spatrick reportDiagnostic(diagFromBlockStringDiag(Error, BSN->getSourceRange()));
25309467b48Spatrick return nullptr;
25409467b48Spatrick }
25509467b48Spatrick In.nextDocument();
25609467b48Spatrick if (!In.setCurrentDocument())
25709467b48Spatrick NoMIRDocuments = true;
25809467b48Spatrick } else {
25909467b48Spatrick // Create an new, empty module.
26009467b48Spatrick M = std::make_unique<Module>(Filename, Context);
261*d415bd75Srobert if (auto LayoutOverride =
262*d415bd75Srobert DataLayoutCallback(M->getTargetTriple(), M->getDataLayoutStr()))
263097a140dSpatrick M->setDataLayout(*LayoutOverride);
26409467b48Spatrick NoLLVMIR = true;
26509467b48Spatrick }
26609467b48Spatrick return M;
26709467b48Spatrick }
26809467b48Spatrick
parseMachineFunctions(Module & M,MachineModuleInfo & MMI)26909467b48Spatrick bool MIRParserImpl::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) {
27009467b48Spatrick if (NoMIRDocuments)
27109467b48Spatrick return false;
27209467b48Spatrick
27309467b48Spatrick // Parse the machine functions.
27409467b48Spatrick do {
27509467b48Spatrick if (parseMachineFunction(M, MMI))
27609467b48Spatrick return true;
27709467b48Spatrick In.nextDocument();
27809467b48Spatrick } while (In.setCurrentDocument());
27909467b48Spatrick
28009467b48Spatrick return false;
28109467b48Spatrick }
28209467b48Spatrick
createDummyFunction(StringRef Name,Module & M)28309467b48Spatrick Function *MIRParserImpl::createDummyFunction(StringRef Name, Module &M) {
28409467b48Spatrick auto &Context = M.getContext();
28509467b48Spatrick Function *F =
28609467b48Spatrick Function::Create(FunctionType::get(Type::getVoidTy(Context), false),
28709467b48Spatrick Function::ExternalLinkage, Name, M);
28809467b48Spatrick BasicBlock *BB = BasicBlock::Create(Context, "entry", F);
28909467b48Spatrick new UnreachableInst(Context, BB);
29009467b48Spatrick
29109467b48Spatrick if (ProcessIRFunction)
29209467b48Spatrick ProcessIRFunction(*F);
29309467b48Spatrick
29409467b48Spatrick return F;
29509467b48Spatrick }
29609467b48Spatrick
parseMachineFunction(Module & M,MachineModuleInfo & MMI)29709467b48Spatrick bool MIRParserImpl::parseMachineFunction(Module &M, MachineModuleInfo &MMI) {
29809467b48Spatrick // Parse the yaml.
29909467b48Spatrick yaml::MachineFunction YamlMF;
30009467b48Spatrick yaml::EmptyContext Ctx;
30109467b48Spatrick
30209467b48Spatrick const LLVMTargetMachine &TM = MMI.getTarget();
30309467b48Spatrick YamlMF.MachineFuncInfo = std::unique_ptr<yaml::MachineFunctionInfo>(
30409467b48Spatrick TM.createDefaultFuncInfoYAML());
30509467b48Spatrick
30609467b48Spatrick yaml::yamlize(In, YamlMF, false, Ctx);
30709467b48Spatrick if (In.error())
30809467b48Spatrick return true;
30909467b48Spatrick
31009467b48Spatrick // Search for the corresponding IR function.
31109467b48Spatrick StringRef FunctionName = YamlMF.Name;
31209467b48Spatrick Function *F = M.getFunction(FunctionName);
31309467b48Spatrick if (!F) {
31409467b48Spatrick if (NoLLVMIR) {
31509467b48Spatrick F = createDummyFunction(FunctionName, M);
31609467b48Spatrick } else {
31709467b48Spatrick return error(Twine("function '") + FunctionName +
31809467b48Spatrick "' isn't defined in the provided LLVM IR");
31909467b48Spatrick }
32009467b48Spatrick }
32109467b48Spatrick if (MMI.getMachineFunction(*F) != nullptr)
32209467b48Spatrick return error(Twine("redefinition of machine function '") + FunctionName +
32309467b48Spatrick "'");
32409467b48Spatrick
32509467b48Spatrick // Create the MachineFunction.
32609467b48Spatrick MachineFunction &MF = MMI.getOrCreateMachineFunction(*F);
32709467b48Spatrick if (initializeMachineFunction(YamlMF, MF))
32809467b48Spatrick return true;
32909467b48Spatrick
33009467b48Spatrick return false;
33109467b48Spatrick }
33209467b48Spatrick
isSSA(const MachineFunction & MF)33309467b48Spatrick static bool isSSA(const MachineFunction &MF) {
33409467b48Spatrick const MachineRegisterInfo &MRI = MF.getRegInfo();
33509467b48Spatrick for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) {
33673471bf0Spatrick Register Reg = Register::index2VirtReg(I);
33709467b48Spatrick if (!MRI.hasOneDef(Reg) && !MRI.def_empty(Reg))
33809467b48Spatrick return false;
33973471bf0Spatrick
34073471bf0Spatrick // Subregister defs are invalid in SSA.
34173471bf0Spatrick const MachineOperand *RegDef = MRI.getOneDef(Reg);
34273471bf0Spatrick if (RegDef && RegDef->getSubReg() != 0)
34373471bf0Spatrick return false;
34409467b48Spatrick }
34509467b48Spatrick return true;
34609467b48Spatrick }
34709467b48Spatrick
computeFunctionProperties(MachineFunction & MF)34809467b48Spatrick void MIRParserImpl::computeFunctionProperties(MachineFunction &MF) {
34909467b48Spatrick MachineFunctionProperties &Properties = MF.getProperties();
35009467b48Spatrick
35109467b48Spatrick bool HasPHI = false;
35209467b48Spatrick bool HasInlineAsm = false;
353*d415bd75Srobert bool AllTiedOpsRewritten = true, HasTiedOps = false;
35409467b48Spatrick for (const MachineBasicBlock &MBB : MF) {
35509467b48Spatrick for (const MachineInstr &MI : MBB) {
35609467b48Spatrick if (MI.isPHI())
35709467b48Spatrick HasPHI = true;
35809467b48Spatrick if (MI.isInlineAsm())
35909467b48Spatrick HasInlineAsm = true;
360*d415bd75Srobert for (unsigned I = 0; I < MI.getNumOperands(); ++I) {
361*d415bd75Srobert const MachineOperand &MO = MI.getOperand(I);
362*d415bd75Srobert if (!MO.isReg() || !MO.getReg())
363*d415bd75Srobert continue;
364*d415bd75Srobert unsigned DefIdx;
365*d415bd75Srobert if (MO.isUse() && MI.isRegTiedToDefOperand(I, &DefIdx)) {
366*d415bd75Srobert HasTiedOps = true;
367*d415bd75Srobert if (MO.getReg() != MI.getOperand(DefIdx).getReg())
368*d415bd75Srobert AllTiedOpsRewritten = false;
369*d415bd75Srobert }
370*d415bd75Srobert }
37109467b48Spatrick }
37209467b48Spatrick }
37309467b48Spatrick if (!HasPHI)
37409467b48Spatrick Properties.set(MachineFunctionProperties::Property::NoPHIs);
37509467b48Spatrick MF.setHasInlineAsm(HasInlineAsm);
37609467b48Spatrick
377*d415bd75Srobert if (HasTiedOps && AllTiedOpsRewritten)
378*d415bd75Srobert Properties.set(MachineFunctionProperties::Property::TiedOpsRewritten);
379*d415bd75Srobert
38009467b48Spatrick if (isSSA(MF))
38109467b48Spatrick Properties.set(MachineFunctionProperties::Property::IsSSA);
38209467b48Spatrick else
38309467b48Spatrick Properties.reset(MachineFunctionProperties::Property::IsSSA);
38409467b48Spatrick
38509467b48Spatrick const MachineRegisterInfo &MRI = MF.getRegInfo();
38609467b48Spatrick if (MRI.getNumVirtRegs() == 0)
38709467b48Spatrick Properties.set(MachineFunctionProperties::Property::NoVRegs);
38809467b48Spatrick }
38909467b48Spatrick
initializeCallSiteInfo(PerFunctionMIParsingState & PFS,const yaml::MachineFunction & YamlMF)39009467b48Spatrick bool MIRParserImpl::initializeCallSiteInfo(
39109467b48Spatrick PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF) {
39209467b48Spatrick MachineFunction &MF = PFS.MF;
39309467b48Spatrick SMDiagnostic Error;
39409467b48Spatrick const LLVMTargetMachine &TM = MF.getTarget();
39509467b48Spatrick for (auto YamlCSInfo : YamlMF.CallSitesInfo) {
39609467b48Spatrick yaml::CallSiteInfo::MachineInstrLoc MILoc = YamlCSInfo.CallLocation;
39709467b48Spatrick if (MILoc.BlockNum >= MF.size())
39809467b48Spatrick return error(Twine(MF.getName()) +
39909467b48Spatrick Twine(" call instruction block out of range.") +
40009467b48Spatrick " Unable to reference bb:" + Twine(MILoc.BlockNum));
40109467b48Spatrick auto CallB = std::next(MF.begin(), MILoc.BlockNum);
40209467b48Spatrick if (MILoc.Offset >= CallB->size())
40309467b48Spatrick return error(Twine(MF.getName()) +
40409467b48Spatrick Twine(" call instruction offset out of range.") +
40509467b48Spatrick " Unable to reference instruction at bb: " +
40609467b48Spatrick Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset));
40709467b48Spatrick auto CallI = std::next(CallB->instr_begin(), MILoc.Offset);
40809467b48Spatrick if (!CallI->isCall(MachineInstr::IgnoreBundle))
40909467b48Spatrick return error(Twine(MF.getName()) +
41009467b48Spatrick Twine(" call site info should reference call "
41109467b48Spatrick "instruction. Instruction at bb:") +
41209467b48Spatrick Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset) +
41309467b48Spatrick " is not a call instruction");
41409467b48Spatrick MachineFunction::CallSiteInfo CSInfo;
41509467b48Spatrick for (auto ArgRegPair : YamlCSInfo.ArgForwardingRegs) {
416097a140dSpatrick Register Reg;
41709467b48Spatrick if (parseNamedRegisterReference(PFS, Reg, ArgRegPair.Reg.Value, Error))
41809467b48Spatrick return error(Error, ArgRegPair.Reg.SourceRange);
41909467b48Spatrick CSInfo.emplace_back(Reg, ArgRegPair.ArgNo);
42009467b48Spatrick }
42109467b48Spatrick
422097a140dSpatrick if (TM.Options.EmitCallSiteInfo)
42309467b48Spatrick MF.addCallArgsForwardingRegs(&*CallI, std::move(CSInfo));
42409467b48Spatrick }
42509467b48Spatrick
426097a140dSpatrick if (YamlMF.CallSitesInfo.size() && !TM.Options.EmitCallSiteInfo)
42709467b48Spatrick return error(Twine("Call site info provided but not used"));
42809467b48Spatrick return false;
42909467b48Spatrick }
43009467b48Spatrick
setupDebugValueTracking(MachineFunction & MF,PerFunctionMIParsingState & PFS,const yaml::MachineFunction & YamlMF)43173471bf0Spatrick void MIRParserImpl::setupDebugValueTracking(
43273471bf0Spatrick MachineFunction &MF, PerFunctionMIParsingState &PFS,
43373471bf0Spatrick const yaml::MachineFunction &YamlMF) {
43473471bf0Spatrick // Compute the value of the "next instruction number" field.
43573471bf0Spatrick unsigned MaxInstrNum = 0;
43673471bf0Spatrick for (auto &MBB : MF)
43773471bf0Spatrick for (auto &MI : MBB)
43873471bf0Spatrick MaxInstrNum = std::max((unsigned)MI.peekDebugInstrNum(), MaxInstrNum);
43973471bf0Spatrick MF.setDebugInstrNumberingCount(MaxInstrNum);
44073471bf0Spatrick
44173471bf0Spatrick // Load any substitutions.
442*d415bd75Srobert for (const auto &Sub : YamlMF.DebugValueSubstitutions) {
44373471bf0Spatrick MF.makeDebugValueSubstitution({Sub.SrcInst, Sub.SrcOp},
44473471bf0Spatrick {Sub.DstInst, Sub.DstOp}, Sub.Subreg);
44573471bf0Spatrick }
446*d415bd75Srobert
447*d415bd75Srobert // Flag for whether we're supposed to be using DBG_INSTR_REF.
448*d415bd75Srobert MF.setUseDebugInstrRef(YamlMF.UseDebugInstrRef);
44973471bf0Spatrick }
45073471bf0Spatrick
45109467b48Spatrick bool
initializeMachineFunction(const yaml::MachineFunction & YamlMF,MachineFunction & MF)45209467b48Spatrick MIRParserImpl::initializeMachineFunction(const yaml::MachineFunction &YamlMF,
45309467b48Spatrick MachineFunction &MF) {
45409467b48Spatrick // TODO: Recreate the machine function.
45509467b48Spatrick if (Target) {
45609467b48Spatrick // Avoid clearing state if we're using the same subtarget again.
45709467b48Spatrick Target->setTarget(MF.getSubtarget());
45809467b48Spatrick } else {
45909467b48Spatrick Target.reset(new PerTargetMIParsingState(MF.getSubtarget()));
46009467b48Spatrick }
46109467b48Spatrick
462097a140dSpatrick MF.setAlignment(YamlMF.Alignment.valueOrOne());
46309467b48Spatrick MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice);
46409467b48Spatrick MF.setHasWinCFI(YamlMF.HasWinCFI);
46509467b48Spatrick
466*d415bd75Srobert MF.setCallsEHReturn(YamlMF.CallsEHReturn);
467*d415bd75Srobert MF.setCallsUnwindInit(YamlMF.CallsUnwindInit);
468*d415bd75Srobert MF.setHasEHCatchret(YamlMF.HasEHCatchret);
469*d415bd75Srobert MF.setHasEHScopes(YamlMF.HasEHScopes);
470*d415bd75Srobert MF.setHasEHFunclets(YamlMF.HasEHFunclets);
471*d415bd75Srobert
47209467b48Spatrick if (YamlMF.Legalized)
47309467b48Spatrick MF.getProperties().set(MachineFunctionProperties::Property::Legalized);
47409467b48Spatrick if (YamlMF.RegBankSelected)
47509467b48Spatrick MF.getProperties().set(
47609467b48Spatrick MachineFunctionProperties::Property::RegBankSelected);
47709467b48Spatrick if (YamlMF.Selected)
47809467b48Spatrick MF.getProperties().set(MachineFunctionProperties::Property::Selected);
47909467b48Spatrick if (YamlMF.FailedISel)
48009467b48Spatrick MF.getProperties().set(MachineFunctionProperties::Property::FailedISel);
481*d415bd75Srobert if (YamlMF.FailsVerification)
482*d415bd75Srobert MF.getProperties().set(
483*d415bd75Srobert MachineFunctionProperties::Property::FailsVerification);
484*d415bd75Srobert if (YamlMF.TracksDebugUserValues)
485*d415bd75Srobert MF.getProperties().set(
486*d415bd75Srobert MachineFunctionProperties::Property::TracksDebugUserValues);
48709467b48Spatrick
48809467b48Spatrick PerFunctionMIParsingState PFS(MF, SM, IRSlots, *Target);
48909467b48Spatrick if (parseRegisterInfo(PFS, YamlMF))
49009467b48Spatrick return true;
49109467b48Spatrick if (!YamlMF.Constants.empty()) {
49209467b48Spatrick auto *ConstantPool = MF.getConstantPool();
49309467b48Spatrick assert(ConstantPool && "Constant pool must be created");
49409467b48Spatrick if (initializeConstantPool(PFS, *ConstantPool, YamlMF))
49509467b48Spatrick return true;
49609467b48Spatrick }
49773471bf0Spatrick if (!YamlMF.MachineMetadataNodes.empty() &&
49873471bf0Spatrick parseMachineMetadataNodes(PFS, MF, YamlMF))
49973471bf0Spatrick return true;
50009467b48Spatrick
50109467b48Spatrick StringRef BlockStr = YamlMF.Body.Value.Value;
50209467b48Spatrick SMDiagnostic Error;
50309467b48Spatrick SourceMgr BlockSM;
50409467b48Spatrick BlockSM.AddNewSourceBuffer(
50509467b48Spatrick MemoryBuffer::getMemBuffer(BlockStr, "",/*RequiresNullTerminator=*/false),
50609467b48Spatrick SMLoc());
50709467b48Spatrick PFS.SM = &BlockSM;
50809467b48Spatrick if (parseMachineBasicBlockDefinitions(PFS, BlockStr, Error)) {
50909467b48Spatrick reportDiagnostic(
51009467b48Spatrick diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
51109467b48Spatrick return true;
51209467b48Spatrick }
513097a140dSpatrick // Check Basic Block Section Flags.
514097a140dSpatrick if (MF.getTarget().getBBSectionsType() == BasicBlockSection::Labels) {
515097a140dSpatrick MF.setBBSectionsType(BasicBlockSection::Labels);
516097a140dSpatrick } else if (MF.hasBBSections()) {
517097a140dSpatrick MF.assignBeginEndSections();
518097a140dSpatrick }
51909467b48Spatrick PFS.SM = &SM;
52009467b48Spatrick
52109467b48Spatrick // Initialize the frame information after creating all the MBBs so that the
52209467b48Spatrick // MBB references in the frame information can be resolved.
52309467b48Spatrick if (initializeFrameInfo(PFS, YamlMF))
52409467b48Spatrick return true;
52509467b48Spatrick // Initialize the jump table after creating all the MBBs so that the MBB
52609467b48Spatrick // references can be resolved.
52709467b48Spatrick if (!YamlMF.JumpTableInfo.Entries.empty() &&
52809467b48Spatrick initializeJumpTableInfo(PFS, YamlMF.JumpTableInfo))
52909467b48Spatrick return true;
53009467b48Spatrick // Parse the machine instructions after creating all of the MBBs so that the
53109467b48Spatrick // parser can resolve the MBB references.
53209467b48Spatrick StringRef InsnStr = YamlMF.Body.Value.Value;
53309467b48Spatrick SourceMgr InsnSM;
53409467b48Spatrick InsnSM.AddNewSourceBuffer(
53509467b48Spatrick MemoryBuffer::getMemBuffer(InsnStr, "", /*RequiresNullTerminator=*/false),
53609467b48Spatrick SMLoc());
53709467b48Spatrick PFS.SM = &InsnSM;
53809467b48Spatrick if (parseMachineInstructions(PFS, InsnStr, Error)) {
53909467b48Spatrick reportDiagnostic(
54009467b48Spatrick diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange));
54109467b48Spatrick return true;
54209467b48Spatrick }
54309467b48Spatrick PFS.SM = &SM;
54409467b48Spatrick
54509467b48Spatrick if (setupRegisterInfo(PFS, YamlMF))
54609467b48Spatrick return true;
54709467b48Spatrick
54809467b48Spatrick if (YamlMF.MachineFuncInfo) {
54909467b48Spatrick const LLVMTargetMachine &TM = MF.getTarget();
55009467b48Spatrick // Note this is called after the initial constructor of the
55109467b48Spatrick // MachineFunctionInfo based on the MachineFunction, which may depend on the
55209467b48Spatrick // IR.
55309467b48Spatrick
55409467b48Spatrick SMRange SrcRange;
55509467b48Spatrick if (TM.parseMachineFunctionInfo(*YamlMF.MachineFuncInfo, PFS, Error,
55609467b48Spatrick SrcRange)) {
55709467b48Spatrick return error(Error, SrcRange);
55809467b48Spatrick }
55909467b48Spatrick }
56009467b48Spatrick
56109467b48Spatrick // Set the reserved registers after parsing MachineFuncInfo. The target may
56209467b48Spatrick // have been recording information used to select the reserved registers
56309467b48Spatrick // there.
56409467b48Spatrick // FIXME: This is a temporary workaround until the reserved registers can be
56509467b48Spatrick // serialized.
56609467b48Spatrick MachineRegisterInfo &MRI = MF.getRegInfo();
56709467b48Spatrick MRI.freezeReservedRegs(MF);
56809467b48Spatrick
56909467b48Spatrick computeFunctionProperties(MF);
57009467b48Spatrick
57109467b48Spatrick if (initializeCallSiteInfo(PFS, YamlMF))
57209467b48Spatrick return false;
57309467b48Spatrick
57473471bf0Spatrick setupDebugValueTracking(MF, PFS, YamlMF);
57573471bf0Spatrick
57609467b48Spatrick MF.getSubtarget().mirFileLoaded(MF);
57709467b48Spatrick
57809467b48Spatrick MF.verify();
57909467b48Spatrick return false;
58009467b48Spatrick }
58109467b48Spatrick
parseRegisterInfo(PerFunctionMIParsingState & PFS,const yaml::MachineFunction & YamlMF)58209467b48Spatrick bool MIRParserImpl::parseRegisterInfo(PerFunctionMIParsingState &PFS,
58309467b48Spatrick const yaml::MachineFunction &YamlMF) {
58409467b48Spatrick MachineFunction &MF = PFS.MF;
58509467b48Spatrick MachineRegisterInfo &RegInfo = MF.getRegInfo();
58609467b48Spatrick assert(RegInfo.tracksLiveness());
58709467b48Spatrick if (!YamlMF.TracksRegLiveness)
58809467b48Spatrick RegInfo.invalidateLiveness();
58909467b48Spatrick
59009467b48Spatrick SMDiagnostic Error;
59109467b48Spatrick // Parse the virtual register information.
59209467b48Spatrick for (const auto &VReg : YamlMF.VirtualRegisters) {
59309467b48Spatrick VRegInfo &Info = PFS.getVRegInfo(VReg.ID.Value);
59409467b48Spatrick if (Info.Explicit)
59509467b48Spatrick return error(VReg.ID.SourceRange.Start,
59609467b48Spatrick Twine("redefinition of virtual register '%") +
59709467b48Spatrick Twine(VReg.ID.Value) + "'");
59809467b48Spatrick Info.Explicit = true;
59909467b48Spatrick
60009467b48Spatrick if (StringRef(VReg.Class.Value).equals("_")) {
60109467b48Spatrick Info.Kind = VRegInfo::GENERIC;
60209467b48Spatrick Info.D.RegBank = nullptr;
60309467b48Spatrick } else {
60409467b48Spatrick const auto *RC = Target->getRegClass(VReg.Class.Value);
60509467b48Spatrick if (RC) {
60609467b48Spatrick Info.Kind = VRegInfo::NORMAL;
60709467b48Spatrick Info.D.RC = RC;
60809467b48Spatrick } else {
60909467b48Spatrick const RegisterBank *RegBank = Target->getRegBank(VReg.Class.Value);
61009467b48Spatrick if (!RegBank)
61109467b48Spatrick return error(
61209467b48Spatrick VReg.Class.SourceRange.Start,
61309467b48Spatrick Twine("use of undefined register class or register bank '") +
61409467b48Spatrick VReg.Class.Value + "'");
61509467b48Spatrick Info.Kind = VRegInfo::REGBANK;
61609467b48Spatrick Info.D.RegBank = RegBank;
61709467b48Spatrick }
61809467b48Spatrick }
61909467b48Spatrick
62009467b48Spatrick if (!VReg.PreferredRegister.Value.empty()) {
62109467b48Spatrick if (Info.Kind != VRegInfo::NORMAL)
62209467b48Spatrick return error(VReg.Class.SourceRange.Start,
62309467b48Spatrick Twine("preferred register can only be set for normal vregs"));
62409467b48Spatrick
62509467b48Spatrick if (parseRegisterReference(PFS, Info.PreferredReg,
62609467b48Spatrick VReg.PreferredRegister.Value, Error))
62709467b48Spatrick return error(Error, VReg.PreferredRegister.SourceRange);
62809467b48Spatrick }
62909467b48Spatrick }
63009467b48Spatrick
63109467b48Spatrick // Parse the liveins.
63209467b48Spatrick for (const auto &LiveIn : YamlMF.LiveIns) {
633097a140dSpatrick Register Reg;
63409467b48Spatrick if (parseNamedRegisterReference(PFS, Reg, LiveIn.Register.Value, Error))
63509467b48Spatrick return error(Error, LiveIn.Register.SourceRange);
636097a140dSpatrick Register VReg;
63709467b48Spatrick if (!LiveIn.VirtualRegister.Value.empty()) {
63809467b48Spatrick VRegInfo *Info;
63909467b48Spatrick if (parseVirtualRegisterReference(PFS, Info, LiveIn.VirtualRegister.Value,
64009467b48Spatrick Error))
64109467b48Spatrick return error(Error, LiveIn.VirtualRegister.SourceRange);
64209467b48Spatrick VReg = Info->VReg;
64309467b48Spatrick }
64409467b48Spatrick RegInfo.addLiveIn(Reg, VReg);
64509467b48Spatrick }
64609467b48Spatrick
64709467b48Spatrick // Parse the callee saved registers (Registers that will
64809467b48Spatrick // be saved for the caller).
64909467b48Spatrick if (YamlMF.CalleeSavedRegisters) {
65009467b48Spatrick SmallVector<MCPhysReg, 16> CalleeSavedRegisters;
651*d415bd75Srobert for (const auto &RegSource : *YamlMF.CalleeSavedRegisters) {
652097a140dSpatrick Register Reg;
65309467b48Spatrick if (parseNamedRegisterReference(PFS, Reg, RegSource.Value, Error))
65409467b48Spatrick return error(Error, RegSource.SourceRange);
65509467b48Spatrick CalleeSavedRegisters.push_back(Reg);
65609467b48Spatrick }
65709467b48Spatrick RegInfo.setCalleeSavedRegs(CalleeSavedRegisters);
65809467b48Spatrick }
65909467b48Spatrick
66009467b48Spatrick return false;
66109467b48Spatrick }
66209467b48Spatrick
setupRegisterInfo(const PerFunctionMIParsingState & PFS,const yaml::MachineFunction & YamlMF)66309467b48Spatrick bool MIRParserImpl::setupRegisterInfo(const PerFunctionMIParsingState &PFS,
66409467b48Spatrick const yaml::MachineFunction &YamlMF) {
66509467b48Spatrick MachineFunction &MF = PFS.MF;
66609467b48Spatrick MachineRegisterInfo &MRI = MF.getRegInfo();
667*d415bd75Srobert const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
668*d415bd75Srobert
66909467b48Spatrick bool Error = false;
67009467b48Spatrick // Create VRegs
67109467b48Spatrick auto populateVRegInfo = [&](const VRegInfo &Info, Twine Name) {
672097a140dSpatrick Register Reg = Info.VReg;
67309467b48Spatrick switch (Info.Kind) {
67409467b48Spatrick case VRegInfo::UNKNOWN:
67509467b48Spatrick error(Twine("Cannot determine class/bank of virtual register ") +
67609467b48Spatrick Name + " in function '" + MF.getName() + "'");
67709467b48Spatrick Error = true;
67809467b48Spatrick break;
67909467b48Spatrick case VRegInfo::NORMAL:
680*d415bd75Srobert if (!Info.D.RC->isAllocatable()) {
681*d415bd75Srobert error(Twine("Cannot use non-allocatable class '") +
682*d415bd75Srobert TRI->getRegClassName(Info.D.RC) + "' for virtual register " +
683*d415bd75Srobert Name + " in function '" + MF.getName() + "'");
684*d415bd75Srobert Error = true;
685*d415bd75Srobert break;
686*d415bd75Srobert }
687*d415bd75Srobert
68809467b48Spatrick MRI.setRegClass(Reg, Info.D.RC);
68909467b48Spatrick if (Info.PreferredReg != 0)
69009467b48Spatrick MRI.setSimpleHint(Reg, Info.PreferredReg);
69109467b48Spatrick break;
69209467b48Spatrick case VRegInfo::GENERIC:
69309467b48Spatrick break;
69409467b48Spatrick case VRegInfo::REGBANK:
69509467b48Spatrick MRI.setRegBank(Reg, *Info.D.RegBank);
69609467b48Spatrick break;
69709467b48Spatrick }
69809467b48Spatrick };
69909467b48Spatrick
70073471bf0Spatrick for (const auto &P : PFS.VRegInfosNamed) {
70173471bf0Spatrick const VRegInfo &Info = *P.second;
70273471bf0Spatrick populateVRegInfo(Info, Twine(P.first()));
70309467b48Spatrick }
70409467b48Spatrick
70509467b48Spatrick for (auto P : PFS.VRegInfos) {
70609467b48Spatrick const VRegInfo &Info = *P.second;
70709467b48Spatrick populateVRegInfo(Info, Twine(P.first));
70809467b48Spatrick }
70909467b48Spatrick
71009467b48Spatrick // Compute MachineRegisterInfo::UsedPhysRegMask
71109467b48Spatrick for (const MachineBasicBlock &MBB : MF) {
71273471bf0Spatrick // Make sure MRI knows about registers clobbered by unwinder.
71373471bf0Spatrick if (MBB.isEHPad())
71473471bf0Spatrick if (auto *RegMask = TRI->getCustomEHPadPreservedMask(MF))
71573471bf0Spatrick MRI.addPhysRegsUsedFromRegMask(RegMask);
71673471bf0Spatrick
71709467b48Spatrick for (const MachineInstr &MI : MBB) {
71809467b48Spatrick for (const MachineOperand &MO : MI.operands()) {
71909467b48Spatrick if (!MO.isRegMask())
72009467b48Spatrick continue;
72109467b48Spatrick MRI.addPhysRegsUsedFromRegMask(MO.getRegMask());
72209467b48Spatrick }
72309467b48Spatrick }
72409467b48Spatrick }
72509467b48Spatrick
72609467b48Spatrick return Error;
72709467b48Spatrick }
72809467b48Spatrick
initializeFrameInfo(PerFunctionMIParsingState & PFS,const yaml::MachineFunction & YamlMF)72909467b48Spatrick bool MIRParserImpl::initializeFrameInfo(PerFunctionMIParsingState &PFS,
73009467b48Spatrick const yaml::MachineFunction &YamlMF) {
73109467b48Spatrick MachineFunction &MF = PFS.MF;
73209467b48Spatrick MachineFrameInfo &MFI = MF.getFrameInfo();
73309467b48Spatrick const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
73409467b48Spatrick const Function &F = MF.getFunction();
73509467b48Spatrick const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo;
73609467b48Spatrick MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken);
73709467b48Spatrick MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken);
73809467b48Spatrick MFI.setHasStackMap(YamlMFI.HasStackMap);
73909467b48Spatrick MFI.setHasPatchPoint(YamlMFI.HasPatchPoint);
74009467b48Spatrick MFI.setStackSize(YamlMFI.StackSize);
74109467b48Spatrick MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment);
74209467b48Spatrick if (YamlMFI.MaxAlignment)
743097a140dSpatrick MFI.ensureMaxAlignment(Align(YamlMFI.MaxAlignment));
74409467b48Spatrick MFI.setAdjustsStack(YamlMFI.AdjustsStack);
74509467b48Spatrick MFI.setHasCalls(YamlMFI.HasCalls);
74609467b48Spatrick if (YamlMFI.MaxCallFrameSize != ~0u)
74709467b48Spatrick MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize);
74809467b48Spatrick MFI.setCVBytesOfCalleeSavedRegisters(YamlMFI.CVBytesOfCalleeSavedRegisters);
74909467b48Spatrick MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment);
75009467b48Spatrick MFI.setHasVAStart(YamlMFI.HasVAStart);
75109467b48Spatrick MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc);
75273471bf0Spatrick MFI.setHasTailCall(YamlMFI.HasTailCall);
75309467b48Spatrick MFI.setLocalFrameSize(YamlMFI.LocalFrameSize);
75409467b48Spatrick if (!YamlMFI.SavePoint.Value.empty()) {
75509467b48Spatrick MachineBasicBlock *MBB = nullptr;
75609467b48Spatrick if (parseMBBReference(PFS, MBB, YamlMFI.SavePoint))
75709467b48Spatrick return true;
75809467b48Spatrick MFI.setSavePoint(MBB);
75909467b48Spatrick }
76009467b48Spatrick if (!YamlMFI.RestorePoint.Value.empty()) {
76109467b48Spatrick MachineBasicBlock *MBB = nullptr;
76209467b48Spatrick if (parseMBBReference(PFS, MBB, YamlMFI.RestorePoint))
76309467b48Spatrick return true;
76409467b48Spatrick MFI.setRestorePoint(MBB);
76509467b48Spatrick }
76609467b48Spatrick
76709467b48Spatrick std::vector<CalleeSavedInfo> CSIInfo;
76809467b48Spatrick // Initialize the fixed frame objects.
76909467b48Spatrick for (const auto &Object : YamlMF.FixedStackObjects) {
77009467b48Spatrick int ObjectIdx;
77109467b48Spatrick if (Object.Type != yaml::FixedMachineStackObject::SpillSlot)
77209467b48Spatrick ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset,
77309467b48Spatrick Object.IsImmutable, Object.IsAliased);
77409467b48Spatrick else
77509467b48Spatrick ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset);
77609467b48Spatrick
77709467b48Spatrick if (!TFI->isSupportedStackID(Object.StackID))
77809467b48Spatrick return error(Object.ID.SourceRange.Start,
77909467b48Spatrick Twine("StackID is not supported by target"));
78009467b48Spatrick MFI.setStackID(ObjectIdx, Object.StackID);
781097a140dSpatrick MFI.setObjectAlignment(ObjectIdx, Object.Alignment.valueOrOne());
78209467b48Spatrick if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value,
78309467b48Spatrick ObjectIdx))
78409467b48Spatrick .second)
78509467b48Spatrick return error(Object.ID.SourceRange.Start,
78609467b48Spatrick Twine("redefinition of fixed stack object '%fixed-stack.") +
78709467b48Spatrick Twine(Object.ID.Value) + "'");
78809467b48Spatrick if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
78909467b48Spatrick Object.CalleeSavedRestored, ObjectIdx))
79009467b48Spatrick return true;
79109467b48Spatrick if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
79209467b48Spatrick return true;
79309467b48Spatrick }
79409467b48Spatrick
79509467b48Spatrick // Initialize the ordinary frame objects.
79609467b48Spatrick for (const auto &Object : YamlMF.StackObjects) {
79709467b48Spatrick int ObjectIdx;
79809467b48Spatrick const AllocaInst *Alloca = nullptr;
79909467b48Spatrick const yaml::StringValue &Name = Object.Name;
80009467b48Spatrick if (!Name.Value.empty()) {
80109467b48Spatrick Alloca = dyn_cast_or_null<AllocaInst>(
80209467b48Spatrick F.getValueSymbolTable()->lookup(Name.Value));
80309467b48Spatrick if (!Alloca)
80409467b48Spatrick return error(Name.SourceRange.Start,
80509467b48Spatrick "alloca instruction named '" + Name.Value +
80609467b48Spatrick "' isn't defined in the function '" + F.getName() +
80709467b48Spatrick "'");
80809467b48Spatrick }
80909467b48Spatrick if (!TFI->isSupportedStackID(Object.StackID))
81009467b48Spatrick return error(Object.ID.SourceRange.Start,
81109467b48Spatrick Twine("StackID is not supported by target"));
81209467b48Spatrick if (Object.Type == yaml::MachineStackObject::VariableSized)
813097a140dSpatrick ObjectIdx =
814097a140dSpatrick MFI.CreateVariableSizedObject(Object.Alignment.valueOrOne(), Alloca);
81509467b48Spatrick else
81609467b48Spatrick ObjectIdx = MFI.CreateStackObject(
817097a140dSpatrick Object.Size, Object.Alignment.valueOrOne(),
81809467b48Spatrick Object.Type == yaml::MachineStackObject::SpillSlot, Alloca,
81909467b48Spatrick Object.StackID);
82009467b48Spatrick MFI.setObjectOffset(ObjectIdx, Object.Offset);
82109467b48Spatrick
82209467b48Spatrick if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx))
82309467b48Spatrick .second)
82409467b48Spatrick return error(Object.ID.SourceRange.Start,
82509467b48Spatrick Twine("redefinition of stack object '%stack.") +
82609467b48Spatrick Twine(Object.ID.Value) + "'");
82709467b48Spatrick if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister,
82809467b48Spatrick Object.CalleeSavedRestored, ObjectIdx))
82909467b48Spatrick return true;
83009467b48Spatrick if (Object.LocalOffset)
831*d415bd75Srobert MFI.mapLocalFrameObject(ObjectIdx, *Object.LocalOffset);
83209467b48Spatrick if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx))
83309467b48Spatrick return true;
83409467b48Spatrick }
83509467b48Spatrick MFI.setCalleeSavedInfo(CSIInfo);
83609467b48Spatrick if (!CSIInfo.empty())
83709467b48Spatrick MFI.setCalleeSavedInfoValid(true);
83809467b48Spatrick
83909467b48Spatrick // Initialize the various stack object references after initializing the
84009467b48Spatrick // stack objects.
84109467b48Spatrick if (!YamlMFI.StackProtector.Value.empty()) {
84209467b48Spatrick SMDiagnostic Error;
84309467b48Spatrick int FI;
84409467b48Spatrick if (parseStackObjectReference(PFS, FI, YamlMFI.StackProtector.Value, Error))
84509467b48Spatrick return error(Error, YamlMFI.StackProtector.SourceRange);
84609467b48Spatrick MFI.setStackProtectorIndex(FI);
84709467b48Spatrick }
848*d415bd75Srobert
849*d415bd75Srobert if (!YamlMFI.FunctionContext.Value.empty()) {
850*d415bd75Srobert SMDiagnostic Error;
851*d415bd75Srobert int FI;
852*d415bd75Srobert if (parseStackObjectReference(PFS, FI, YamlMFI.FunctionContext.Value, Error))
853*d415bd75Srobert return error(Error, YamlMFI.FunctionContext.SourceRange);
854*d415bd75Srobert MFI.setFunctionContextIndex(FI);
855*d415bd75Srobert }
856*d415bd75Srobert
85709467b48Spatrick return false;
85809467b48Spatrick }
85909467b48Spatrick
parseCalleeSavedRegister(PerFunctionMIParsingState & PFS,std::vector<CalleeSavedInfo> & CSIInfo,const yaml::StringValue & RegisterSource,bool IsRestored,int FrameIdx)86009467b48Spatrick bool MIRParserImpl::parseCalleeSavedRegister(PerFunctionMIParsingState &PFS,
86109467b48Spatrick std::vector<CalleeSavedInfo> &CSIInfo,
86209467b48Spatrick const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx) {
86309467b48Spatrick if (RegisterSource.Value.empty())
86409467b48Spatrick return false;
865097a140dSpatrick Register Reg;
86609467b48Spatrick SMDiagnostic Error;
86709467b48Spatrick if (parseNamedRegisterReference(PFS, Reg, RegisterSource.Value, Error))
86809467b48Spatrick return error(Error, RegisterSource.SourceRange);
86909467b48Spatrick CalleeSavedInfo CSI(Reg, FrameIdx);
87009467b48Spatrick CSI.setRestored(IsRestored);
87109467b48Spatrick CSIInfo.push_back(CSI);
87209467b48Spatrick return false;
87309467b48Spatrick }
87409467b48Spatrick
87509467b48Spatrick /// Verify that given node is of a certain type. Return true on error.
87609467b48Spatrick template <typename T>
typecheckMDNode(T * & Result,MDNode * Node,const yaml::StringValue & Source,StringRef TypeString,MIRParserImpl & Parser)87709467b48Spatrick static bool typecheckMDNode(T *&Result, MDNode *Node,
87809467b48Spatrick const yaml::StringValue &Source,
87909467b48Spatrick StringRef TypeString, MIRParserImpl &Parser) {
88009467b48Spatrick if (!Node)
88109467b48Spatrick return false;
88209467b48Spatrick Result = dyn_cast<T>(Node);
88309467b48Spatrick if (!Result)
88409467b48Spatrick return Parser.error(Source.SourceRange.Start,
88509467b48Spatrick "expected a reference to a '" + TypeString +
88609467b48Spatrick "' metadata node");
88709467b48Spatrick return false;
88809467b48Spatrick }
88909467b48Spatrick
89009467b48Spatrick template <typename T>
parseStackObjectsDebugInfo(PerFunctionMIParsingState & PFS,const T & Object,int FrameIdx)89109467b48Spatrick bool MIRParserImpl::parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS,
89209467b48Spatrick const T &Object, int FrameIdx) {
89309467b48Spatrick // Debug information can only be attached to stack objects; Fixed stack
89409467b48Spatrick // objects aren't supported.
89509467b48Spatrick MDNode *Var = nullptr, *Expr = nullptr, *Loc = nullptr;
89609467b48Spatrick if (parseMDNode(PFS, Var, Object.DebugVar) ||
89709467b48Spatrick parseMDNode(PFS, Expr, Object.DebugExpr) ||
89809467b48Spatrick parseMDNode(PFS, Loc, Object.DebugLoc))
89909467b48Spatrick return true;
90009467b48Spatrick if (!Var && !Expr && !Loc)
90109467b48Spatrick return false;
90209467b48Spatrick DILocalVariable *DIVar = nullptr;
90309467b48Spatrick DIExpression *DIExpr = nullptr;
90409467b48Spatrick DILocation *DILoc = nullptr;
90509467b48Spatrick if (typecheckMDNode(DIVar, Var, Object.DebugVar, "DILocalVariable", *this) ||
90609467b48Spatrick typecheckMDNode(DIExpr, Expr, Object.DebugExpr, "DIExpression", *this) ||
90709467b48Spatrick typecheckMDNode(DILoc, Loc, Object.DebugLoc, "DILocation", *this))
90809467b48Spatrick return true;
90909467b48Spatrick PFS.MF.setVariableDbgInfo(DIVar, DIExpr, FrameIdx, DILoc);
91009467b48Spatrick return false;
91109467b48Spatrick }
91209467b48Spatrick
parseMDNode(PerFunctionMIParsingState & PFS,MDNode * & Node,const yaml::StringValue & Source)91309467b48Spatrick bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState &PFS,
91409467b48Spatrick MDNode *&Node, const yaml::StringValue &Source) {
91509467b48Spatrick if (Source.Value.empty())
91609467b48Spatrick return false;
91709467b48Spatrick SMDiagnostic Error;
91809467b48Spatrick if (llvm::parseMDNode(PFS, Node, Source.Value, Error))
91909467b48Spatrick return error(Error, Source.SourceRange);
92009467b48Spatrick return false;
92109467b48Spatrick }
92209467b48Spatrick
initializeConstantPool(PerFunctionMIParsingState & PFS,MachineConstantPool & ConstantPool,const yaml::MachineFunction & YamlMF)92309467b48Spatrick bool MIRParserImpl::initializeConstantPool(PerFunctionMIParsingState &PFS,
92409467b48Spatrick MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF) {
92509467b48Spatrick DenseMap<unsigned, unsigned> &ConstantPoolSlots = PFS.ConstantPoolSlots;
92609467b48Spatrick const MachineFunction &MF = PFS.MF;
92709467b48Spatrick const auto &M = *MF.getFunction().getParent();
92809467b48Spatrick SMDiagnostic Error;
92909467b48Spatrick for (const auto &YamlConstant : YamlMF.Constants) {
93009467b48Spatrick if (YamlConstant.IsTargetSpecific)
93109467b48Spatrick // FIXME: Support target-specific constant pools
93209467b48Spatrick return error(YamlConstant.Value.SourceRange.Start,
93309467b48Spatrick "Can't parse target-specific constant pool entries yet");
93409467b48Spatrick const Constant *Value = dyn_cast_or_null<Constant>(
93509467b48Spatrick parseConstantValue(YamlConstant.Value.Value, Error, M));
93609467b48Spatrick if (!Value)
93709467b48Spatrick return error(Error, YamlConstant.Value.SourceRange);
938097a140dSpatrick const Align PrefTypeAlign =
939097a140dSpatrick M.getDataLayout().getPrefTypeAlign(Value->getType());
940*d415bd75Srobert const Align Alignment = YamlConstant.Alignment.value_or(PrefTypeAlign);
94109467b48Spatrick unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment);
94209467b48Spatrick if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index))
94309467b48Spatrick .second)
94409467b48Spatrick return error(YamlConstant.ID.SourceRange.Start,
94509467b48Spatrick Twine("redefinition of constant pool item '%const.") +
94609467b48Spatrick Twine(YamlConstant.ID.Value) + "'");
94709467b48Spatrick }
94809467b48Spatrick return false;
94909467b48Spatrick }
95009467b48Spatrick
initializeJumpTableInfo(PerFunctionMIParsingState & PFS,const yaml::MachineJumpTable & YamlJTI)95109467b48Spatrick bool MIRParserImpl::initializeJumpTableInfo(PerFunctionMIParsingState &PFS,
95209467b48Spatrick const yaml::MachineJumpTable &YamlJTI) {
95309467b48Spatrick MachineJumpTableInfo *JTI = PFS.MF.getOrCreateJumpTableInfo(YamlJTI.Kind);
95409467b48Spatrick for (const auto &Entry : YamlJTI.Entries) {
95509467b48Spatrick std::vector<MachineBasicBlock *> Blocks;
95609467b48Spatrick for (const auto &MBBSource : Entry.Blocks) {
95709467b48Spatrick MachineBasicBlock *MBB = nullptr;
95809467b48Spatrick if (parseMBBReference(PFS, MBB, MBBSource.Value))
95909467b48Spatrick return true;
96009467b48Spatrick Blocks.push_back(MBB);
96109467b48Spatrick }
96209467b48Spatrick unsigned Index = JTI->createJumpTableIndex(Blocks);
96309467b48Spatrick if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index))
96409467b48Spatrick .second)
96509467b48Spatrick return error(Entry.ID.SourceRange.Start,
96609467b48Spatrick Twine("redefinition of jump table entry '%jump-table.") +
96709467b48Spatrick Twine(Entry.ID.Value) + "'");
96809467b48Spatrick }
96909467b48Spatrick return false;
97009467b48Spatrick }
97109467b48Spatrick
parseMBBReference(PerFunctionMIParsingState & PFS,MachineBasicBlock * & MBB,const yaml::StringValue & Source)97209467b48Spatrick bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState &PFS,
97309467b48Spatrick MachineBasicBlock *&MBB,
97409467b48Spatrick const yaml::StringValue &Source) {
97509467b48Spatrick SMDiagnostic Error;
97609467b48Spatrick if (llvm::parseMBBReference(PFS, MBB, Source.Value, Error))
97709467b48Spatrick return error(Error, Source.SourceRange);
97809467b48Spatrick return false;
97909467b48Spatrick }
98009467b48Spatrick
parseMachineMetadata(PerFunctionMIParsingState & PFS,const yaml::StringValue & Source)98173471bf0Spatrick bool MIRParserImpl::parseMachineMetadata(PerFunctionMIParsingState &PFS,
98273471bf0Spatrick const yaml::StringValue &Source) {
98373471bf0Spatrick SMDiagnostic Error;
98473471bf0Spatrick if (llvm::parseMachineMetadata(PFS, Source.Value, Source.SourceRange, Error))
98573471bf0Spatrick return error(Error, Source.SourceRange);
98673471bf0Spatrick return false;
98773471bf0Spatrick }
98873471bf0Spatrick
parseMachineMetadataNodes(PerFunctionMIParsingState & PFS,MachineFunction & MF,const yaml::MachineFunction & YMF)98973471bf0Spatrick bool MIRParserImpl::parseMachineMetadataNodes(
99073471bf0Spatrick PerFunctionMIParsingState &PFS, MachineFunction &MF,
99173471bf0Spatrick const yaml::MachineFunction &YMF) {
992*d415bd75Srobert for (const auto &MDS : YMF.MachineMetadataNodes) {
99373471bf0Spatrick if (parseMachineMetadata(PFS, MDS))
99473471bf0Spatrick return true;
99573471bf0Spatrick }
99673471bf0Spatrick // Report missing definitions from forward referenced nodes.
99773471bf0Spatrick if (!PFS.MachineForwardRefMDNodes.empty())
99873471bf0Spatrick return error(PFS.MachineForwardRefMDNodes.begin()->second.second,
99973471bf0Spatrick "use of undefined metadata '!" +
100073471bf0Spatrick Twine(PFS.MachineForwardRefMDNodes.begin()->first) + "'");
100173471bf0Spatrick return false;
100273471bf0Spatrick }
100373471bf0Spatrick
diagFromMIStringDiag(const SMDiagnostic & Error,SMRange SourceRange)100409467b48Spatrick SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error,
100509467b48Spatrick SMRange SourceRange) {
100609467b48Spatrick assert(SourceRange.isValid() && "Invalid source range");
100709467b48Spatrick SMLoc Loc = SourceRange.Start;
100809467b48Spatrick bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() &&
100909467b48Spatrick *Loc.getPointer() == '\'';
101009467b48Spatrick // Translate the location of the error from the location in the MI string to
101109467b48Spatrick // the corresponding location in the MIR file.
101209467b48Spatrick Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() +
101309467b48Spatrick (HasQuote ? 1 : 0));
101409467b48Spatrick
101509467b48Spatrick // TODO: Translate any source ranges as well.
1016*d415bd75Srobert return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), std::nullopt,
101709467b48Spatrick Error.getFixIts());
101809467b48Spatrick }
101909467b48Spatrick
diagFromBlockStringDiag(const SMDiagnostic & Error,SMRange SourceRange)102009467b48Spatrick SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error,
102109467b48Spatrick SMRange SourceRange) {
102209467b48Spatrick assert(SourceRange.isValid());
102309467b48Spatrick
102409467b48Spatrick // Translate the location of the error from the location in the llvm IR string
102509467b48Spatrick // to the corresponding location in the MIR file.
102609467b48Spatrick auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start);
102709467b48Spatrick unsigned Line = LineAndColumn.first + Error.getLineNo() - 1;
102809467b48Spatrick unsigned Column = Error.getColumnNo();
102909467b48Spatrick StringRef LineStr = Error.getLineContents();
103009467b48Spatrick SMLoc Loc = Error.getLoc();
103109467b48Spatrick
103209467b48Spatrick // Get the full line and adjust the column number by taking the indentation of
103309467b48Spatrick // LLVM IR into account.
103409467b48Spatrick for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E;
103509467b48Spatrick L != E; ++L) {
103609467b48Spatrick if (L.line_number() == Line) {
103709467b48Spatrick LineStr = *L;
103809467b48Spatrick Loc = SMLoc::getFromPointer(LineStr.data());
103909467b48Spatrick auto Indent = LineStr.find(Error.getLineContents());
104009467b48Spatrick if (Indent != StringRef::npos)
104109467b48Spatrick Column += Indent;
104209467b48Spatrick break;
104309467b48Spatrick }
104409467b48Spatrick }
104509467b48Spatrick
104609467b48Spatrick return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(),
104709467b48Spatrick Error.getMessage(), LineStr, Error.getRanges(),
104809467b48Spatrick Error.getFixIts());
104909467b48Spatrick }
105009467b48Spatrick
MIRParser(std::unique_ptr<MIRParserImpl> Impl)105109467b48Spatrick MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl)
105209467b48Spatrick : Impl(std::move(Impl)) {}
105309467b48Spatrick
1054*d415bd75Srobert MIRParser::~MIRParser() = default;
105509467b48Spatrick
1056097a140dSpatrick std::unique_ptr<Module>
parseIRModule(DataLayoutCallbackTy DataLayoutCallback)1057097a140dSpatrick MIRParser::parseIRModule(DataLayoutCallbackTy DataLayoutCallback) {
1058097a140dSpatrick return Impl->parseIRModule(DataLayoutCallback);
105909467b48Spatrick }
106009467b48Spatrick
parseMachineFunctions(Module & M,MachineModuleInfo & MMI)106109467b48Spatrick bool MIRParser::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) {
106209467b48Spatrick return Impl->parseMachineFunctions(M, MMI);
106309467b48Spatrick }
106409467b48Spatrick
createMIRParserFromFile(StringRef Filename,SMDiagnostic & Error,LLVMContext & Context,std::function<void (Function &)> ProcessIRFunction)106509467b48Spatrick std::unique_ptr<MIRParser> llvm::createMIRParserFromFile(
106609467b48Spatrick StringRef Filename, SMDiagnostic &Error, LLVMContext &Context,
106709467b48Spatrick std::function<void(Function &)> ProcessIRFunction) {
106873471bf0Spatrick auto FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/true);
106909467b48Spatrick if (std::error_code EC = FileOrErr.getError()) {
107009467b48Spatrick Error = SMDiagnostic(Filename, SourceMgr::DK_Error,
107109467b48Spatrick "Could not open input file: " + EC.message());
107209467b48Spatrick return nullptr;
107309467b48Spatrick }
107409467b48Spatrick return createMIRParser(std::move(FileOrErr.get()), Context,
107509467b48Spatrick ProcessIRFunction);
107609467b48Spatrick }
107709467b48Spatrick
107809467b48Spatrick std::unique_ptr<MIRParser>
createMIRParser(std::unique_ptr<MemoryBuffer> Contents,LLVMContext & Context,std::function<void (Function &)> ProcessIRFunction)107909467b48Spatrick llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents,
108009467b48Spatrick LLVMContext &Context,
108109467b48Spatrick std::function<void(Function &)> ProcessIRFunction) {
108209467b48Spatrick auto Filename = Contents->getBufferIdentifier();
108309467b48Spatrick if (Context.shouldDiscardValueNames()) {
108409467b48Spatrick Context.diagnose(DiagnosticInfoMIRParser(
108509467b48Spatrick DS_Error,
108609467b48Spatrick SMDiagnostic(
108709467b48Spatrick Filename, SourceMgr::DK_Error,
108809467b48Spatrick "Can't read MIR with a Context that discards named Values")));
108909467b48Spatrick return nullptr;
109009467b48Spatrick }
109109467b48Spatrick return std::make_unique<MIRParser>(std::make_unique<MIRParserImpl>(
109209467b48Spatrick std::move(Contents), Filename, Context, ProcessIRFunction));
109309467b48Spatrick }
1094