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