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