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