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/CodeGen/MachineConstantPool.h" 21 #include "llvm/CodeGen/MachineFrameInfo.h" 22 #include "llvm/CodeGen/MachineFunctionInitializer.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/IR/DataLayout.h" 31 #include "llvm/IR/DebugInfo.h" 32 #include "llvm/IR/Function.h" 33 #include "llvm/IR/Module.h" 34 #include "llvm/IR/ModuleSlotTracker.h" 35 #include "llvm/MC/MCAsmInfo.h" 36 #include "llvm/MC/MCContext.h" 37 #include "llvm/Support/Debug.h" 38 #include "llvm/Support/GraphWriter.h" 39 #include "llvm/Support/raw_ostream.h" 40 #include "llvm/Target/TargetFrameLowering.h" 41 #include "llvm/Target/TargetLowering.h" 42 #include "llvm/Target/TargetMachine.h" 43 #include "llvm/Target/TargetSubtargetInfo.h" 44 using namespace llvm; 45 46 #define DEBUG_TYPE "codegen" 47 48 void MachineFunctionInitializer::anchor() {} 49 50 //===----------------------------------------------------------------------===// 51 // MachineFunction implementation 52 //===----------------------------------------------------------------------===// 53 54 // Out-of-line virtual method. 55 MachineFunctionInfo::~MachineFunctionInfo() {} 56 57 void ilist_traits<MachineBasicBlock>::deleteNode(MachineBasicBlock *MBB) { 58 MBB->getParent()->DeleteMachineBasicBlock(MBB); 59 } 60 61 MachineFunction::MachineFunction(const Function *F, const TargetMachine &TM, 62 unsigned FunctionNum, MachineModuleInfo &mmi) 63 : Fn(F), Target(TM), STI(TM.getSubtargetImpl(*F)), Ctx(mmi.getContext()), 64 MMI(mmi) { 65 if (STI->getRegisterInfo()) 66 RegInfo = new (Allocator) MachineRegisterInfo(this); 67 else 68 RegInfo = nullptr; 69 70 MFInfo = nullptr; 71 FrameInfo = new (Allocator) 72 MachineFrameInfo(STI->getFrameLowering()->getStackAlignment(), 73 STI->getFrameLowering()->isStackRealignable(), 74 !F->hasFnAttribute("no-realign-stack")); 75 76 if (Fn->hasFnAttribute(Attribute::StackAlignment)) 77 FrameInfo->ensureMaxAlignment(Fn->getFnStackAlignment()); 78 79 ConstantPool = new (Allocator) MachineConstantPool(getDataLayout()); 80 Alignment = STI->getTargetLowering()->getMinFunctionAlignment(); 81 82 // FIXME: Shouldn't use pref alignment if explicit alignment is set on Fn. 83 // FIXME: Use Function::optForSize(). 84 if (!Fn->hasFnAttribute(Attribute::OptimizeForSize)) 85 Alignment = std::max(Alignment, 86 STI->getTargetLowering()->getPrefFunctionAlignment()); 87 88 FunctionNumber = FunctionNum; 89 JumpTableInfo = nullptr; 90 PSVManager = llvm::make_unique<PseudoSourceValueManager>(); 91 } 92 93 MachineFunction::~MachineFunction() { 94 // Don't call destructors on MachineInstr and MachineOperand. All of their 95 // memory comes from the BumpPtrAllocator which is about to be purged. 96 // 97 // Do call MachineBasicBlock destructors, it contains std::vectors. 98 for (iterator I = begin(), E = end(); I != E; I = BasicBlocks.erase(I)) 99 I->Insts.clearAndLeakNodesUnsafely(); 100 101 InstructionRecycler.clear(Allocator); 102 OperandRecycler.clear(Allocator); 103 BasicBlockRecycler.clear(Allocator); 104 if (RegInfo) { 105 RegInfo->~MachineRegisterInfo(); 106 Allocator.Deallocate(RegInfo); 107 } 108 if (MFInfo) { 109 MFInfo->~MachineFunctionInfo(); 110 Allocator.Deallocate(MFInfo); 111 } 112 113 FrameInfo->~MachineFrameInfo(); 114 Allocator.Deallocate(FrameInfo); 115 116 ConstantPool->~MachineConstantPool(); 117 Allocator.Deallocate(ConstantPool); 118 119 if (JumpTableInfo) { 120 JumpTableInfo->~MachineJumpTableInfo(); 121 Allocator.Deallocate(JumpTableInfo); 122 } 123 } 124 125 const DataLayout &MachineFunction::getDataLayout() const { 126 return Fn->getParent()->getDataLayout(); 127 } 128 129 /// Get the JumpTableInfo for this function. 130 /// If it does not already exist, allocate one. 131 MachineJumpTableInfo *MachineFunction:: 132 getOrCreateJumpTableInfo(unsigned EntryKind) { 133 if (JumpTableInfo) return JumpTableInfo; 134 135 JumpTableInfo = new (Allocator) 136 MachineJumpTableInfo((MachineJumpTableInfo::JTEntryKind)EntryKind); 137 return JumpTableInfo; 138 } 139 140 /// Should we be emitting segmented stack stuff for the function 141 bool MachineFunction::shouldSplitStack() { 142 return getFunction()->hasFnAttribute("split-stack"); 143 } 144 145 /// This discards all of the MachineBasicBlock numbers and recomputes them. 146 /// This guarantees that the MBB numbers are sequential, dense, and match the 147 /// ordering of the blocks within the function. If a specific MachineBasicBlock 148 /// is specified, only that block and those after it are renumbered. 149 void MachineFunction::RenumberBlocks(MachineBasicBlock *MBB) { 150 if (empty()) { MBBNumbering.clear(); return; } 151 MachineFunction::iterator MBBI, E = end(); 152 if (MBB == nullptr) 153 MBBI = begin(); 154 else 155 MBBI = MBB; 156 157 // Figure out the block number this should have. 158 unsigned BlockNo = 0; 159 if (MBBI != begin()) 160 BlockNo = std::prev(MBBI)->getNumber() + 1; 161 162 for (; MBBI != E; ++MBBI, ++BlockNo) { 163 if (MBBI->getNumber() != (int)BlockNo) { 164 // Remove use of the old number. 165 if (MBBI->getNumber() != -1) { 166 assert(MBBNumbering[MBBI->getNumber()] == &*MBBI && 167 "MBB number mismatch!"); 168 MBBNumbering[MBBI->getNumber()] = nullptr; 169 } 170 171 // If BlockNo is already taken, set that block's number to -1. 172 if (MBBNumbering[BlockNo]) 173 MBBNumbering[BlockNo]->setNumber(-1); 174 175 MBBNumbering[BlockNo] = MBBI; 176 MBBI->setNumber(BlockNo); 177 } 178 } 179 180 // Okay, all the blocks are renumbered. If we have compactified the block 181 // numbering, shrink MBBNumbering now. 182 assert(BlockNo <= MBBNumbering.size() && "Mismatch!"); 183 MBBNumbering.resize(BlockNo); 184 } 185 186 /// Allocate a new MachineInstr. Use this instead of `new MachineInstr'. 187 MachineInstr * 188 MachineFunction::CreateMachineInstr(const MCInstrDesc &MCID, 189 DebugLoc DL, bool NoImp) { 190 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator)) 191 MachineInstr(*this, MCID, DL, NoImp); 192 } 193 194 /// Create a new MachineInstr which is a copy of the 'Orig' instruction, 195 /// identical in all ways except the instruction has no parent, prev, or next. 196 MachineInstr * 197 MachineFunction::CloneMachineInstr(const MachineInstr *Orig) { 198 return new (InstructionRecycler.Allocate<MachineInstr>(Allocator)) 199 MachineInstr(*this, *Orig); 200 } 201 202 /// Delete the given MachineInstr. 203 /// 204 /// This function also serves as the MachineInstr destructor - the real 205 /// ~MachineInstr() destructor must be empty. 206 void 207 MachineFunction::DeleteMachineInstr(MachineInstr *MI) { 208 // Strip it for parts. The operand array and the MI object itself are 209 // independently recyclable. 210 if (MI->Operands) 211 deallocateOperandArray(MI->CapOperands, MI->Operands); 212 // Don't call ~MachineInstr() which must be trivial anyway because 213 // ~MachineFunction drops whole lists of MachineInstrs wihout calling their 214 // destructors. 215 InstructionRecycler.Deallocate(Allocator, MI); 216 } 217 218 /// Allocate a new MachineBasicBlock. Use this instead of 219 /// `new MachineBasicBlock'. 220 MachineBasicBlock * 221 MachineFunction::CreateMachineBasicBlock(const BasicBlock *bb) { 222 return new (BasicBlockRecycler.Allocate<MachineBasicBlock>(Allocator)) 223 MachineBasicBlock(*this, bb); 224 } 225 226 /// Delete the given MachineBasicBlock. 227 void 228 MachineFunction::DeleteMachineBasicBlock(MachineBasicBlock *MBB) { 229 assert(MBB->getParent() == this && "MBB parent mismatch!"); 230 MBB->~MachineBasicBlock(); 231 BasicBlockRecycler.Deallocate(Allocator, MBB); 232 } 233 234 MachineMemOperand * 235 MachineFunction::getMachineMemOperand(MachinePointerInfo PtrInfo, unsigned f, 236 uint64_t s, unsigned base_alignment, 237 const AAMDNodes &AAInfo, 238 const MDNode *Ranges) { 239 return new (Allocator) MachineMemOperand(PtrInfo, f, s, base_alignment, 240 AAInfo, Ranges); 241 } 242 243 MachineMemOperand * 244 MachineFunction::getMachineMemOperand(const MachineMemOperand *MMO, 245 int64_t Offset, uint64_t Size) { 246 if (MMO->getValue()) 247 return new (Allocator) 248 MachineMemOperand(MachinePointerInfo(MMO->getValue(), 249 MMO->getOffset()+Offset), 250 MMO->getFlags(), Size, 251 MMO->getBaseAlignment()); 252 return new (Allocator) 253 MachineMemOperand(MachinePointerInfo(MMO->getPseudoValue(), 254 MMO->getOffset()+Offset), 255 MMO->getFlags(), Size, 256 MMO->getBaseAlignment()); 257 } 258 259 MachineInstr::mmo_iterator 260 MachineFunction::allocateMemRefsArray(unsigned long Num) { 261 return Allocator.Allocate<MachineMemOperand *>(Num); 262 } 263 264 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator> 265 MachineFunction::extractLoadMemRefs(MachineInstr::mmo_iterator Begin, 266 MachineInstr::mmo_iterator End) { 267 // Count the number of load mem refs. 268 unsigned Num = 0; 269 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) 270 if ((*I)->isLoad()) 271 ++Num; 272 273 // Allocate a new array and populate it with the load information. 274 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num); 275 unsigned Index = 0; 276 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) { 277 if ((*I)->isLoad()) { 278 if (!(*I)->isStore()) 279 // Reuse the MMO. 280 Result[Index] = *I; 281 else { 282 // Clone the MMO and unset the store flag. 283 MachineMemOperand *JustLoad = 284 getMachineMemOperand((*I)->getPointerInfo(), 285 (*I)->getFlags() & ~MachineMemOperand::MOStore, 286 (*I)->getSize(), (*I)->getBaseAlignment(), 287 (*I)->getAAInfo()); 288 Result[Index] = JustLoad; 289 } 290 ++Index; 291 } 292 } 293 return std::make_pair(Result, Result + Num); 294 } 295 296 std::pair<MachineInstr::mmo_iterator, MachineInstr::mmo_iterator> 297 MachineFunction::extractStoreMemRefs(MachineInstr::mmo_iterator Begin, 298 MachineInstr::mmo_iterator End) { 299 // Count the number of load mem refs. 300 unsigned Num = 0; 301 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) 302 if ((*I)->isStore()) 303 ++Num; 304 305 // Allocate a new array and populate it with the store information. 306 MachineInstr::mmo_iterator Result = allocateMemRefsArray(Num); 307 unsigned Index = 0; 308 for (MachineInstr::mmo_iterator I = Begin; I != End; ++I) { 309 if ((*I)->isStore()) { 310 if (!(*I)->isLoad()) 311 // Reuse the MMO. 312 Result[Index] = *I; 313 else { 314 // Clone the MMO and unset the load flag. 315 MachineMemOperand *JustStore = 316 getMachineMemOperand((*I)->getPointerInfo(), 317 (*I)->getFlags() & ~MachineMemOperand::MOLoad, 318 (*I)->getSize(), (*I)->getBaseAlignment(), 319 (*I)->getAAInfo()); 320 Result[Index] = JustStore; 321 } 322 ++Index; 323 } 324 } 325 return std::make_pair(Result, Result + Num); 326 } 327 328 const char *MachineFunction::createExternalSymbolName(StringRef Name) { 329 char *Dest = Allocator.Allocate<char>(Name.size() + 1); 330 std::copy(Name.begin(), Name.end(), Dest); 331 Dest[Name.size()] = 0; 332 return Dest; 333 } 334 335 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 336 void MachineFunction::dump() const { 337 print(dbgs()); 338 } 339 #endif 340 341 StringRef MachineFunction::getName() const { 342 assert(getFunction() && "No function!"); 343 return getFunction()->getName(); 344 } 345 346 void MachineFunction::print(raw_ostream &OS, SlotIndexes *Indexes) const { 347 OS << "# Machine code for function " << getName() << ": "; 348 if (RegInfo) { 349 OS << (RegInfo->isSSA() ? "SSA" : "Post SSA"); 350 if (!RegInfo->tracksLiveness()) 351 OS << ", not tracking liveness"; 352 } 353 OS << '\n'; 354 355 // Print Frame Information 356 FrameInfo->print(*this, OS); 357 358 // Print JumpTable Information 359 if (JumpTableInfo) 360 JumpTableInfo->print(OS); 361 362 // Print Constant Pool 363 ConstantPool->print(OS); 364 365 const TargetRegisterInfo *TRI = getSubtarget().getRegisterInfo(); 366 367 if (RegInfo && !RegInfo->livein_empty()) { 368 OS << "Function Live Ins: "; 369 for (MachineRegisterInfo::livein_iterator 370 I = RegInfo->livein_begin(), E = RegInfo->livein_end(); I != E; ++I) { 371 OS << PrintReg(I->first, TRI); 372 if (I->second) 373 OS << " in " << PrintReg(I->second, TRI); 374 if (std::next(I) != E) 375 OS << ", "; 376 } 377 OS << '\n'; 378 } 379 380 ModuleSlotTracker MST(getFunction()->getParent()); 381 MST.incorporateFunction(*getFunction()); 382 for (const auto &BB : *this) { 383 OS << '\n'; 384 BB.print(OS, MST, Indexes); 385 } 386 387 OS << "\n# End machine code for function " << getName() << ".\n\n"; 388 } 389 390 namespace llvm { 391 template<> 392 struct DOTGraphTraits<const MachineFunction*> : public DefaultDOTGraphTraits { 393 394 DOTGraphTraits (bool isSimple=false) : DefaultDOTGraphTraits(isSimple) {} 395 396 static std::string getGraphName(const MachineFunction *F) { 397 return ("CFG for '" + F->getName() + "' function").str(); 398 } 399 400 std::string getNodeLabel(const MachineBasicBlock *Node, 401 const MachineFunction *Graph) { 402 std::string OutStr; 403 { 404 raw_string_ostream OSS(OutStr); 405 406 if (isSimple()) { 407 OSS << "BB#" << Node->getNumber(); 408 if (const BasicBlock *BB = Node->getBasicBlock()) 409 OSS << ": " << BB->getName(); 410 } else 411 Node->print(OSS); 412 } 413 414 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin()); 415 416 // Process string output to make it nicer... 417 for (unsigned i = 0; i != OutStr.length(); ++i) 418 if (OutStr[i] == '\n') { // Left justify 419 OutStr[i] = '\\'; 420 OutStr.insert(OutStr.begin()+i+1, 'l'); 421 } 422 return OutStr; 423 } 424 }; 425 } 426 427 void MachineFunction::viewCFG() const 428 { 429 #ifndef NDEBUG 430 ViewGraph(this, "mf" + getName()); 431 #else 432 errs() << "MachineFunction::viewCFG is only available in debug builds on " 433 << "systems with Graphviz or gv!\n"; 434 #endif // NDEBUG 435 } 436 437 void MachineFunction::viewCFGOnly() const 438 { 439 #ifndef NDEBUG 440 ViewGraph(this, "mf" + getName(), true); 441 #else 442 errs() << "MachineFunction::viewCFGOnly is only available in debug builds on " 443 << "systems with Graphviz or gv!\n"; 444 #endif // NDEBUG 445 } 446 447 /// Add the specified physical register as a live-in value and 448 /// create a corresponding virtual register for it. 449 unsigned MachineFunction::addLiveIn(unsigned PReg, 450 const TargetRegisterClass *RC) { 451 MachineRegisterInfo &MRI = getRegInfo(); 452 unsigned VReg = MRI.getLiveInVirtReg(PReg); 453 if (VReg) { 454 const TargetRegisterClass *VRegRC = MRI.getRegClass(VReg); 455 (void)VRegRC; 456 // A physical register can be added several times. 457 // Between two calls, the register class of the related virtual register 458 // may have been constrained to match some operation constraints. 459 // In that case, check that the current register class includes the 460 // physical register and is a sub class of the specified RC. 461 assert((VRegRC == RC || (VRegRC->contains(PReg) && 462 RC->hasSubClassEq(VRegRC))) && 463 "Register class mismatch!"); 464 return VReg; 465 } 466 VReg = MRI.createVirtualRegister(RC); 467 MRI.addLiveIn(PReg, VReg); 468 return VReg; 469 } 470 471 /// Return the MCSymbol for the specified non-empty jump table. 472 /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a 473 /// normal 'L' label is returned. 474 MCSymbol *MachineFunction::getJTISymbol(unsigned JTI, MCContext &Ctx, 475 bool isLinkerPrivate) const { 476 const DataLayout &DL = getDataLayout(); 477 assert(JumpTableInfo && "No jump tables"); 478 assert(JTI < JumpTableInfo->getJumpTables().size() && "Invalid JTI!"); 479 480 const char *Prefix = isLinkerPrivate ? DL.getLinkerPrivateGlobalPrefix() 481 : DL.getPrivateGlobalPrefix(); 482 SmallString<60> Name; 483 raw_svector_ostream(Name) 484 << Prefix << "JTI" << getFunctionNumber() << '_' << JTI; 485 return Ctx.getOrCreateSymbol(Name); 486 } 487 488 /// Return a function-local symbol to represent the PIC base. 489 MCSymbol *MachineFunction::getPICBaseSymbol() const { 490 const DataLayout &DL = getDataLayout(); 491 return Ctx.getOrCreateSymbol(Twine(DL.getPrivateGlobalPrefix()) + 492 Twine(getFunctionNumber()) + "$pb"); 493 } 494 495 //===----------------------------------------------------------------------===// 496 // MachineFrameInfo implementation 497 //===----------------------------------------------------------------------===// 498 499 /// Make sure the function is at least Align bytes aligned. 500 void MachineFrameInfo::ensureMaxAlignment(unsigned Align) { 501 if (!StackRealignable || !RealignOption) 502 assert(Align <= StackAlignment && 503 "For targets without stack realignment, Align is out of limit!"); 504 if (MaxAlignment < Align) MaxAlignment = Align; 505 } 506 507 /// Clamp the alignment if requested and emit a warning. 508 static inline unsigned clampStackAlignment(bool ShouldClamp, unsigned Align, 509 unsigned StackAlign) { 510 if (!ShouldClamp || Align <= StackAlign) 511 return Align; 512 DEBUG(dbgs() << "Warning: requested alignment " << Align 513 << " exceeds the stack alignment " << StackAlign 514 << " when stack realignment is off" << '\n'); 515 return StackAlign; 516 } 517 518 /// Create a new statically sized stack object, returning a nonnegative 519 /// identifier to represent it. 520 int MachineFrameInfo::CreateStackObject(uint64_t Size, unsigned Alignment, 521 bool isSS, const AllocaInst *Alloca) { 522 assert(Size != 0 && "Cannot allocate zero size stack objects!"); 523 Alignment = clampStackAlignment(!StackRealignable || !RealignOption, 524 Alignment, StackAlignment); 525 Objects.push_back(StackObject(Size, Alignment, 0, false, isSS, Alloca, 526 !isSS)); 527 int Index = (int)Objects.size() - NumFixedObjects - 1; 528 assert(Index >= 0 && "Bad frame index!"); 529 ensureMaxAlignment(Alignment); 530 return Index; 531 } 532 533 /// Create a new statically sized stack object that represents a spill slot, 534 /// returning a nonnegative identifier to represent it. 535 int MachineFrameInfo::CreateSpillStackObject(uint64_t Size, 536 unsigned Alignment) { 537 Alignment = clampStackAlignment(!StackRealignable || !RealignOption, 538 Alignment, StackAlignment); 539 CreateStackObject(Size, Alignment, true); 540 int Index = (int)Objects.size() - NumFixedObjects - 1; 541 ensureMaxAlignment(Alignment); 542 return Index; 543 } 544 545 /// Notify the MachineFrameInfo object that a variable sized object has been 546 /// created. This must be created whenever a variable sized object is created, 547 /// whether or not the index returned is actually used. 548 int MachineFrameInfo::CreateVariableSizedObject(unsigned Alignment, 549 const AllocaInst *Alloca) { 550 HasVarSizedObjects = true; 551 Alignment = clampStackAlignment(!StackRealignable || !RealignOption, 552 Alignment, StackAlignment); 553 Objects.push_back(StackObject(0, Alignment, 0, false, false, Alloca, true)); 554 ensureMaxAlignment(Alignment); 555 return (int)Objects.size()-NumFixedObjects-1; 556 } 557 558 /// Create a new object at a fixed location on the stack. 559 /// All fixed objects should be created before other objects are created for 560 /// efficiency. By default, fixed objects are immutable. This returns an 561 /// index with a negative value. 562 int MachineFrameInfo::CreateFixedObject(uint64_t Size, int64_t SPOffset, 563 bool Immutable, bool isAliased) { 564 assert(Size != 0 && "Cannot allocate zero size fixed stack objects!"); 565 // The alignment of the frame index can be determined from its offset from 566 // the incoming frame position. If the frame object is at offset 32 and 567 // the stack is guaranteed to be 16-byte aligned, then we know that the 568 // object is 16-byte aligned. 569 unsigned Align = MinAlign(SPOffset, StackAlignment); 570 Align = clampStackAlignment(!StackRealignable || !RealignOption, Align, 571 StackAlignment); 572 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, Immutable, 573 /*isSS*/ false, 574 /*Alloca*/ nullptr, isAliased)); 575 return -++NumFixedObjects; 576 } 577 578 /// Create a spill slot at a fixed location on the stack. 579 /// Returns an index with a negative value. 580 int MachineFrameInfo::CreateFixedSpillStackObject(uint64_t Size, 581 int64_t SPOffset) { 582 unsigned Align = MinAlign(SPOffset, StackAlignment); 583 Align = clampStackAlignment(!StackRealignable || !RealignOption, Align, 584 StackAlignment); 585 Objects.insert(Objects.begin(), StackObject(Size, Align, SPOffset, 586 /*Immutable*/ true, 587 /*isSS*/ true, 588 /*Alloca*/ nullptr, 589 /*isAliased*/ false)); 590 return -++NumFixedObjects; 591 } 592 593 BitVector MachineFrameInfo::getPristineRegs(const MachineFunction &MF) const { 594 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 595 BitVector BV(TRI->getNumRegs()); 596 597 // Before CSI is calculated, no registers are considered pristine. They can be 598 // freely used and PEI will make sure they are saved. 599 if (!isCalleeSavedInfoValid()) 600 return BV; 601 602 for (const MCPhysReg *CSR = TRI->getCalleeSavedRegs(&MF); CSR && *CSR; ++CSR) 603 BV.set(*CSR); 604 605 // Saved CSRs are not pristine. 606 const std::vector<CalleeSavedInfo> &CSI = getCalleeSavedInfo(); 607 for (std::vector<CalleeSavedInfo>::const_iterator I = CSI.begin(), 608 E = CSI.end(); I != E; ++I) 609 BV.reset(I->getReg()); 610 611 return BV; 612 } 613 614 unsigned MachineFrameInfo::estimateStackSize(const MachineFunction &MF) const { 615 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); 616 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo(); 617 unsigned MaxAlign = getMaxAlignment(); 618 int Offset = 0; 619 620 // This code is very, very similar to PEI::calculateFrameObjectOffsets(). 621 // It really should be refactored to share code. Until then, changes 622 // should keep in mind that there's tight coupling between the two. 623 624 for (int i = getObjectIndexBegin(); i != 0; ++i) { 625 int FixedOff = -getObjectOffset(i); 626 if (FixedOff > Offset) Offset = FixedOff; 627 } 628 for (unsigned i = 0, e = getObjectIndexEnd(); i != e; ++i) { 629 if (isDeadObjectIndex(i)) 630 continue; 631 Offset += getObjectSize(i); 632 unsigned Align = getObjectAlignment(i); 633 // Adjust to alignment boundary 634 Offset = (Offset+Align-1)/Align*Align; 635 636 MaxAlign = std::max(Align, MaxAlign); 637 } 638 639 if (adjustsStack() && TFI->hasReservedCallFrame(MF)) 640 Offset += getMaxCallFrameSize(); 641 642 // Round up the size to a multiple of the alignment. If the function has 643 // any calls or alloca's, align to the target's StackAlignment value to 644 // ensure that the callee's frame or the alloca data is suitably aligned; 645 // otherwise, for leaf functions, align to the TransientStackAlignment 646 // value. 647 unsigned StackAlign; 648 if (adjustsStack() || hasVarSizedObjects() || 649 (RegInfo->needsStackRealignment(MF) && getObjectIndexEnd() != 0)) 650 StackAlign = TFI->getStackAlignment(); 651 else 652 StackAlign = TFI->getTransientStackAlignment(); 653 654 // If the frame pointer is eliminated, all frame offsets will be relative to 655 // SP not FP. Align to MaxAlign so this works. 656 StackAlign = std::max(StackAlign, MaxAlign); 657 unsigned AlignMask = StackAlign - 1; 658 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask); 659 660 return (unsigned)Offset; 661 } 662 663 void MachineFrameInfo::print(const MachineFunction &MF, raw_ostream &OS) const{ 664 if (Objects.empty()) return; 665 666 const TargetFrameLowering *FI = MF.getSubtarget().getFrameLowering(); 667 int ValOffset = (FI ? FI->getOffsetOfLocalArea() : 0); 668 669 OS << "Frame Objects:\n"; 670 671 for (unsigned i = 0, e = Objects.size(); i != e; ++i) { 672 const StackObject &SO = Objects[i]; 673 OS << " fi#" << (int)(i-NumFixedObjects) << ": "; 674 if (SO.Size == ~0ULL) { 675 OS << "dead\n"; 676 continue; 677 } 678 if (SO.Size == 0) 679 OS << "variable sized"; 680 else 681 OS << "size=" << SO.Size; 682 OS << ", align=" << SO.Alignment; 683 684 if (i < NumFixedObjects) 685 OS << ", fixed"; 686 if (i < NumFixedObjects || SO.SPOffset != -1) { 687 int64_t Off = SO.SPOffset - ValOffset; 688 OS << ", at location [SP"; 689 if (Off > 0) 690 OS << "+" << Off; 691 else if (Off < 0) 692 OS << Off; 693 OS << "]"; 694 } 695 OS << "\n"; 696 } 697 } 698 699 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 700 void MachineFrameInfo::dump(const MachineFunction &MF) const { 701 print(MF, dbgs()); 702 } 703 #endif 704 705 //===----------------------------------------------------------------------===// 706 // MachineJumpTableInfo implementation 707 //===----------------------------------------------------------------------===// 708 709 /// Return the size of each entry in the jump table. 710 unsigned MachineJumpTableInfo::getEntrySize(const DataLayout &TD) const { 711 // The size of a jump table entry is 4 bytes unless the entry is just the 712 // address of a block, in which case it is the pointer size. 713 switch (getEntryKind()) { 714 case MachineJumpTableInfo::EK_BlockAddress: 715 return TD.getPointerSize(); 716 case MachineJumpTableInfo::EK_GPRel64BlockAddress: 717 return 8; 718 case MachineJumpTableInfo::EK_GPRel32BlockAddress: 719 case MachineJumpTableInfo::EK_LabelDifference32: 720 case MachineJumpTableInfo::EK_Custom32: 721 return 4; 722 case MachineJumpTableInfo::EK_Inline: 723 return 0; 724 } 725 llvm_unreachable("Unknown jump table encoding!"); 726 } 727 728 /// Return the alignment of each entry in the jump table. 729 unsigned MachineJumpTableInfo::getEntryAlignment(const DataLayout &TD) const { 730 // The alignment of a jump table entry is the alignment of int32 unless the 731 // entry is just the address of a block, in which case it is the pointer 732 // alignment. 733 switch (getEntryKind()) { 734 case MachineJumpTableInfo::EK_BlockAddress: 735 return TD.getPointerABIAlignment(); 736 case MachineJumpTableInfo::EK_GPRel64BlockAddress: 737 return TD.getABIIntegerTypeAlignment(64); 738 case MachineJumpTableInfo::EK_GPRel32BlockAddress: 739 case MachineJumpTableInfo::EK_LabelDifference32: 740 case MachineJumpTableInfo::EK_Custom32: 741 return TD.getABIIntegerTypeAlignment(32); 742 case MachineJumpTableInfo::EK_Inline: 743 return 1; 744 } 745 llvm_unreachable("Unknown jump table encoding!"); 746 } 747 748 /// Create a new jump table entry in the jump table info. 749 unsigned MachineJumpTableInfo::createJumpTableIndex( 750 const std::vector<MachineBasicBlock*> &DestBBs) { 751 assert(!DestBBs.empty() && "Cannot create an empty jump table!"); 752 JumpTables.push_back(MachineJumpTableEntry(DestBBs)); 753 return JumpTables.size()-1; 754 } 755 756 /// If Old is the target of any jump tables, update the jump tables to branch 757 /// to New instead. 758 bool MachineJumpTableInfo::ReplaceMBBInJumpTables(MachineBasicBlock *Old, 759 MachineBasicBlock *New) { 760 assert(Old != New && "Not making a change?"); 761 bool MadeChange = false; 762 for (size_t i = 0, e = JumpTables.size(); i != e; ++i) 763 ReplaceMBBInJumpTable(i, Old, New); 764 return MadeChange; 765 } 766 767 /// If Old is a target of the jump tables, update the jump table to branch to 768 /// New instead. 769 bool MachineJumpTableInfo::ReplaceMBBInJumpTable(unsigned Idx, 770 MachineBasicBlock *Old, 771 MachineBasicBlock *New) { 772 assert(Old != New && "Not making a change?"); 773 bool MadeChange = false; 774 MachineJumpTableEntry &JTE = JumpTables[Idx]; 775 for (size_t j = 0, e = JTE.MBBs.size(); j != e; ++j) 776 if (JTE.MBBs[j] == Old) { 777 JTE.MBBs[j] = New; 778 MadeChange = true; 779 } 780 return MadeChange; 781 } 782 783 void MachineJumpTableInfo::print(raw_ostream &OS) const { 784 if (JumpTables.empty()) return; 785 786 OS << "Jump Tables:\n"; 787 788 for (unsigned i = 0, e = JumpTables.size(); i != e; ++i) { 789 OS << " jt#" << i << ": "; 790 for (unsigned j = 0, f = JumpTables[i].MBBs.size(); j != f; ++j) 791 OS << " BB#" << JumpTables[i].MBBs[j]->getNumber(); 792 } 793 794 OS << '\n'; 795 } 796 797 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 798 void MachineJumpTableInfo::dump() const { print(dbgs()); } 799 #endif 800 801 802 //===----------------------------------------------------------------------===// 803 // MachineConstantPool implementation 804 //===----------------------------------------------------------------------===// 805 806 void MachineConstantPoolValue::anchor() { } 807 808 Type *MachineConstantPoolEntry::getType() const { 809 if (isMachineConstantPoolEntry()) 810 return Val.MachineCPVal->getType(); 811 return Val.ConstVal->getType(); 812 } 813 814 815 unsigned MachineConstantPoolEntry::getRelocationInfo() const { 816 if (isMachineConstantPoolEntry()) 817 return Val.MachineCPVal->getRelocationInfo(); 818 return Val.ConstVal->getRelocationInfo(); 819 } 820 821 SectionKind 822 MachineConstantPoolEntry::getSectionKind(const DataLayout *DL) const { 823 SectionKind Kind; 824 switch (getRelocationInfo()) { 825 default: 826 llvm_unreachable("Unknown section kind"); 827 case Constant::GlobalRelocations: 828 Kind = SectionKind::getReadOnlyWithRel(); 829 break; 830 case Constant::LocalRelocation: 831 Kind = SectionKind::getReadOnlyWithRelLocal(); 832 break; 833 case Constant::NoRelocation: 834 switch (DL->getTypeAllocSize(getType())) { 835 case 4: 836 Kind = SectionKind::getMergeableConst4(); 837 break; 838 case 8: 839 Kind = SectionKind::getMergeableConst8(); 840 break; 841 case 16: 842 Kind = SectionKind::getMergeableConst16(); 843 break; 844 default: 845 Kind = SectionKind::getReadOnly(); 846 break; 847 } 848 } 849 return Kind; 850 } 851 852 MachineConstantPool::~MachineConstantPool() { 853 for (unsigned i = 0, e = Constants.size(); i != e; ++i) 854 if (Constants[i].isMachineConstantPoolEntry()) 855 delete Constants[i].Val.MachineCPVal; 856 for (DenseSet<MachineConstantPoolValue*>::iterator I = 857 MachineCPVsSharingEntries.begin(), E = MachineCPVsSharingEntries.end(); 858 I != E; ++I) 859 delete *I; 860 } 861 862 /// Test whether the given two constants can be allocated the same constant pool 863 /// entry. 864 static bool CanShareConstantPoolEntry(const Constant *A, const Constant *B, 865 const DataLayout &DL) { 866 // Handle the trivial case quickly. 867 if (A == B) return true; 868 869 // If they have the same type but weren't the same constant, quickly 870 // reject them. 871 if (A->getType() == B->getType()) return false; 872 873 // We can't handle structs or arrays. 874 if (isa<StructType>(A->getType()) || isa<ArrayType>(A->getType()) || 875 isa<StructType>(B->getType()) || isa<ArrayType>(B->getType())) 876 return false; 877 878 // For now, only support constants with the same size. 879 uint64_t StoreSize = DL.getTypeStoreSize(A->getType()); 880 if (StoreSize != DL.getTypeStoreSize(B->getType()) || StoreSize > 128) 881 return false; 882 883 Type *IntTy = IntegerType::get(A->getContext(), StoreSize*8); 884 885 // Try constant folding a bitcast of both instructions to an integer. If we 886 // get two identical ConstantInt's, then we are good to share them. We use 887 // the constant folding APIs to do this so that we get the benefit of 888 // DataLayout. 889 if (isa<PointerType>(A->getType())) 890 A = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy, 891 const_cast<Constant *>(A), DL); 892 else if (A->getType() != IntTy) 893 A = ConstantFoldInstOperands(Instruction::BitCast, IntTy, 894 const_cast<Constant *>(A), DL); 895 if (isa<PointerType>(B->getType())) 896 B = ConstantFoldInstOperands(Instruction::PtrToInt, IntTy, 897 const_cast<Constant *>(B), DL); 898 else if (B->getType() != IntTy) 899 B = ConstantFoldInstOperands(Instruction::BitCast, IntTy, 900 const_cast<Constant *>(B), DL); 901 902 return A == B; 903 } 904 905 /// Create a new entry in the constant pool or return an existing one. 906 /// User must specify the log2 of the minimum required alignment for the object. 907 unsigned MachineConstantPool::getConstantPoolIndex(const Constant *C, 908 unsigned Alignment) { 909 assert(Alignment && "Alignment must be specified!"); 910 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 911 912 // Check to see if we already have this constant. 913 // 914 // FIXME, this could be made much more efficient for large constant pools. 915 for (unsigned i = 0, e = Constants.size(); i != e; ++i) 916 if (!Constants[i].isMachineConstantPoolEntry() && 917 CanShareConstantPoolEntry(Constants[i].Val.ConstVal, C, DL)) { 918 if ((unsigned)Constants[i].getAlignment() < Alignment) 919 Constants[i].Alignment = Alignment; 920 return i; 921 } 922 923 Constants.push_back(MachineConstantPoolEntry(C, Alignment)); 924 return Constants.size()-1; 925 } 926 927 unsigned MachineConstantPool::getConstantPoolIndex(MachineConstantPoolValue *V, 928 unsigned Alignment) { 929 assert(Alignment && "Alignment must be specified!"); 930 if (Alignment > PoolAlignment) PoolAlignment = Alignment; 931 932 // Check to see if we already have this constant. 933 // 934 // FIXME, this could be made much more efficient for large constant pools. 935 int Idx = V->getExistingMachineCPValue(this, Alignment); 936 if (Idx != -1) { 937 MachineCPVsSharingEntries.insert(V); 938 return (unsigned)Idx; 939 } 940 941 Constants.push_back(MachineConstantPoolEntry(V, Alignment)); 942 return Constants.size()-1; 943 } 944 945 void MachineConstantPool::print(raw_ostream &OS) const { 946 if (Constants.empty()) return; 947 948 OS << "Constant Pool:\n"; 949 for (unsigned i = 0, e = Constants.size(); i != e; ++i) { 950 OS << " cp#" << i << ": "; 951 if (Constants[i].isMachineConstantPoolEntry()) 952 Constants[i].Val.MachineCPVal->print(OS); 953 else 954 Constants[i].Val.ConstVal->printAsOperand(OS, /*PrintType=*/false); 955 OS << ", align=" << Constants[i].getAlignment(); 956 OS << "\n"; 957 } 958 } 959 960 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 961 void MachineConstantPool::dump() const { print(dbgs()); } 962 #endif 963