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