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