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