1 //===- MIRParser.cpp - MIR serialization format parser implementation -----===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the class that parses the optional LLVM IR and machine 10 // functions that are stored in MIR files. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/CodeGen/MIRParser/MIRParser.h" 15 #include "llvm/ADT/DenseMap.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/StringMap.h" 18 #include "llvm/ADT/StringRef.h" 19 #include "llvm/AsmParser/Parser.h" 20 #include "llvm/AsmParser/SlotMapping.h" 21 #include "llvm/CodeGen/GlobalISel/RegisterBank.h" 22 #include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h" 23 #include "llvm/CodeGen/MIRParser/MIParser.h" 24 #include "llvm/CodeGen/MIRYamlMapping.h" 25 #include "llvm/CodeGen/MachineConstantPool.h" 26 #include "llvm/CodeGen/MachineFrameInfo.h" 27 #include "llvm/CodeGen/MachineFunction.h" 28 #include "llvm/CodeGen/MachineModuleInfo.h" 29 #include "llvm/CodeGen/MachineRegisterInfo.h" 30 #include "llvm/CodeGen/TargetFrameLowering.h" 31 #include "llvm/IR/BasicBlock.h" 32 #include "llvm/IR/DebugInfo.h" 33 #include "llvm/IR/DiagnosticInfo.h" 34 #include "llvm/IR/Instructions.h" 35 #include "llvm/IR/LLVMContext.h" 36 #include "llvm/IR/Module.h" 37 #include "llvm/IR/ValueSymbolTable.h" 38 #include "llvm/Support/LineIterator.h" 39 #include "llvm/Support/MemoryBuffer.h" 40 #include "llvm/Support/SMLoc.h" 41 #include "llvm/Support/SourceMgr.h" 42 #include "llvm/Support/YAMLTraits.h" 43 #include "llvm/Target/TargetMachine.h" 44 #include <memory> 45 46 using namespace llvm; 47 48 namespace llvm { 49 50 /// This class implements the parsing of LLVM IR that's embedded inside a MIR 51 /// file. 52 class MIRParserImpl { 53 SourceMgr SM; 54 yaml::Input In; 55 StringRef Filename; 56 LLVMContext &Context; 57 SlotMapping IRSlots; 58 std::unique_ptr<PerTargetMIParsingState> Target; 59 60 /// True when the MIR file doesn't have LLVM IR. Dummy IR functions are 61 /// created and inserted into the given module when this is true. 62 bool NoLLVMIR = false; 63 /// True when a well formed MIR file does not contain any MIR/machine function 64 /// parts. 65 bool NoMIRDocuments = false; 66 67 std::function<void(Function &)> ProcessIRFunction; 68 69 public: 70 MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, StringRef Filename, 71 LLVMContext &Context, 72 std::function<void(Function &)> ProcessIRFunction); 73 74 void reportDiagnostic(const SMDiagnostic &Diag); 75 76 /// Report an error with the given message at unknown location. 77 /// 78 /// Always returns true. 79 bool error(const Twine &Message); 80 81 /// Report an error with the given message at the given location. 82 /// 83 /// Always returns true. 84 bool error(SMLoc Loc, const Twine &Message); 85 86 /// Report a given error with the location translated from the location in an 87 /// embedded string literal to a location in the MIR file. 88 /// 89 /// Always returns true. 90 bool error(const SMDiagnostic &Error, SMRange SourceRange); 91 92 /// Try to parse the optional LLVM module and the machine functions in the MIR 93 /// file. 94 /// 95 /// Return null if an error occurred. 96 std::unique_ptr<Module> parseIRModule(); 97 98 /// Create an empty function with the given name. 99 Function *createDummyFunction(StringRef Name, Module &M); 100 101 bool parseMachineFunctions(Module &M, MachineModuleInfo &MMI); 102 103 /// Parse the machine function in the current YAML document. 104 /// 105 /// 106 /// Return true if an error occurred. 107 bool parseMachineFunction(Module &M, MachineModuleInfo &MMI); 108 109 /// Initialize the machine function to the state that's described in the MIR 110 /// file. 111 /// 112 /// Return true if error occurred. 113 bool initializeMachineFunction(const yaml::MachineFunction &YamlMF, 114 MachineFunction &MF); 115 116 bool parseRegisterInfo(PerFunctionMIParsingState &PFS, 117 const yaml::MachineFunction &YamlMF); 118 119 bool setupRegisterInfo(const PerFunctionMIParsingState &PFS, 120 const yaml::MachineFunction &YamlMF); 121 122 bool initializeFrameInfo(PerFunctionMIParsingState &PFS, 123 const yaml::MachineFunction &YamlMF); 124 125 bool initializeCallSiteInfo(PerFunctionMIParsingState &PFS, 126 const yaml::MachineFunction &YamlMF); 127 128 bool parseCalleeSavedRegister(PerFunctionMIParsingState &PFS, 129 std::vector<CalleeSavedInfo> &CSIInfo, 130 const yaml::StringValue &RegisterSource, 131 bool IsRestored, int FrameIdx); 132 133 template <typename T> 134 bool parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS, 135 const T &Object, 136 int FrameIdx); 137 138 bool initializeConstantPool(PerFunctionMIParsingState &PFS, 139 MachineConstantPool &ConstantPool, 140 const yaml::MachineFunction &YamlMF); 141 142 bool initializeJumpTableInfo(PerFunctionMIParsingState &PFS, 143 const yaml::MachineJumpTable &YamlJTI); 144 145 private: 146 bool parseMDNode(PerFunctionMIParsingState &PFS, MDNode *&Node, 147 const yaml::StringValue &Source); 148 149 bool parseMBBReference(PerFunctionMIParsingState &PFS, 150 MachineBasicBlock *&MBB, 151 const yaml::StringValue &Source); 152 153 /// Return a MIR diagnostic converted from an MI string diagnostic. 154 SMDiagnostic diagFromMIStringDiag(const SMDiagnostic &Error, 155 SMRange SourceRange); 156 157 /// Return a MIR diagnostic converted from a diagnostic located in a YAML 158 /// block scalar string. 159 SMDiagnostic diagFromBlockStringDiag(const SMDiagnostic &Error, 160 SMRange SourceRange); 161 162 void computeFunctionProperties(MachineFunction &MF); 163 }; 164 165 } // end namespace llvm 166 167 static void handleYAMLDiag(const SMDiagnostic &Diag, void *Context) { 168 reinterpret_cast<MIRParserImpl *>(Context)->reportDiagnostic(Diag); 169 } 170 171 MIRParserImpl::MIRParserImpl(std::unique_ptr<MemoryBuffer> Contents, 172 StringRef Filename, LLVMContext &Context, 173 std::function<void(Function &)> Callback) 174 : SM(), 175 In(SM.getMemoryBuffer(SM.AddNewSourceBuffer(std::move(Contents), SMLoc())) 176 ->getBuffer(), 177 nullptr, handleYAMLDiag, this), 178 Filename(Filename), Context(Context), ProcessIRFunction(Callback) { 179 In.setContext(&In); 180 } 181 182 bool MIRParserImpl::error(const Twine &Message) { 183 Context.diagnose(DiagnosticInfoMIRParser( 184 DS_Error, SMDiagnostic(Filename, SourceMgr::DK_Error, Message.str()))); 185 return true; 186 } 187 188 bool MIRParserImpl::error(SMLoc Loc, const Twine &Message) { 189 Context.diagnose(DiagnosticInfoMIRParser( 190 DS_Error, SM.GetMessage(Loc, SourceMgr::DK_Error, Message))); 191 return true; 192 } 193 194 bool MIRParserImpl::error(const SMDiagnostic &Error, SMRange SourceRange) { 195 assert(Error.getKind() == SourceMgr::DK_Error && "Expected an error"); 196 reportDiagnostic(diagFromMIStringDiag(Error, SourceRange)); 197 return true; 198 } 199 200 void MIRParserImpl::reportDiagnostic(const SMDiagnostic &Diag) { 201 DiagnosticSeverity Kind; 202 switch (Diag.getKind()) { 203 case SourceMgr::DK_Error: 204 Kind = DS_Error; 205 break; 206 case SourceMgr::DK_Warning: 207 Kind = DS_Warning; 208 break; 209 case SourceMgr::DK_Note: 210 Kind = DS_Note; 211 break; 212 case SourceMgr::DK_Remark: 213 llvm_unreachable("remark unexpected"); 214 break; 215 } 216 Context.diagnose(DiagnosticInfoMIRParser(Kind, Diag)); 217 } 218 219 std::unique_ptr<Module> MIRParserImpl::parseIRModule() { 220 if (!In.setCurrentDocument()) { 221 if (In.error()) 222 return nullptr; 223 // Create an empty module when the MIR file is empty. 224 NoMIRDocuments = true; 225 return std::make_unique<Module>(Filename, Context); 226 } 227 228 std::unique_ptr<Module> M; 229 // Parse the block scalar manually so that we can return unique pointer 230 // without having to go trough YAML traits. 231 if (const auto *BSN = 232 dyn_cast_or_null<yaml::BlockScalarNode>(In.getCurrentNode())) { 233 SMDiagnostic Error; 234 M = parseAssembly(MemoryBufferRef(BSN->getValue(), Filename), Error, 235 Context, &IRSlots, /*UpgradeDebugInfo=*/false); 236 if (!M) { 237 reportDiagnostic(diagFromBlockStringDiag(Error, BSN->getSourceRange())); 238 return nullptr; 239 } 240 In.nextDocument(); 241 if (!In.setCurrentDocument()) 242 NoMIRDocuments = true; 243 } else { 244 // Create an new, empty module. 245 M = std::make_unique<Module>(Filename, Context); 246 NoLLVMIR = true; 247 } 248 return M; 249 } 250 251 bool MIRParserImpl::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) { 252 if (NoMIRDocuments) 253 return false; 254 255 // Parse the machine functions. 256 do { 257 if (parseMachineFunction(M, MMI)) 258 return true; 259 In.nextDocument(); 260 } while (In.setCurrentDocument()); 261 262 return false; 263 } 264 265 Function *MIRParserImpl::createDummyFunction(StringRef Name, Module &M) { 266 auto &Context = M.getContext(); 267 Function *F = 268 Function::Create(FunctionType::get(Type::getVoidTy(Context), false), 269 Function::ExternalLinkage, Name, M); 270 BasicBlock *BB = BasicBlock::Create(Context, "entry", F); 271 new UnreachableInst(Context, BB); 272 273 if (ProcessIRFunction) 274 ProcessIRFunction(*F); 275 276 return F; 277 } 278 279 bool MIRParserImpl::parseMachineFunction(Module &M, MachineModuleInfo &MMI) { 280 // Parse the yaml. 281 yaml::MachineFunction YamlMF; 282 yaml::EmptyContext Ctx; 283 284 const LLVMTargetMachine &TM = MMI.getTarget(); 285 YamlMF.MachineFuncInfo = std::unique_ptr<yaml::MachineFunctionInfo>( 286 TM.createDefaultFuncInfoYAML()); 287 288 yaml::yamlize(In, YamlMF, false, Ctx); 289 if (In.error()) 290 return true; 291 292 // Search for the corresponding IR function. 293 StringRef FunctionName = YamlMF.Name; 294 Function *F = M.getFunction(FunctionName); 295 if (!F) { 296 if (NoLLVMIR) { 297 F = createDummyFunction(FunctionName, M); 298 } else { 299 return error(Twine("function '") + FunctionName + 300 "' isn't defined in the provided LLVM IR"); 301 } 302 } 303 if (MMI.getMachineFunction(*F) != nullptr) 304 return error(Twine("redefinition of machine function '") + FunctionName + 305 "'"); 306 307 // Create the MachineFunction. 308 MachineFunction &MF = MMI.getOrCreateMachineFunction(*F); 309 if (initializeMachineFunction(YamlMF, MF)) 310 return true; 311 312 return false; 313 } 314 315 static bool isSSA(const MachineFunction &MF) { 316 const MachineRegisterInfo &MRI = MF.getRegInfo(); 317 for (unsigned I = 0, E = MRI.getNumVirtRegs(); I != E; ++I) { 318 unsigned Reg = Register::index2VirtReg(I); 319 if (!MRI.hasOneDef(Reg) && !MRI.def_empty(Reg)) 320 return false; 321 } 322 return true; 323 } 324 325 void MIRParserImpl::computeFunctionProperties(MachineFunction &MF) { 326 MachineFunctionProperties &Properties = MF.getProperties(); 327 328 bool HasPHI = false; 329 bool HasInlineAsm = false; 330 for (const MachineBasicBlock &MBB : MF) { 331 for (const MachineInstr &MI : MBB) { 332 if (MI.isPHI()) 333 HasPHI = true; 334 if (MI.isInlineAsm()) 335 HasInlineAsm = true; 336 } 337 } 338 if (!HasPHI) 339 Properties.set(MachineFunctionProperties::Property::NoPHIs); 340 MF.setHasInlineAsm(HasInlineAsm); 341 342 if (isSSA(MF)) 343 Properties.set(MachineFunctionProperties::Property::IsSSA); 344 else 345 Properties.reset(MachineFunctionProperties::Property::IsSSA); 346 347 const MachineRegisterInfo &MRI = MF.getRegInfo(); 348 if (MRI.getNumVirtRegs() == 0) 349 Properties.set(MachineFunctionProperties::Property::NoVRegs); 350 } 351 352 bool MIRParserImpl::initializeCallSiteInfo( 353 PerFunctionMIParsingState &PFS, const yaml::MachineFunction &YamlMF) { 354 MachineFunction &MF = PFS.MF; 355 SMDiagnostic Error; 356 const LLVMTargetMachine &TM = MF.getTarget(); 357 for (auto YamlCSInfo : YamlMF.CallSitesInfo) { 358 yaml::CallSiteInfo::MachineInstrLoc MILoc = YamlCSInfo.CallLocation; 359 if (MILoc.BlockNum >= MF.size()) 360 return error(Twine(MF.getName()) + 361 Twine(" call instruction block out of range.") + 362 " Unable to reference bb:" + Twine(MILoc.BlockNum)); 363 auto CallB = std::next(MF.begin(), MILoc.BlockNum); 364 if (MILoc.Offset >= CallB->size()) 365 return error(Twine(MF.getName()) + 366 Twine(" call instruction offset out of range.") + 367 " Unable to reference instruction at bb: " + 368 Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset)); 369 auto CallI = std::next(CallB->instr_begin(), MILoc.Offset); 370 if (!CallI->isCall(MachineInstr::IgnoreBundle)) 371 return error(Twine(MF.getName()) + 372 Twine(" call site info should reference call " 373 "instruction. Instruction at bb:") + 374 Twine(MILoc.BlockNum) + " at offset:" + Twine(MILoc.Offset) + 375 " is not a call instruction"); 376 MachineFunction::CallSiteInfo CSInfo; 377 for (auto ArgRegPair : YamlCSInfo.ArgForwardingRegs) { 378 unsigned Reg = 0; 379 if (parseNamedRegisterReference(PFS, Reg, ArgRegPair.Reg.Value, Error)) 380 return error(Error, ArgRegPair.Reg.SourceRange); 381 CSInfo.emplace_back(Reg, ArgRegPair.ArgNo); 382 } 383 384 if (TM.Options.EmitCallSiteInfo) 385 MF.addCallArgsForwardingRegs(&*CallI, std::move(CSInfo)); 386 } 387 388 if (YamlMF.CallSitesInfo.size() && !TM.Options.EmitCallSiteInfo) 389 return error(Twine("Call site info provided but not used")); 390 return false; 391 } 392 393 bool 394 MIRParserImpl::initializeMachineFunction(const yaml::MachineFunction &YamlMF, 395 MachineFunction &MF) { 396 // TODO: Recreate the machine function. 397 if (Target) { 398 // Avoid clearing state if we're using the same subtarget again. 399 Target->setTarget(MF.getSubtarget()); 400 } else { 401 Target.reset(new PerTargetMIParsingState(MF.getSubtarget())); 402 } 403 404 if (YamlMF.Alignment) 405 MF.setAlignment(Align(YamlMF.Alignment)); 406 MF.setExposesReturnsTwice(YamlMF.ExposesReturnsTwice); 407 MF.setHasWinCFI(YamlMF.HasWinCFI); 408 409 if (YamlMF.Legalized) 410 MF.getProperties().set(MachineFunctionProperties::Property::Legalized); 411 if (YamlMF.RegBankSelected) 412 MF.getProperties().set( 413 MachineFunctionProperties::Property::RegBankSelected); 414 if (YamlMF.Selected) 415 MF.getProperties().set(MachineFunctionProperties::Property::Selected); 416 if (YamlMF.FailedISel) 417 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel); 418 419 PerFunctionMIParsingState PFS(MF, SM, IRSlots, *Target); 420 if (parseRegisterInfo(PFS, YamlMF)) 421 return true; 422 if (!YamlMF.Constants.empty()) { 423 auto *ConstantPool = MF.getConstantPool(); 424 assert(ConstantPool && "Constant pool must be created"); 425 if (initializeConstantPool(PFS, *ConstantPool, YamlMF)) 426 return true; 427 } 428 429 StringRef BlockStr = YamlMF.Body.Value.Value; 430 SMDiagnostic Error; 431 SourceMgr BlockSM; 432 BlockSM.AddNewSourceBuffer( 433 MemoryBuffer::getMemBuffer(BlockStr, "",/*RequiresNullTerminator=*/false), 434 SMLoc()); 435 PFS.SM = &BlockSM; 436 if (parseMachineBasicBlockDefinitions(PFS, BlockStr, Error)) { 437 reportDiagnostic( 438 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange)); 439 return true; 440 } 441 // Check Basic Block Section Flags. 442 if (MF.getTarget().getBBSectionsType() == BasicBlockSection::Labels) { 443 MF.createBBLabels(); 444 MF.setBBSectionsType(BasicBlockSection::Labels); 445 } else if (MF.hasBBSections()) { 446 MF.setSectionRange(); 447 MF.createBBLabels(); 448 } 449 PFS.SM = &SM; 450 451 // Initialize the frame information after creating all the MBBs so that the 452 // MBB references in the frame information can be resolved. 453 if (initializeFrameInfo(PFS, YamlMF)) 454 return true; 455 // Initialize the jump table after creating all the MBBs so that the MBB 456 // references can be resolved. 457 if (!YamlMF.JumpTableInfo.Entries.empty() && 458 initializeJumpTableInfo(PFS, YamlMF.JumpTableInfo)) 459 return true; 460 // Parse the machine instructions after creating all of the MBBs so that the 461 // parser can resolve the MBB references. 462 StringRef InsnStr = YamlMF.Body.Value.Value; 463 SourceMgr InsnSM; 464 InsnSM.AddNewSourceBuffer( 465 MemoryBuffer::getMemBuffer(InsnStr, "", /*RequiresNullTerminator=*/false), 466 SMLoc()); 467 PFS.SM = &InsnSM; 468 if (parseMachineInstructions(PFS, InsnStr, Error)) { 469 reportDiagnostic( 470 diagFromBlockStringDiag(Error, YamlMF.Body.Value.SourceRange)); 471 return true; 472 } 473 PFS.SM = &SM; 474 475 if (setupRegisterInfo(PFS, YamlMF)) 476 return true; 477 478 if (YamlMF.MachineFuncInfo) { 479 const LLVMTargetMachine &TM = MF.getTarget(); 480 // Note this is called after the initial constructor of the 481 // MachineFunctionInfo based on the MachineFunction, which may depend on the 482 // IR. 483 484 SMRange SrcRange; 485 if (TM.parseMachineFunctionInfo(*YamlMF.MachineFuncInfo, PFS, Error, 486 SrcRange)) { 487 return error(Error, SrcRange); 488 } 489 } 490 491 // Set the reserved registers after parsing MachineFuncInfo. The target may 492 // have been recording information used to select the reserved registers 493 // there. 494 // FIXME: This is a temporary workaround until the reserved registers can be 495 // serialized. 496 MachineRegisterInfo &MRI = MF.getRegInfo(); 497 MRI.freezeReservedRegs(MF); 498 499 computeFunctionProperties(MF); 500 501 if (initializeCallSiteInfo(PFS, YamlMF)) 502 return false; 503 504 MF.getSubtarget().mirFileLoaded(MF); 505 506 MF.verify(); 507 return false; 508 } 509 510 bool MIRParserImpl::parseRegisterInfo(PerFunctionMIParsingState &PFS, 511 const yaml::MachineFunction &YamlMF) { 512 MachineFunction &MF = PFS.MF; 513 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 514 assert(RegInfo.tracksLiveness()); 515 if (!YamlMF.TracksRegLiveness) 516 RegInfo.invalidateLiveness(); 517 518 SMDiagnostic Error; 519 // Parse the virtual register information. 520 for (const auto &VReg : YamlMF.VirtualRegisters) { 521 VRegInfo &Info = PFS.getVRegInfo(VReg.ID.Value); 522 if (Info.Explicit) 523 return error(VReg.ID.SourceRange.Start, 524 Twine("redefinition of virtual register '%") + 525 Twine(VReg.ID.Value) + "'"); 526 Info.Explicit = true; 527 528 if (StringRef(VReg.Class.Value).equals("_")) { 529 Info.Kind = VRegInfo::GENERIC; 530 Info.D.RegBank = nullptr; 531 } else { 532 const auto *RC = Target->getRegClass(VReg.Class.Value); 533 if (RC) { 534 Info.Kind = VRegInfo::NORMAL; 535 Info.D.RC = RC; 536 } else { 537 const RegisterBank *RegBank = Target->getRegBank(VReg.Class.Value); 538 if (!RegBank) 539 return error( 540 VReg.Class.SourceRange.Start, 541 Twine("use of undefined register class or register bank '") + 542 VReg.Class.Value + "'"); 543 Info.Kind = VRegInfo::REGBANK; 544 Info.D.RegBank = RegBank; 545 } 546 } 547 548 if (!VReg.PreferredRegister.Value.empty()) { 549 if (Info.Kind != VRegInfo::NORMAL) 550 return error(VReg.Class.SourceRange.Start, 551 Twine("preferred register can only be set for normal vregs")); 552 553 if (parseRegisterReference(PFS, Info.PreferredReg, 554 VReg.PreferredRegister.Value, Error)) 555 return error(Error, VReg.PreferredRegister.SourceRange); 556 } 557 } 558 559 // Parse the liveins. 560 for (const auto &LiveIn : YamlMF.LiveIns) { 561 unsigned Reg = 0; 562 if (parseNamedRegisterReference(PFS, Reg, LiveIn.Register.Value, Error)) 563 return error(Error, LiveIn.Register.SourceRange); 564 unsigned VReg = 0; 565 if (!LiveIn.VirtualRegister.Value.empty()) { 566 VRegInfo *Info; 567 if (parseVirtualRegisterReference(PFS, Info, LiveIn.VirtualRegister.Value, 568 Error)) 569 return error(Error, LiveIn.VirtualRegister.SourceRange); 570 VReg = Info->VReg; 571 } 572 RegInfo.addLiveIn(Reg, VReg); 573 } 574 575 // Parse the callee saved registers (Registers that will 576 // be saved for the caller). 577 if (YamlMF.CalleeSavedRegisters) { 578 SmallVector<MCPhysReg, 16> CalleeSavedRegisters; 579 for (const auto &RegSource : YamlMF.CalleeSavedRegisters.getValue()) { 580 unsigned Reg = 0; 581 if (parseNamedRegisterReference(PFS, Reg, RegSource.Value, Error)) 582 return error(Error, RegSource.SourceRange); 583 CalleeSavedRegisters.push_back(Reg); 584 } 585 RegInfo.setCalleeSavedRegs(CalleeSavedRegisters); 586 } 587 588 return false; 589 } 590 591 bool MIRParserImpl::setupRegisterInfo(const PerFunctionMIParsingState &PFS, 592 const yaml::MachineFunction &YamlMF) { 593 MachineFunction &MF = PFS.MF; 594 MachineRegisterInfo &MRI = MF.getRegInfo(); 595 bool Error = false; 596 // Create VRegs 597 auto populateVRegInfo = [&] (const VRegInfo &Info, Twine Name) { 598 unsigned Reg = Info.VReg; 599 switch (Info.Kind) { 600 case VRegInfo::UNKNOWN: 601 error(Twine("Cannot determine class/bank of virtual register ") + 602 Name + " in function '" + MF.getName() + "'"); 603 Error = true; 604 break; 605 case VRegInfo::NORMAL: 606 MRI.setRegClass(Reg, Info.D.RC); 607 if (Info.PreferredReg != 0) 608 MRI.setSimpleHint(Reg, Info.PreferredReg); 609 break; 610 case VRegInfo::GENERIC: 611 break; 612 case VRegInfo::REGBANK: 613 MRI.setRegBank(Reg, *Info.D.RegBank); 614 break; 615 } 616 }; 617 618 for (auto I = PFS.VRegInfosNamed.begin(), E = PFS.VRegInfosNamed.end(); 619 I != E; I++) { 620 const VRegInfo &Info = *I->second; 621 populateVRegInfo(Info, Twine(I->first())); 622 } 623 624 for (auto P : PFS.VRegInfos) { 625 const VRegInfo &Info = *P.second; 626 populateVRegInfo(Info, Twine(P.first)); 627 } 628 629 // Compute MachineRegisterInfo::UsedPhysRegMask 630 for (const MachineBasicBlock &MBB : MF) { 631 for (const MachineInstr &MI : MBB) { 632 for (const MachineOperand &MO : MI.operands()) { 633 if (!MO.isRegMask()) 634 continue; 635 MRI.addPhysRegsUsedFromRegMask(MO.getRegMask()); 636 } 637 } 638 } 639 640 return Error; 641 } 642 643 bool MIRParserImpl::initializeFrameInfo(PerFunctionMIParsingState &PFS, 644 const yaml::MachineFunction &YamlMF) { 645 MachineFunction &MF = PFS.MF; 646 MachineFrameInfo &MFI = MF.getFrameInfo(); 647 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); 648 const Function &F = MF.getFunction(); 649 const yaml::MachineFrameInfo &YamlMFI = YamlMF.FrameInfo; 650 MFI.setFrameAddressIsTaken(YamlMFI.IsFrameAddressTaken); 651 MFI.setReturnAddressIsTaken(YamlMFI.IsReturnAddressTaken); 652 MFI.setHasStackMap(YamlMFI.HasStackMap); 653 MFI.setHasPatchPoint(YamlMFI.HasPatchPoint); 654 MFI.setStackSize(YamlMFI.StackSize); 655 MFI.setOffsetAdjustment(YamlMFI.OffsetAdjustment); 656 if (YamlMFI.MaxAlignment) 657 MFI.ensureMaxAlignment(Align(YamlMFI.MaxAlignment)); 658 MFI.setAdjustsStack(YamlMFI.AdjustsStack); 659 MFI.setHasCalls(YamlMFI.HasCalls); 660 if (YamlMFI.MaxCallFrameSize != ~0u) 661 MFI.setMaxCallFrameSize(YamlMFI.MaxCallFrameSize); 662 MFI.setCVBytesOfCalleeSavedRegisters(YamlMFI.CVBytesOfCalleeSavedRegisters); 663 MFI.setHasOpaqueSPAdjustment(YamlMFI.HasOpaqueSPAdjustment); 664 MFI.setHasVAStart(YamlMFI.HasVAStart); 665 MFI.setHasMustTailInVarArgFunc(YamlMFI.HasMustTailInVarArgFunc); 666 MFI.setLocalFrameSize(YamlMFI.LocalFrameSize); 667 if (!YamlMFI.SavePoint.Value.empty()) { 668 MachineBasicBlock *MBB = nullptr; 669 if (parseMBBReference(PFS, MBB, YamlMFI.SavePoint)) 670 return true; 671 MFI.setSavePoint(MBB); 672 } 673 if (!YamlMFI.RestorePoint.Value.empty()) { 674 MachineBasicBlock *MBB = nullptr; 675 if (parseMBBReference(PFS, MBB, YamlMFI.RestorePoint)) 676 return true; 677 MFI.setRestorePoint(MBB); 678 } 679 680 std::vector<CalleeSavedInfo> CSIInfo; 681 // Initialize the fixed frame objects. 682 for (const auto &Object : YamlMF.FixedStackObjects) { 683 int ObjectIdx; 684 if (Object.Type != yaml::FixedMachineStackObject::SpillSlot) 685 ObjectIdx = MFI.CreateFixedObject(Object.Size, Object.Offset, 686 Object.IsImmutable, Object.IsAliased); 687 else 688 ObjectIdx = MFI.CreateFixedSpillStackObject(Object.Size, Object.Offset); 689 690 if (!TFI->isSupportedStackID(Object.StackID)) 691 return error(Object.ID.SourceRange.Start, 692 Twine("StackID is not supported by target")); 693 MFI.setStackID(ObjectIdx, Object.StackID); 694 MFI.setObjectAlignment(ObjectIdx, Object.Alignment); 695 if (!PFS.FixedStackObjectSlots.insert(std::make_pair(Object.ID.Value, 696 ObjectIdx)) 697 .second) 698 return error(Object.ID.SourceRange.Start, 699 Twine("redefinition of fixed stack object '%fixed-stack.") + 700 Twine(Object.ID.Value) + "'"); 701 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister, 702 Object.CalleeSavedRestored, ObjectIdx)) 703 return true; 704 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx)) 705 return true; 706 } 707 708 // Initialize the ordinary frame objects. 709 for (const auto &Object : YamlMF.StackObjects) { 710 int ObjectIdx; 711 const AllocaInst *Alloca = nullptr; 712 const yaml::StringValue &Name = Object.Name; 713 if (!Name.Value.empty()) { 714 Alloca = dyn_cast_or_null<AllocaInst>( 715 F.getValueSymbolTable()->lookup(Name.Value)); 716 if (!Alloca) 717 return error(Name.SourceRange.Start, 718 "alloca instruction named '" + Name.Value + 719 "' isn't defined in the function '" + F.getName() + 720 "'"); 721 } 722 if (!TFI->isSupportedStackID(Object.StackID)) 723 return error(Object.ID.SourceRange.Start, 724 Twine("StackID is not supported by target")); 725 if (Object.Type == yaml::MachineStackObject::VariableSized) 726 ObjectIdx = MFI.CreateVariableSizedObject(Object.Alignment, Alloca); 727 else 728 ObjectIdx = MFI.CreateStackObject( 729 Object.Size, Object.Alignment, 730 Object.Type == yaml::MachineStackObject::SpillSlot, Alloca, 731 Object.StackID); 732 MFI.setObjectOffset(ObjectIdx, Object.Offset); 733 734 if (!PFS.StackObjectSlots.insert(std::make_pair(Object.ID.Value, ObjectIdx)) 735 .second) 736 return error(Object.ID.SourceRange.Start, 737 Twine("redefinition of stack object '%stack.") + 738 Twine(Object.ID.Value) + "'"); 739 if (parseCalleeSavedRegister(PFS, CSIInfo, Object.CalleeSavedRegister, 740 Object.CalleeSavedRestored, ObjectIdx)) 741 return true; 742 if (Object.LocalOffset) 743 MFI.mapLocalFrameObject(ObjectIdx, Object.LocalOffset.getValue()); 744 if (parseStackObjectsDebugInfo(PFS, Object, ObjectIdx)) 745 return true; 746 } 747 MFI.setCalleeSavedInfo(CSIInfo); 748 if (!CSIInfo.empty()) 749 MFI.setCalleeSavedInfoValid(true); 750 751 // Initialize the various stack object references after initializing the 752 // stack objects. 753 if (!YamlMFI.StackProtector.Value.empty()) { 754 SMDiagnostic Error; 755 int FI; 756 if (parseStackObjectReference(PFS, FI, YamlMFI.StackProtector.Value, Error)) 757 return error(Error, YamlMFI.StackProtector.SourceRange); 758 MFI.setStackProtectorIndex(FI); 759 } 760 return false; 761 } 762 763 bool MIRParserImpl::parseCalleeSavedRegister(PerFunctionMIParsingState &PFS, 764 std::vector<CalleeSavedInfo> &CSIInfo, 765 const yaml::StringValue &RegisterSource, bool IsRestored, int FrameIdx) { 766 if (RegisterSource.Value.empty()) 767 return false; 768 unsigned Reg = 0; 769 SMDiagnostic Error; 770 if (parseNamedRegisterReference(PFS, Reg, RegisterSource.Value, Error)) 771 return error(Error, RegisterSource.SourceRange); 772 CalleeSavedInfo CSI(Reg, FrameIdx); 773 CSI.setRestored(IsRestored); 774 CSIInfo.push_back(CSI); 775 return false; 776 } 777 778 /// Verify that given node is of a certain type. Return true on error. 779 template <typename T> 780 static bool typecheckMDNode(T *&Result, MDNode *Node, 781 const yaml::StringValue &Source, 782 StringRef TypeString, MIRParserImpl &Parser) { 783 if (!Node) 784 return false; 785 Result = dyn_cast<T>(Node); 786 if (!Result) 787 return Parser.error(Source.SourceRange.Start, 788 "expected a reference to a '" + TypeString + 789 "' metadata node"); 790 return false; 791 } 792 793 template <typename T> 794 bool MIRParserImpl::parseStackObjectsDebugInfo(PerFunctionMIParsingState &PFS, 795 const T &Object, int FrameIdx) { 796 // Debug information can only be attached to stack objects; Fixed stack 797 // objects aren't supported. 798 MDNode *Var = nullptr, *Expr = nullptr, *Loc = nullptr; 799 if (parseMDNode(PFS, Var, Object.DebugVar) || 800 parseMDNode(PFS, Expr, Object.DebugExpr) || 801 parseMDNode(PFS, Loc, Object.DebugLoc)) 802 return true; 803 if (!Var && !Expr && !Loc) 804 return false; 805 DILocalVariable *DIVar = nullptr; 806 DIExpression *DIExpr = nullptr; 807 DILocation *DILoc = nullptr; 808 if (typecheckMDNode(DIVar, Var, Object.DebugVar, "DILocalVariable", *this) || 809 typecheckMDNode(DIExpr, Expr, Object.DebugExpr, "DIExpression", *this) || 810 typecheckMDNode(DILoc, Loc, Object.DebugLoc, "DILocation", *this)) 811 return true; 812 PFS.MF.setVariableDbgInfo(DIVar, DIExpr, FrameIdx, DILoc); 813 return false; 814 } 815 816 bool MIRParserImpl::parseMDNode(PerFunctionMIParsingState &PFS, 817 MDNode *&Node, const yaml::StringValue &Source) { 818 if (Source.Value.empty()) 819 return false; 820 SMDiagnostic Error; 821 if (llvm::parseMDNode(PFS, Node, Source.Value, Error)) 822 return error(Error, Source.SourceRange); 823 return false; 824 } 825 826 bool MIRParserImpl::initializeConstantPool(PerFunctionMIParsingState &PFS, 827 MachineConstantPool &ConstantPool, const yaml::MachineFunction &YamlMF) { 828 DenseMap<unsigned, unsigned> &ConstantPoolSlots = PFS.ConstantPoolSlots; 829 const MachineFunction &MF = PFS.MF; 830 const auto &M = *MF.getFunction().getParent(); 831 SMDiagnostic Error; 832 for (const auto &YamlConstant : YamlMF.Constants) { 833 if (YamlConstant.IsTargetSpecific) 834 // FIXME: Support target-specific constant pools 835 return error(YamlConstant.Value.SourceRange.Start, 836 "Can't parse target-specific constant pool entries yet"); 837 const Constant *Value = dyn_cast_or_null<Constant>( 838 parseConstantValue(YamlConstant.Value.Value, Error, M)); 839 if (!Value) 840 return error(Error, YamlConstant.Value.SourceRange); 841 unsigned Alignment = 842 YamlConstant.Alignment 843 ? YamlConstant.Alignment 844 : M.getDataLayout().getPrefTypeAlignment(Value->getType()); 845 unsigned Index = ConstantPool.getConstantPoolIndex(Value, Alignment); 846 if (!ConstantPoolSlots.insert(std::make_pair(YamlConstant.ID.Value, Index)) 847 .second) 848 return error(YamlConstant.ID.SourceRange.Start, 849 Twine("redefinition of constant pool item '%const.") + 850 Twine(YamlConstant.ID.Value) + "'"); 851 } 852 return false; 853 } 854 855 bool MIRParserImpl::initializeJumpTableInfo(PerFunctionMIParsingState &PFS, 856 const yaml::MachineJumpTable &YamlJTI) { 857 MachineJumpTableInfo *JTI = PFS.MF.getOrCreateJumpTableInfo(YamlJTI.Kind); 858 for (const auto &Entry : YamlJTI.Entries) { 859 std::vector<MachineBasicBlock *> Blocks; 860 for (const auto &MBBSource : Entry.Blocks) { 861 MachineBasicBlock *MBB = nullptr; 862 if (parseMBBReference(PFS, MBB, MBBSource.Value)) 863 return true; 864 Blocks.push_back(MBB); 865 } 866 unsigned Index = JTI->createJumpTableIndex(Blocks); 867 if (!PFS.JumpTableSlots.insert(std::make_pair(Entry.ID.Value, Index)) 868 .second) 869 return error(Entry.ID.SourceRange.Start, 870 Twine("redefinition of jump table entry '%jump-table.") + 871 Twine(Entry.ID.Value) + "'"); 872 } 873 return false; 874 } 875 876 bool MIRParserImpl::parseMBBReference(PerFunctionMIParsingState &PFS, 877 MachineBasicBlock *&MBB, 878 const yaml::StringValue &Source) { 879 SMDiagnostic Error; 880 if (llvm::parseMBBReference(PFS, MBB, Source.Value, Error)) 881 return error(Error, Source.SourceRange); 882 return false; 883 } 884 885 SMDiagnostic MIRParserImpl::diagFromMIStringDiag(const SMDiagnostic &Error, 886 SMRange SourceRange) { 887 assert(SourceRange.isValid() && "Invalid source range"); 888 SMLoc Loc = SourceRange.Start; 889 bool HasQuote = Loc.getPointer() < SourceRange.End.getPointer() && 890 *Loc.getPointer() == '\''; 891 // Translate the location of the error from the location in the MI string to 892 // the corresponding location in the MIR file. 893 Loc = Loc.getFromPointer(Loc.getPointer() + Error.getColumnNo() + 894 (HasQuote ? 1 : 0)); 895 896 // TODO: Translate any source ranges as well. 897 return SM.GetMessage(Loc, Error.getKind(), Error.getMessage(), None, 898 Error.getFixIts()); 899 } 900 901 SMDiagnostic MIRParserImpl::diagFromBlockStringDiag(const SMDiagnostic &Error, 902 SMRange SourceRange) { 903 assert(SourceRange.isValid()); 904 905 // Translate the location of the error from the location in the llvm IR string 906 // to the corresponding location in the MIR file. 907 auto LineAndColumn = SM.getLineAndColumn(SourceRange.Start); 908 unsigned Line = LineAndColumn.first + Error.getLineNo() - 1; 909 unsigned Column = Error.getColumnNo(); 910 StringRef LineStr = Error.getLineContents(); 911 SMLoc Loc = Error.getLoc(); 912 913 // Get the full line and adjust the column number by taking the indentation of 914 // LLVM IR into account. 915 for (line_iterator L(*SM.getMemoryBuffer(SM.getMainFileID()), false), E; 916 L != E; ++L) { 917 if (L.line_number() == Line) { 918 LineStr = *L; 919 Loc = SMLoc::getFromPointer(LineStr.data()); 920 auto Indent = LineStr.find(Error.getLineContents()); 921 if (Indent != StringRef::npos) 922 Column += Indent; 923 break; 924 } 925 } 926 927 return SMDiagnostic(SM, Loc, Filename, Line, Column, Error.getKind(), 928 Error.getMessage(), LineStr, Error.getRanges(), 929 Error.getFixIts()); 930 } 931 932 MIRParser::MIRParser(std::unique_ptr<MIRParserImpl> Impl) 933 : Impl(std::move(Impl)) {} 934 935 MIRParser::~MIRParser() {} 936 937 std::unique_ptr<Module> MIRParser::parseIRModule() { 938 return Impl->parseIRModule(); 939 } 940 941 bool MIRParser::parseMachineFunctions(Module &M, MachineModuleInfo &MMI) { 942 return Impl->parseMachineFunctions(M, MMI); 943 } 944 945 std::unique_ptr<MIRParser> llvm::createMIRParserFromFile( 946 StringRef Filename, SMDiagnostic &Error, LLVMContext &Context, 947 std::function<void(Function &)> ProcessIRFunction) { 948 auto FileOrErr = MemoryBuffer::getFileOrSTDIN(Filename); 949 if (std::error_code EC = FileOrErr.getError()) { 950 Error = SMDiagnostic(Filename, SourceMgr::DK_Error, 951 "Could not open input file: " + EC.message()); 952 return nullptr; 953 } 954 return createMIRParser(std::move(FileOrErr.get()), Context, 955 ProcessIRFunction); 956 } 957 958 std::unique_ptr<MIRParser> 959 llvm::createMIRParser(std::unique_ptr<MemoryBuffer> Contents, 960 LLVMContext &Context, 961 std::function<void(Function &)> ProcessIRFunction) { 962 auto Filename = Contents->getBufferIdentifier(); 963 if (Context.shouldDiscardValueNames()) { 964 Context.diagnose(DiagnosticInfoMIRParser( 965 DS_Error, 966 SMDiagnostic( 967 Filename, SourceMgr::DK_Error, 968 "Can't read MIR with a Context that discards named Values"))); 969 return nullptr; 970 } 971 return std::make_unique<MIRParser>(std::make_unique<MIRParserImpl>( 972 std::move(Contents), Filename, Context, ProcessIRFunction)); 973 } 974