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