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