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