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