1 //===- MachineFunction.cpp ------------------------------------------------===// 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 // Collect native machine code information for a function. This allows 10 // target-specific information about the generated code to be stored with each 11 // function. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/CodeGen/MachineFunction.h" 16 #include "llvm/ADT/BitVector.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/DenseSet.h" 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SmallString.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/ADT/StringRef.h" 23 #include "llvm/ADT/Twine.h" 24 #include "llvm/Analysis/ConstantFolding.h" 25 #include "llvm/Analysis/EHPersonalities.h" 26 #include "llvm/CodeGen/MachineBasicBlock.h" 27 #include "llvm/CodeGen/MachineConstantPool.h" 28 #include "llvm/CodeGen/MachineFrameInfo.h" 29 #include "llvm/CodeGen/MachineInstr.h" 30 #include "llvm/CodeGen/MachineJumpTableInfo.h" 31 #include "llvm/CodeGen/MachineMemOperand.h" 32 #include "llvm/CodeGen/MachineModuleInfo.h" 33 #include "llvm/CodeGen/MachineRegisterInfo.h" 34 #include "llvm/CodeGen/PseudoSourceValue.h" 35 #include "llvm/CodeGen/TargetFrameLowering.h" 36 #include "llvm/CodeGen/TargetLowering.h" 37 #include "llvm/CodeGen/TargetRegisterInfo.h" 38 #include "llvm/CodeGen/TargetSubtargetInfo.h" 39 #include "llvm/CodeGen/WasmEHFuncInfo.h" 40 #include "llvm/CodeGen/WinEHFuncInfo.h" 41 #include "llvm/Config/llvm-config.h" 42 #include "llvm/IR/Attributes.h" 43 #include "llvm/IR/BasicBlock.h" 44 #include "llvm/IR/Constant.h" 45 #include "llvm/IR/DataLayout.h" 46 #include "llvm/IR/DerivedTypes.h" 47 #include "llvm/IR/Function.h" 48 #include "llvm/IR/GlobalValue.h" 49 #include "llvm/IR/Instruction.h" 50 #include "llvm/IR/Instructions.h" 51 #include "llvm/IR/Metadata.h" 52 #include "llvm/IR/Module.h" 53 #include "llvm/IR/ModuleSlotTracker.h" 54 #include "llvm/IR/Value.h" 55 #include "llvm/MC/MCContext.h" 56 #include "llvm/MC/MCSymbol.h" 57 #include "llvm/MC/SectionKind.h" 58 #include "llvm/Support/Casting.h" 59 #include "llvm/Support/CommandLine.h" 60 #include "llvm/Support/Compiler.h" 61 #include "llvm/Support/DOTGraphTraits.h" 62 #include "llvm/Support/Debug.h" 63 #include "llvm/Support/ErrorHandling.h" 64 #include "llvm/Support/GraphWriter.h" 65 #include "llvm/Support/raw_ostream.h" 66 #include "llvm/Target/TargetMachine.h" 67 #include <algorithm> 68 #include <cassert> 69 #include <cstddef> 70 #include <cstdint> 71 #include <iterator> 72 #include <string> 73 #include <utility> 74 #include <vector> 75 76 using namespace llvm; 77 78 #define DEBUG_TYPE "codegen" 79 80 static cl::opt<unsigned> 81 AlignAllFunctions("align-all-functions", 82 cl::desc("Force the alignment of all functions."), 83 cl::init(0), cl::Hidden); 84 85 static const char *getPropertyName(MachineFunctionProperties::Property Prop) { 86 using P = MachineFunctionProperties::Property; 87 88 switch(Prop) { 89 case P::FailedISel: return "FailedISel"; 90 case P::IsSSA: return "IsSSA"; 91 case P::Legalized: return "Legalized"; 92 case P::NoPHIs: return "NoPHIs"; 93 case P::NoVRegs: return "NoVRegs"; 94 case P::RegBankSelected: return "RegBankSelected"; 95 case P::Selected: return "Selected"; 96 case P::TracksLiveness: return "TracksLiveness"; 97 } 98 llvm_unreachable("Invalid machine function property"); 99 } 100 101 // Pin the vtable to this file. 102 void MachineFunction::Delegate::anchor() {} 103 104 void MachineFunctionProperties::print(raw_ostream &OS) const { 105 const char *Separator = ""; 106 for (BitVector::size_type I = 0; I < Properties.size(); ++I) { 107 if (!Properties[I]) 108 continue; 109 OS << Separator << getPropertyName(static_cast<Property>(I)); 110 Separator = ", "; 111 } 112 } 113 114 //===----------------------------------------------------------------------===// 115 // MachineFunction implementation 116 //===----------------------------------------------------------------------===// 117 118 // Out-of-line virtual method. 119 MachineFunctionInfo::~MachineFunctionInfo() = default; 120 121 void ilist_alloc_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) { 122 MBB->getParent()->DeleteMachineBasicBlock(MBB); 123 } 124 125 static inline unsigned getFnStackAlignment(const TargetSubtargetInfo *STI, 126 const Function &F) { 127 if (F.hasFnAttribute(Attribute::StackAlignment)) 128 return F.getFnStackAlignment(); 129 return STI->getFrameLowering()->getStackAlignment(); 130 } 131 132 MachineFunction::MachineFunction(const Function &F, 133 const LLVMTargetMachine &Target, 134 const TargetSubtargetInfo &STI, 135 unsigned FunctionNum, MachineModuleInfo &mmi) 136 : F(F), Target(Target), STI(&STI), Ctx(mmi.getContext()), MMI(mmi) { 137 FunctionNumber = FunctionNum; 138 init(); 139 } 140 141 void MachineFunction::handleInsertion(MachineInstr &MI) { 142 if (TheDelegate) 143 TheDelegate->MF_HandleInsertion(MI); 144 } 145 146 void MachineFunction::handleRemoval(MachineInstr &MI) { 147 if (TheDelegate) 148 TheDelegate->MF_HandleRemoval(MI); 149 } 150 151 void MachineFunction::init() { 152 // Assume the function starts in SSA form with correct liveness. 153 Properties.set(MachineFunctionProperties::Property::IsSSA); 154 Properties.set(MachineFunctionProperties::Property::TracksLiveness); 155 if (STI->getRegisterInfo()) 156 RegInfo = new (Allocator) MachineRegisterInfo(this); 157 else 158 RegInfo = nullptr; 159 160 MFInfo = nullptr; 161 // We can realign the stack if the target supports it and the user hasn't 162 // explicitly asked us not to. 163 bool CanRealignSP = STI->getFrameLowering()->isStackRealignable() && 164 !F.hasFnAttribute("no-realign-stack"); 165 FrameInfo = new (Allocator) MachineFrameInfo( 166 getFnStackAlignment(STI, F), /*StackRealignable=*/CanRealignSP, 167 /*ForceRealign=*/CanRealignSP && 168 F.hasFnAttribute(Attribute::StackAlignment)); 169 170 if (F.hasFnAttribute(Attribute::StackAlignment)) 171 FrameInfo->ensureMaxAlignment(F.getFnStackAlignment()); 172 173 ConstantPool = new (Allocator) MachineConstantPool(getDataLayout()); 174 Alignment = STI->getTargetLowering()->getMinFunctionAlignment(); 175 176 // FIXME: Shouldn't use pref alignment if explicit alignment is set on F. 177 // FIXME: Use Function::hasOptSize(). 178 if (!F.hasFnAttribute(Attribute::OptimizeForSize)) 179 Alignment = std::max(Alignment, 180 STI->getTargetLowering()->getPrefFunctionAlignment()); 181 182 if (AlignAllFunctions) 183 Alignment = AlignAllFunctions; 184 185 JumpTableInfo = nullptr; 186 187 if (isFuncletEHPersonality(classifyEHPersonality( 188 F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) { 189 WinEHInfo = new (Allocator) WinEHFuncInfo(); 190 } 191 192 if (isScopedEHPersonality(classifyEHPersonality( 193 F.hasPersonalityFn() ? F.getPersonalityFn() : nullptr))) { 194 WasmEHInfo = new (Allocator) WasmEHFuncInfo(); 195 } 196 197 assert(Target.isCompatibleDataLayout(getDataLayout()) && 198 "Can't create a MachineFunction using a Module with a " 199 "Target-incompatible DataLayout attached\n"); 200 201 PSVManager = 202 llvm::make_unique<PseudoSourceValueManager>(*(getSubtarget(). 203 getInstrInfo())); 204 } 205 206 MachineFunction::~MachineFunction() { 207 clear(); 208 } 209 210 void MachineFunction::clear() { 211 Properties.reset(); 212 // Don't call destructors on MachineInstr and MachineOperand. All of their 213 // memory comes from the BumpPtrAllocator which is about to be purged. 214 // 215 // Do call MachineBasicBlock destructors, it contains std::vectors. 216 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I)) 217 I->Insts.clearAndLeakNodesUnsafely(); 218 MBBNumbering.clear(); 219 220 InstructionRecycler.clear(Allocator); 221 OperandRecycler.clear(Allocator); 222 BasicBlockRecycler.clear(Allocator); 223 CodeViewAnnotations.clear(); 224 VariableDbgInfos.clear(); 225 if (RegInfo) { 226 RegInfo->~MachineRegisterInfo(); 227 Allocator.Deallocate(RegInfo); 228 } 229 if (MFInfo) { 230 MFInfo->~MachineFunctionInfo(); 231 Allocator.Deallocate(MFInfo); 232 } 233 234 FrameInfo->~MachineFrameInfo(); 235 Allocator.Deallocate(FrameInfo); 236 237 ConstantPool->~MachineConstantPool(); 238 Allocator.Deallocate(ConstantPool); 239 240 if (JumpTableInfo) { 241 JumpTableInfo->~MachineJumpTableInfo(); 242 Allocator.Deallocate(JumpTableInfo); 243 } 244 245 if (WinEHInfo) { 246 WinEHInfo->~WinEHFuncInfo(); 247 Allocator.Deallocate(WinEHInfo); 248 } 249 250 if (WasmEHInfo) { 251 WasmEHInfo->~WasmEHFuncInfo(); 252 Allocator.Deallocate(WasmEHInfo); 253 } 254 } 255 256 const DataLayout &MachineFunction::getDataLayout() const { 257 return F.getParent()->getDataLayout(); 258 } 259 260 /// Get the JumpTableInfo for this function. 261 /// If it does not already exist, allocate one. 262 MachineJumpTableInfo *MachineFunction:: 263 getOrCreateJumpTableInfo(unsigned EntryKind) { 264 if (JumpTableInfo) return JumpTableInfo; 265 266 JumpTableInfo = new (Allocator) 267 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind); 268 return JumpTableInfo; 269 } 270 271 /// Should we be emitting segmented stack stuff for the function 272 bool MachineFunction::shouldSplitStack() const { 273 return getFunction().hasFnAttribute("split-stack"); 274 } 275 276 LLVM_NODISCARD unsigned 277 MachineFunction::addFrameInst(const MCCFIInstruction &Inst) { 278 FrameInstructions.push_back(Inst); 279 return FrameInstructions.size() - 1; 280 } 281 282 /// This discards all of the MachineBasicBlock numbers and recomputes them. 283 /// This guarantees that the MBB numbers are sequential, dense, and match the 284 /// ordering of the blocks within the function. If a specific MachineBasicBlock 285 /// is specified, only that block and those after it are renumbered. 286 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) { 287 if (empty()) { MBBNumbering.clear(); return; } 288 MachineFunction::iterator MBBI, E = end(); 289 if (MBB == nullptr) 290 MBBI = begin(); 291 else 292 MBBI = MBB->getIterator(); 293 294 // Figure out the block number this should have. 295 unsigned BlockNo = 0; 296 if (MBBI != begin()) 297 BlockNo = std::prev(MBBI)->getNumber() + 1; 298 299 for (; MBBI != E; ++MBBI, ++BlockNo) { 300 if (MBBI->getNumber() != (int)BlockNo) { 301 // Remove use of the old number. 302 if (MBBI->getNumber() != -1) { 303 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI && 304 "MBB number mismatch!"); 305 MBBNumbering[MBBI->getNumber()] = nullptr; 306 } 307 308 // If BlockNo is already taken, set that block's number to -1. 309 if (MBBNumbering[BlockNo]) 310 MBBNumbering[BlockNo]->setNumber(-1); 311 312 MBBNumbering[BlockNo] = &*MBBI; 313 MBBI->setNumber(BlockNo); 314 } 315 } 316 317 // Okay, all the blocks are renumbered. If we have compactified the block 318 // numbering, shrink MBBNumbering now. 319 assert(BlockNo <= MBBNumbering.size() && "Mismatch!"); 320 MBBNumbering.resize(BlockNo); 321 } 322 323 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'. 324 MachineInstr *MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID, 325 const DebugLoc &DL, 326 bool NoImp) { 327 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator)) 328 MachineInstr(*this, MCID, DL, NoImp); 329 } 330 331 /// Create a new MachineInstr which is a copy of the 'Orig' instruction, 332 /// identical in all ways except the instruction has no parent, prev, or next. 333 MachineInstr * 334 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) { 335 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator)) 336 MachineInstr(*this, *Orig); 337 } 338 339 MachineInstr &MachineFunction::CloneMachineInstrBundle(MachineBasicBlock &MBB, 340 MachineBasicBlock::iterator InsertBefore, const MachineInstr &Orig) { 341 MachineInstr *FirstClone = nullptr; 342 MachineBasicBlock::const_instr_iterator I = Orig.getIterator(); 343 while (true) { 344 MachineInstr *Cloned = CloneMachineInstr(&*I); 345 MBB.insert(InsertBefore, Cloned); 346 if (FirstClone == nullptr) { 347 FirstClone = Cloned; 348 } else { 349 Cloned->bundleWithPred(); 350 } 351 352 if (!I->isBundledWithSucc()) 353 break; 354 ++I; 355 } 356 return *FirstClone; 357 } 358 359 /// Delete the given MachineInstr. 360 /// 361 /// This function also serves as the MachineInstr destructor - the real 362 /// ~MachineInstr() destructor must be empty. 363 void 364 MachineFunction::DeleteMachineInstr(MachineInstr *MI) { 365 // Strip it for parts. The operand array and the MI object itself are 366 // independently recyclable. 367 if (MI->Operands) 368 deallocateOperandArray(MI->CapOperands, MI->Operands); 369 // Don't call ~MachineInstr() which must be trivial anyway because 370 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their 371 // destructors. 372 InstructionRecycler.Deallocate(Allocator, MI); 373 } 374 375 /// Allocate a new MachineBasicBlock. Use this instead of 376 /// `new MachineBasicBlock'. 377 MachineBasicBlock * 378 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) { 379 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator)) 380 MachineBasicBlock(*this, bb); 381 } 382 383 /// Delete the given MachineBasicBlock. 384 void 385 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) { 386 assert(MBB->getParent() == this && "MBB parent mismatch!"); 387 MBB->~MachineBasicBlock(); 388 BasicBlockRecycler.Deallocate(Allocator, MBB); 389 } 390 391 MachineMemOperand *MachineFunction::getMachineMemOperand( 392 MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, uint64_t s, 393 unsigned base_alignment, const AAMDNodes &AAInfo, const MDNode *Ranges, 394 SyncScope::ID SSID, AtomicOrdering Ordering, 395 AtomicOrdering FailureOrdering) { 396 return new (Allocator) 397 MachineMemOperand(PtrInfo, f, s, base_alignment, AAInfo, Ranges, 398 SSID, Ordering, FailureOrdering); 399 } 400 401 MachineMemOperand * 402 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 403 int64_t Offset, uint64_t Size) { 404 const MachinePointerInfo &PtrInfo = MMO->getPointerInfo(); 405 406 // If there is no pointer value, the offset isn't tracked so we need to adjust 407 // the base alignment. 408 unsigned Align = PtrInfo.V.isNull() 409 ? MinAlign(MMO->getBaseAlignment(), Offset) 410 : MMO->getBaseAlignment(); 411 412 return new (Allocator) 413 MachineMemOperand(PtrInfo.getWithOffset(Offset), MMO->getFlags(), Size, 414 Align, AAMDNodes(), nullptr, MMO->getSyncScopeID(), 415 MMO->getOrdering(), MMO->getFailureOrdering()); 416 } 417 418 MachineMemOperand * 419 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 420 const AAMDNodes &AAInfo) { 421 MachinePointerInfo MPI = MMO->getValue() ? 422 MachinePointerInfo(MMO->getValue(), MMO->getOffset()) : 423 MachinePointerInfo(MMO->getPseudoValue(), MMO->getOffset()); 424 425 return new (Allocator) 426 MachineMemOperand(MPI, MMO->getFlags(), MMO->getSize(), 427 MMO->getBaseAlignment(), AAInfo, 428 MMO->getRanges(), MMO->getSyncScopeID(), 429 MMO->getOrdering(), MMO->getFailureOrdering()); 430 } 431 432 MachineInstr::ExtraInfo * 433 MachineFunction::createMIExtraInfo(ArrayRef<MachineMemOperand *> MMOs, 434 MCSymbol *PreInstrSymbol, 435 MCSymbol *PostInstrSymbol) { 436 return MachineInstr::ExtraInfo::create(Allocator, MMOs, PreInstrSymbol, 437 PostInstrSymbol); 438 } 439 440 const char *MachineFunction::createExternalSymbolName(StringRef Name) { 441 char *Dest = Allocator.Allocate<char>(Name.size() + 1); 442 llvm::copy(Name, Dest); 443 Dest[Name.size()] = 0; 444 return Dest; 445 } 446 447 uint32_t *MachineFunction::allocateRegMask() { 448 unsigned NumRegs = getSubtarget().getRegisterInfo()->getNumRegs(); 449 unsigned Size = MachineOperand::getRegMaskSize(NumRegs); 450 uint32_t *Mask = Allocator.Allocate<uint32_t>(Size); 451 memset(Mask, 0, Size * sizeof(Mask[0])); 452 return Mask; 453 } 454 455 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 456 LLVM_DUMP_METHOD void MachineFunction::dump() const { 457 print(dbgs()); 458 } 459 #endif 460 461 StringRef MachineFunction::getName() const { 462 return getFunction().getName(); 463 } 464 465 void MachineFunction::print(raw_ostream &OS, const SlotIndexes *Indexes) const { 466 OS << "# Machine code for function " << getName() << ": "; 467 getProperties().print(OS); 468 OS << '\n'; 469 470 // Print Frame Information 471 FrameInfo->print(*this, OS); 472 473 // Print JumpTable Information 474 if (JumpTableInfo) 475 JumpTableInfo->print(OS); 476 477 // Print Constant Pool 478 ConstantPool->print(OS); 479 480 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo(); 481 482 if (RegInfo && !RegInfo->livein_empty()) { 483 OS << "Function Live Ins: "; 484 for (MachineRegisterInfo::livein_iterator 485 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) { 486 OS << printReg(I->first, TRI); 487 if (I->second) 488 OS << " in " << printReg(I->second, TRI); 489 if (std::next(I) != E) 490 OS << ", "; 491 } 492 OS << '\n'; 493 } 494 495 ModuleSlotTracker MST(getFunction().getParent()); 496 MST.incorporateFunction(getFunction()); 497 for (const auto &BB : *this) { 498 OS << '\n'; 499 // If we print the whole function, print it at its most verbose level. 500 BB.print(OS, MST, Indexes, /*IsStandalone=*/true); 501 } 502 503 OS << "\n# End machine code for function " << getName() << ".\n\n"; 504 } 505 506 namespace llvm { 507 508 template<> 509 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits { 510 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 511 512 static std::string getGraphName(const MachineFunction *F) { 513 return ("CFG for '" + F->getName() + "' function").str(); 514 } 515 516 std::string getNodeLabel(const MachineBasicBlock *Node, 517 const MachineFunction *Graph) { 518 std::string OutStr; 519 { 520 raw_string_ostream OSS(OutStr); 521 522 if (isSimple()) { 523 OSS << printMBBReference(*Node); 524 if (const BasicBlock *BB = Node->getBasicBlock()) 525 OSS << ": " << BB->getName(); 526 } else 527 Node->print(OSS); 528 } 529 530 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 531 532 // Process string output to make it nicer... 533 for (unsigned i = 0; i != OutStr.length(); ++i) 534 if (OutStr[i] == '\n') { // Left justify 535 OutStr[i] = '\\'; 536 OutStr.insert(OutStr.begin()+i+1, 'l'); 537 } 538 return OutStr; 539 } 540 }; 541 542 } // end namespace llvm 543 544 void MachineFunction::viewCFG() const 545 { 546 #ifndef NDEBUG 547 ViewGraph(this, "mf" + getName()); 548 #else 549 errs() << "MachineFunction::viewCFG is only available in debug builds on " 550 << "systems with Graphviz or gv!\n"; 551 #endif // NDEBUG 552 } 553 554 void MachineFunction::viewCFGOnly() const 555 { 556 #ifndef NDEBUG 557 ViewGraph(this, "mf" + getName(), true); 558 #else 559 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on " 560 << "systems with Graphviz or gv!\n"; 561 #endif // NDEBUG 562 } 563 564 /// Add the specified physical register as a live-in value and 565 /// create a corresponding virtual register for it. 566 unsigned MachineFunction::addLiveIn(unsigned PReg, 567 const TargetRegisterClass *RC) { 568 MachineRegisterInfo &MRI = getRegInfo(); 569 unsigned VReg = MRI.getLiveInVirtReg(PReg); 570 if (VReg) { 571 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg); 572 (void)VRegRC; 573 // A physical register can be added several times. 574 // Between two calls, the register class of the related virtual register 575 // may have been constrained to match some operation constraints. 576 // In that case, check that the current register class includes the 577 // physical register and is a sub class of the specified RC. 578 assert((VRegRC == RC || (VRegRC->contains(PReg) && 579 RC->hasSubClassEq(VRegRC))) && 580 "Register class mismatch!"); 581 return VReg; 582 } 583 VReg = MRI.createVirtualRegister(RC); 584 MRI.addLiveIn(PReg, VReg); 585 return VReg; 586 } 587 588 /// Return the MCSymbol for the specified non-empty jump table. 589 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a 590 /// normal 'L' label is returned. 591 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx, 592 bool isLinkerPrivate) const { 593 const DataLayout &DL = getDataLayout(); 594 assert(JumpTableInfo && "No jump tables"); 595 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!"); 596 597 StringRef Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix() 598 : DL.getPrivateGlobalPrefix(); 599 SmallString<60> Name; 600 raw_svector_ostream(Name) 601 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI; 602 return Ctx.getOrCreateSymbol(Name); 603 } 604 605 /// Return a function-local symbol to represent the PIC base. 606 MCSymbol *MachineFunction::getPICBaseSymbol() const { 607 const DataLayout &DL = getDataLayout(); 608 return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 609 Twine(getFunctionNumber()) + "$pb"); 610 } 611 612 /// \name Exception Handling 613 /// \{ 614 615 LandingPadInfo & 616 MachineFunction::getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad) { 617 unsigned N = LandingPads.size(); 618 for (unsigned i = 0; i < N; ++i) { 619 LandingPadInfo &LP = LandingPads[i]; 620 if (LP.LandingPadBlock == LandingPad) 621 return LP; 622 } 623 624 LandingPads.push_back(LandingPadInfo(LandingPad)); 625 return LandingPads[N]; 626 } 627 628 void MachineFunction::addInvoke(MachineBasicBlock *LandingPad, 629 MCSymbol *BeginLabel, MCSymbol *EndLabel) { 630 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 631 LP.BeginLabels.push_back(BeginLabel); 632 LP.EndLabels.push_back(EndLabel); 633 } 634 635 MCSymbol *MachineFunction::addLandingPad(MachineBasicBlock *LandingPad) { 636 MCSymbol *LandingPadLabel = Ctx.createTempSymbol(); 637 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 638 LP.LandingPadLabel = LandingPadLabel; 639 640 const Instruction *FirstI = LandingPad->getBasicBlock()->getFirstNonPHI(); 641 if (const auto *LPI = dyn_cast<LandingPadInst>(FirstI)) { 642 if (const auto *PF = 643 dyn_cast<Function>(F.getPersonalityFn()->stripPointerCasts())) 644 getMMI().addPersonality(PF); 645 646 if (LPI->isCleanup()) 647 addCleanup(LandingPad); 648 649 // FIXME: New EH - Add the clauses in reverse order. This isn't 100% 650 // correct, but we need to do it this way because of how the DWARF EH 651 // emitter processes the clauses. 652 for (unsigned I = LPI->getNumClauses(); I != 0; --I) { 653 Value *Val = LPI->getClause(I - 1); 654 if (LPI->isCatch(I - 1)) { 655 addCatchTypeInfo(LandingPad, 656 dyn_cast<GlobalValue>(Val->stripPointerCasts())); 657 } else { 658 // Add filters in a list. 659 auto *CVal = cast<Constant>(Val); 660 SmallVector<const GlobalValue *, 4> FilterList; 661 for (User::op_iterator II = CVal->op_begin(), IE = CVal->op_end(); 662 II != IE; ++II) 663 FilterList.push_back(cast<GlobalValue>((*II)->stripPointerCasts())); 664 665 addFilterTypeInfo(LandingPad, FilterList); 666 } 667 } 668 669 } else if (const auto *CPI = dyn_cast<CatchPadInst>(FirstI)) { 670 for (unsigned I = CPI->getNumArgOperands(); I != 0; --I) { 671 Value *TypeInfo = CPI->getArgOperand(I - 1)->stripPointerCasts(); 672 addCatchTypeInfo(LandingPad, dyn_cast<GlobalValue>(TypeInfo)); 673 } 674 675 } else { 676 assert(isa<CleanupPadInst>(FirstI) && "Invalid landingpad!"); 677 } 678 679 return LandingPadLabel; 680 } 681 682 void MachineFunction::addCatchTypeInfo(MachineBasicBlock *LandingPad, 683 ArrayRef<const GlobalValue *> TyInfo) { 684 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 685 for (unsigned N = TyInfo.size(); N; --N) 686 LP.TypeIds.push_back(getTypeIDFor(TyInfo[N - 1])); 687 } 688 689 void MachineFunction::addFilterTypeInfo(MachineBasicBlock *LandingPad, 690 ArrayRef<const GlobalValue *> TyInfo) { 691 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 692 std::vector<unsigned> IdsInFilter(TyInfo.size()); 693 for (unsigned I = 0, E = TyInfo.size(); I != E; ++I) 694 IdsInFilter[I] = getTypeIDFor(TyInfo[I]); 695 LP.TypeIds.push_back(getFilterIDFor(IdsInFilter)); 696 } 697 698 void MachineFunction::tidyLandingPads(DenseMap<MCSymbol *, uintptr_t> *LPMap, 699 bool TidyIfNoBeginLabels) { 700 for (unsigned i = 0; i != LandingPads.size(); ) { 701 LandingPadInfo &LandingPad = LandingPads[i]; 702 if (LandingPad.LandingPadLabel && 703 !LandingPad.LandingPadLabel->isDefined() && 704 (!LPMap || (*LPMap)[LandingPad.LandingPadLabel] == 0)) 705 LandingPad.LandingPadLabel = nullptr; 706 707 // Special case: we *should* emit LPs with null LP MBB. This indicates 708 // "nounwind" case. 709 if (!LandingPad.LandingPadLabel && LandingPad.LandingPadBlock) { 710 LandingPads.erase(LandingPads.begin() + i); 711 continue; 712 } 713 714 if (TidyIfNoBeginLabels) { 715 for (unsigned j = 0, e = LandingPads[i].BeginLabels.size(); j != e; ++j) { 716 MCSymbol *BeginLabel = LandingPad.BeginLabels[j]; 717 MCSymbol *EndLabel = LandingPad.EndLabels[j]; 718 if ((BeginLabel->isDefined() || (LPMap && (*LPMap)[BeginLabel] != 0)) && 719 (EndLabel->isDefined() || (LPMap && (*LPMap)[EndLabel] != 0))) 720 continue; 721 722 LandingPad.BeginLabels.erase(LandingPad.BeginLabels.begin() + j); 723 LandingPad.EndLabels.erase(LandingPad.EndLabels.begin() + j); 724 --j; 725 --e; 726 } 727 728 // Remove landing pads with no try-ranges. 729 if (LandingPads[i].BeginLabels.empty()) { 730 LandingPads.erase(LandingPads.begin() + i); 731 continue; 732 } 733 } 734 735 // If there is no landing pad, ensure that the list of typeids is empty. 736 // If the only typeid is a cleanup, this is the same as having no typeids. 737 if (!LandingPad.LandingPadBlock || 738 (LandingPad.TypeIds.size() == 1 && !LandingPad.TypeIds[0])) 739 LandingPad.TypeIds.clear(); 740 ++i; 741 } 742 } 743 744 void MachineFunction::addCleanup(MachineBasicBlock *LandingPad) { 745 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 746 LP.TypeIds.push_back(0); 747 } 748 749 void MachineFunction::addSEHCatchHandler(MachineBasicBlock *LandingPad, 750 const Function *Filter, 751 const BlockAddress *RecoverBA) { 752 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 753 SEHHandler Handler; 754 Handler.FilterOrFinally = Filter; 755 Handler.RecoverBA = RecoverBA; 756 LP.SEHHandlers.push_back(Handler); 757 } 758 759 void MachineFunction::addSEHCleanupHandler(MachineBasicBlock *LandingPad, 760 const Function *Cleanup) { 761 LandingPadInfo &LP = getOrCreateLandingPadInfo(LandingPad); 762 SEHHandler Handler; 763 Handler.FilterOrFinally = Cleanup; 764 Handler.RecoverBA = nullptr; 765 LP.SEHHandlers.push_back(Handler); 766 } 767 768 void MachineFunction::setCallSiteLandingPad(MCSymbol *Sym, 769 ArrayRef<unsigned> Sites) { 770 LPadToCallSiteMap[Sym].append(Sites.begin(), Sites.end()); 771 } 772 773 unsigned MachineFunction::getTypeIDFor(const GlobalValue *TI) { 774 for (unsigned i = 0, N = TypeInfos.size(); i != N; ++i) 775 if (TypeInfos[i] == TI) return i + 1; 776 777 TypeInfos.push_back(TI); 778 return TypeInfos.size(); 779 } 780 781 int MachineFunction::getFilterIDFor(std::vector<unsigned> &TyIds) { 782 // If the new filter coincides with the tail of an existing filter, then 783 // re-use the existing filter. Folding filters more than this requires 784 // re-ordering filters and/or their elements - probably not worth it. 785 for (std::vector<unsigned>::iterator I = FilterEnds.begin(), 786 E = FilterEnds.end(); I != E; ++I) { 787 unsigned i = *I, j = TyIds.size(); 788 789 while (i && j) 790 if (FilterIds[--i] != TyIds[--j]) 791 goto try_next; 792 793 if (!j) 794 // The new filter coincides with range [i, end) of the existing filter. 795 return -(1 + i); 796 797 try_next:; 798 } 799 800 // Add the new filter. 801 int FilterID = -(1 + FilterIds.size()); 802 FilterIds.reserve(FilterIds.size() + TyIds.size() + 1); 803 FilterIds.insert(FilterIds.end(), TyIds.begin(), TyIds.end()); 804 FilterEnds.push_back(FilterIds.size()); 805 FilterIds.push_back(0); // terminator 806 return FilterID; 807 } 808 809 /// \} 810 811 //===----------------------------------------------------------------------===// 812 // MachineJumpTableInfo implementation 813 //===----------------------------------------------------------------------===// 814 815 /// Return the size of each entry in the jump table. 816 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const { 817 // The size of a jump table entry is 4 bytes unless the entry is just the 818 // address of a block, in which case it is the pointer size. 819 switch (getEntryKind()) { 820 case MachineJumpTableInfo::EK_BlockAddress: 821 return TD.getPointerSize(); 822 case MachineJumpTableInfo::EK_GPRel64BlockAddress: 823 return 8; 824 case MachineJumpTableInfo::EK_GPRel32BlockAddress: 825 case MachineJumpTableInfo::EK_LabelDifference32: 826 case MachineJumpTableInfo::EK_Custom32: 827 return 4; 828 case MachineJumpTableInfo::EK_Inline: 829 return 0; 830 } 831 llvm_unreachable("Unknown jump table encoding!"); 832 } 833 834 /// Return the alignment of each entry in the jump table. 835 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const { 836 // The alignment of a jump table entry is the alignment of int32 unless the 837 // entry is just the address of a block, in which case it is the pointer 838 // alignment. 839 switch (getEntryKind()) { 840 case MachineJumpTableInfo::EK_BlockAddress: 841 return TD.getPointerABIAlignment(0); 842 case MachineJumpTableInfo::EK_GPRel64BlockAddress: 843 return TD.getABIIntegerTypeAlignment(64); 844 case MachineJumpTableInfo::EK_GPRel32BlockAddress: 845 case MachineJumpTableInfo::EK_LabelDifference32: 846 case MachineJumpTableInfo::EK_Custom32: 847 return TD.getABIIntegerTypeAlignment(32); 848 case MachineJumpTableInfo::EK_Inline: 849 return 1; 850 } 851 llvm_unreachable("Unknown jump table encoding!"); 852 } 853 854 /// Create a new jump table entry in the jump table info. 855 unsigned MachineJumpTableInfo::createJumpTableIndex( 856 const std::vector<MachineBasicBlock*> &DestBBs) { 857 assert(!DestBBs.empty() && "Cannot create an empty jump table!"); 858 JumpTables.push_back(MachineJumpTableEntry(DestBBs)); 859 return JumpTables.size()-1; 860 } 861 862 /// If Old is the target of any jump tables, update the jump tables to branch 863 /// to New instead. 864 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old, 865 MachineBasicBlock *New) { 866 assert(Old != New && "Not making a change?"); 867 bool MadeChange = false; 868 for (size_t i = 0, e = JumpTables.size(); i != e; ++i) 869 ReplaceMBBInJumpTable(i, Old, New); 870 return MadeChange; 871 } 872 873 /// If Old is a target of the jump tables, update the jump table to branch to 874 /// New instead. 875 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx, 876 MachineBasicBlock *Old, 877 MachineBasicBlock *New) { 878 assert(Old != New && "Not making a change?"); 879 bool MadeChange = false; 880 MachineJumpTableEntry &JTE = JumpTables[Idx]; 881 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j) 882 if (JTE.MBBs[j] == Old) { 883 JTE.MBBs[j] = New; 884 MadeChange = true; 885 } 886 return MadeChange; 887 } 888 889 void MachineJumpTableInfo::print(raw_ostream &OS) const { 890 if (JumpTables.empty()) return; 891 892 OS << "Jump Tables:\n"; 893 894 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) { 895 OS << printJumpTableEntryReference(i) << ": "; 896 for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j) 897 OS << ' ' << printMBBReference(*JumpTables[i].MBBs[j]); 898 } 899 900 OS << '\n'; 901 } 902 903 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 904 LLVM_DUMP_METHOD void MachineJumpTableInfo::dump() const { print(dbgs()); } 905 #endif 906 907 Printable llvm::printJumpTableEntryReference(unsigned Idx) { 908 return Printable([Idx](raw_ostream &OS) { OS << "%jump-table." << Idx; }); 909 } 910 911 //===----------------------------------------------------------------------===// 912 // MachineConstantPool implementation 913 //===----------------------------------------------------------------------===// 914 915 void MachineConstantPoolValue::anchor() {} 916 917 Type *MachineConstantPoolEntry::getType() const { 918 if (isMachineConstantPoolEntry()) 919 return Val.MachineCPVal->getType(); 920 return Val.ConstVal->getType(); 921 } 922 923 bool MachineConstantPoolEntry::needsRelocation() const { 924 if (isMachineConstantPoolEntry()) 925 return true; 926 return Val.ConstVal->needsRelocation(); 927 } 928 929 SectionKind 930 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const { 931 if (needsRelocation()) 932 return SectionKind::getReadOnlyWithRel(); 933 switch (DL->getTypeAllocSize(getType())) { 934 case 4: 935 return SectionKind::getMergeableConst4(); 936 case 8: 937 return SectionKind::getMergeableConst8(); 938 case 16: 939 return SectionKind::getMergeableConst16(); 940 case 32: 941 return SectionKind::getMergeableConst32(); 942 default: 943 return SectionKind::getReadOnly(); 944 } 945 } 946 947 MachineConstantPool::~MachineConstantPool() { 948 // A constant may be a member of both Constants and MachineCPVsSharingEntries, 949 // so keep track of which we've deleted to avoid double deletions. 950 DenseSet<MachineConstantPoolValue*> Deleted; 951 for (unsigned i = 0, e = Constants.size(); i != e; ++i) 952 if (Constants[i].isMachineConstantPoolEntry()) { 953 Deleted.insert(Constants[i].Val.MachineCPVal); 954 delete Constants[i].Val.MachineCPVal; 955 } 956 for (DenseSet<MachineConstantPoolValue*>::iterator I = 957 MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end(); 958 I != E; ++I) { 959 if (Deleted.count(*I) == 0) 960 delete *I; 961 } 962 } 963 964 /// Test whether the given two constants can be allocated the same constant pool 965 /// entry. 966 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B, 967 const DataLayout &DL) { 968 // Handle the trivial case quickly. 969 if (A == B) return true; 970 971 // If they have the same type but weren't the same constant, quickly 972 // reject them. 973 if (A->getType() == B->getType()) return false; 974 975 // We can't handle structs or arrays. 976 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) || 977 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType())) 978 return false; 979 980 // For now, only support constants with the same size. 981 uint64_t StoreSize = DL.getTypeStoreSize(A->getType()); 982 if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128) 983 return false; 984 985 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8); 986 987 // Try constant folding a bitcast of both instructions to an integer. If we 988 // get two identical ConstantInt's, then we are good to share them. We use 989 // the constant folding APIs to do this so that we get the benefit of 990 // DataLayout. 991 if (isa<PointerType>(A->getType())) 992 A = ConstantFoldCastOperand(Instruction::PtrToInt, 993 const_cast<Constant *>(A), IntTy, DL); 994 else if (A->getType() != IntTy) 995 A = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(A), 996 IntTy, DL); 997 if (isa<PointerType>(B->getType())) 998 B = ConstantFoldCastOperand(Instruction::PtrToInt, 999 const_cast<Constant *>(B), IntTy, DL); 1000 else if (B->getType() != IntTy) 1001 B = ConstantFoldCastOperand(Instruction::BitCast, const_cast<Constant *>(B), 1002 IntTy, DL); 1003 1004 return A == B; 1005 } 1006 1007 /// Create a new entry in the constant pool or return an existing one. 1008 /// User must specify the log2 of the minimum required alignment for the object. 1009 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C, 1010 unsigned Alignment) { 1011 assert(Alignment && "Alignment must be specified!"); 1012 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 1013 1014 // Check to see if we already have this constant. 1015 // 1016 // FIXME, this could be made much more efficient for large constant pools. 1017 for (unsigned i = 0, e = Constants.size(); i != e; ++i) 1018 if (!Constants[i].isMachineConstantPoolEntry() && 1019 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) { 1020 if ((unsigned)Constants[i].getAlignment() < Alignment) 1021 Constants[i].Alignment = Alignment; 1022 return i; 1023 } 1024 1025 Constants.push_back(MachineConstantPoolEntry(C, Alignment)); 1026 return Constants.size()-1; 1027 } 1028 1029 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V, 1030 unsigned Alignment) { 1031 assert(Alignment && "Alignment must be specified!"); 1032 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 1033 1034 // Check to see if we already have this constant. 1035 // 1036 // FIXME, this could be made much more efficient for large constant pools. 1037 int Idx = V->getExistingMachineCPValue(this, Alignment); 1038 if (Idx != -1) { 1039 MachineCPVsSharingEntries.insert(V); 1040 return (unsigned)Idx; 1041 } 1042 1043 Constants.push_back(MachineConstantPoolEntry(V, Alignment)); 1044 return Constants.size()-1; 1045 } 1046 1047 void MachineConstantPool::print(raw_ostream &OS) const { 1048 if (Constants.empty()) return; 1049 1050 OS << "Constant Pool:\n"; 1051 for (unsigned i = 0, e = Constants.size(); i != e; ++i) { 1052 OS << " cp#" << i << ": "; 1053 if (Constants[i].isMachineConstantPoolEntry()) 1054 Constants[i].Val.MachineCPVal->print(OS); 1055 else 1056 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false); 1057 OS << ", align=" << Constants[i].getAlignment(); 1058 OS << "\n"; 1059 } 1060 } 1061 1062 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1063 LLVM_DUMP_METHOD void MachineConstantPool::dump() const { print(dbgs()); } 1064 #endif 1065