1 //===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===// 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 // This pass is responsible for finalizing the functions frame layout, saving 11 // callee saved registers, and for emitting prolog & epilog code for the 12 // function. 13 // 14 // This pass must be run after register allocation. After this pass is 15 // executed, it is illegal to construct MO_FrameIndex operands. 16 // 17 // This pass provides an optional shrink wrapping variant of prolog/epilog 18 // insertion, enabled via --shrink-wrap. See ShrinkWrapping.cpp. 19 // 20 //===----------------------------------------------------------------------===// 21 22 #define DEBUG_TYPE "pei" 23 #include "PrologEpilogInserter.h" 24 #include "llvm/ADT/IndexedMap.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SmallSet.h" 27 #include "llvm/ADT/Statistic.h" 28 #include "llvm/CodeGen/MachineDominators.h" 29 #include "llvm/CodeGen/MachineFrameInfo.h" 30 #include "llvm/CodeGen/MachineInstr.h" 31 #include "llvm/CodeGen/MachineLoopInfo.h" 32 #include "llvm/CodeGen/MachineRegisterInfo.h" 33 #include "llvm/CodeGen/RegisterScavenging.h" 34 #include "llvm/IR/InlineAsm.h" 35 #include "llvm/Support/CommandLine.h" 36 #include "llvm/Support/Compiler.h" 37 #include "llvm/Support/Debug.h" 38 #include "llvm/Support/raw_ostream.h" 39 #include "llvm/Target/TargetFrameLowering.h" 40 #include "llvm/Target/TargetInstrInfo.h" 41 #include "llvm/Target/TargetMachine.h" 42 #include "llvm/Target/TargetRegisterInfo.h" 43 #include <climits> 44 45 using namespace llvm; 46 47 char PEI::ID = 0; 48 char &llvm::PrologEpilogCodeInserterID = PEI::ID; 49 50 static cl::opt<unsigned> 51 WarnStackSize("warn-stack-size", cl::Hidden, cl::init((unsigned)-1), 52 cl::desc("Warn for stack size bigger than the given" 53 " number")); 54 55 INITIALIZE_PASS_BEGIN(PEI, "prologepilog", 56 "Prologue/Epilogue Insertion", false, false) 57 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 58 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 59 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) 60 INITIALIZE_PASS_END(PEI, "prologepilog", 61 "Prologue/Epilogue Insertion & Frame Finalization", 62 false, false) 63 64 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged"); 65 STATISTIC(NumBytesStackSpace, 66 "Number of bytes used for stack in all functions"); 67 68 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract 69 /// frame indexes with appropriate references. 70 /// 71 bool PEI::runOnMachineFunction(MachineFunction &Fn) { 72 const Function* F = Fn.getFunction(); 73 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo(); 74 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering(); 75 76 assert(!Fn.getRegInfo().getNumVirtRegs() && "Regalloc must assign all vregs"); 77 78 RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL; 79 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn); 80 81 // Calculate the MaxCallFrameSize and AdjustsStack variables for the 82 // function's frame information. Also eliminates call frame pseudo 83 // instructions. 84 calculateCallsInformation(Fn); 85 86 // Allow the target machine to make some adjustments to the function 87 // e.g. UsedPhysRegs before calculateCalleeSavedRegisters. 88 TFI->processFunctionBeforeCalleeSavedScan(Fn, RS); 89 90 // Scan the function for modified callee saved registers and insert spill code 91 // for any callee saved registers that are modified. 92 calculateCalleeSavedRegisters(Fn); 93 94 // Determine placement of CSR spill/restore code: 95 // - With shrink wrapping, place spills and restores to tightly 96 // enclose regions in the Machine CFG of the function where 97 // they are used. 98 // - Without shink wrapping (default), place all spills in the 99 // entry block, all restores in return blocks. 100 placeCSRSpillsAndRestores(Fn); 101 102 // Add the code to save and restore the callee saved registers 103 if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, 104 Attribute::Naked)) 105 insertCSRSpillsAndRestores(Fn); 106 107 // Allow the target machine to make final modifications to the function 108 // before the frame layout is finalized. 109 TFI->processFunctionBeforeFrameFinalized(Fn, RS); 110 111 // Calculate actual frame offsets for all abstract stack objects... 112 calculateFrameObjectOffsets(Fn); 113 114 // Add prolog and epilog code to the function. This function is required 115 // to align the stack frame as necessary for any stack variables or 116 // called functions. Because of this, calculateCalleeSavedRegisters() 117 // must be called before this function in order to set the AdjustsStack 118 // and MaxCallFrameSize variables. 119 if (!F->getAttributes().hasAttribute(AttributeSet::FunctionIndex, 120 Attribute::Naked)) 121 insertPrologEpilogCode(Fn); 122 123 // Replace all MO_FrameIndex operands with physical register references 124 // and actual offsets. 125 // 126 replaceFrameIndices(Fn); 127 128 // If register scavenging is needed, as we've enabled doing it as a 129 // post-pass, scavenge the virtual registers that frame index elimiation 130 // inserted. 131 if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging) 132 scavengeFrameVirtualRegs(Fn); 133 134 // Clear any vregs created by virtual scavenging. 135 Fn.getRegInfo().clearVirtRegs(); 136 137 // Warn on stack size when we exceeds the given limit. 138 MachineFrameInfo *MFI = Fn.getFrameInfo(); 139 if (WarnStackSize.getNumOccurrences() > 0 && 140 WarnStackSize < MFI->getStackSize()) 141 errs() << "warning: Stack size limit exceeded (" << MFI->getStackSize() 142 << ") in " << Fn.getName() << ".\n"; 143 144 delete RS; 145 clearAllSets(); 146 return true; 147 } 148 149 /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack 150 /// variables for the function's frame information and eliminate call frame 151 /// pseudo instructions. 152 void PEI::calculateCallsInformation(MachineFunction &Fn) { 153 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo(); 154 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering(); 155 MachineFrameInfo *MFI = Fn.getFrameInfo(); 156 157 unsigned MaxCallFrameSize = 0; 158 bool AdjustsStack = MFI->adjustsStack(); 159 160 // Get the function call frame set-up and tear-down instruction opcode 161 int FrameSetupOpcode = TII.getCallFrameSetupOpcode(); 162 int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode(); 163 164 // Early exit for targets which have no call frame setup/destroy pseudo 165 // instructions. 166 if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1) 167 return; 168 169 std::vector<MachineBasicBlock::iterator> FrameSDOps; 170 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) 171 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) 172 if (I->getOpcode() == FrameSetupOpcode || 173 I->getOpcode() == FrameDestroyOpcode) { 174 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo" 175 " instructions should have a single immediate argument!"); 176 unsigned Size = I->getOperand(0).getImm(); 177 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size; 178 AdjustsStack = true; 179 FrameSDOps.push_back(I); 180 } else if (I->isInlineAsm()) { 181 // Some inline asm's need a stack frame, as indicated by operand 1. 182 unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 183 if (ExtraInfo & InlineAsm::Extra_IsAlignStack) 184 AdjustsStack = true; 185 } 186 187 MFI->setAdjustsStack(AdjustsStack); 188 MFI->setMaxCallFrameSize(MaxCallFrameSize); 189 190 for (std::vector<MachineBasicBlock::iterator>::iterator 191 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) { 192 MachineBasicBlock::iterator I = *i; 193 194 // If call frames are not being included as part of the stack frame, and 195 // the target doesn't indicate otherwise, remove the call frame pseudos 196 // here. The sub/add sp instruction pairs are still inserted, but we don't 197 // need to track the SP adjustment for frame index elimination. 198 if (TFI->canSimplifyCallFramePseudos(Fn)) 199 TFI->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I); 200 } 201 } 202 203 204 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved 205 /// registers. 206 void PEI::calculateCalleeSavedRegisters(MachineFunction &F) { 207 const TargetRegisterInfo *RegInfo = F.getTarget().getRegisterInfo(); 208 const TargetFrameLowering *TFI = F.getTarget().getFrameLowering(); 209 MachineFrameInfo *MFI = F.getFrameInfo(); 210 211 // Get the callee saved register list... 212 const uint16_t *CSRegs = RegInfo->getCalleeSavedRegs(&F); 213 214 // These are used to keep track the callee-save area. Initialize them. 215 MinCSFrameIndex = INT_MAX; 216 MaxCSFrameIndex = 0; 217 218 // Early exit for targets which have no callee saved registers. 219 if (CSRegs == 0 || CSRegs[0] == 0) 220 return; 221 222 // In Naked functions we aren't going to save any registers. 223 if (F.getFunction()->getAttributes().hasAttribute(AttributeSet::FunctionIndex, 224 Attribute::Naked)) 225 return; 226 227 std::vector<CalleeSavedInfo> CSI; 228 for (unsigned i = 0; CSRegs[i]; ++i) { 229 unsigned Reg = CSRegs[i]; 230 if (F.getRegInfo().isPhysRegUsed(Reg)) { 231 // If the reg is modified, save it! 232 CSI.push_back(CalleeSavedInfo(Reg)); 233 } 234 } 235 236 if (CSI.empty()) 237 return; // Early exit if no callee saved registers are modified! 238 239 unsigned NumFixedSpillSlots; 240 const TargetFrameLowering::SpillSlot *FixedSpillSlots = 241 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots); 242 243 // Now that we know which registers need to be saved and restored, allocate 244 // stack slots for them. 245 for (std::vector<CalleeSavedInfo>::iterator 246 I = CSI.begin(), E = CSI.end(); I != E; ++I) { 247 unsigned Reg = I->getReg(); 248 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg); 249 250 int FrameIdx; 251 if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) { 252 I->setFrameIdx(FrameIdx); 253 continue; 254 } 255 256 // Check to see if this physreg must be spilled to a particular stack slot 257 // on this target. 258 const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots; 259 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots && 260 FixedSlot->Reg != Reg) 261 ++FixedSlot; 262 263 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) { 264 // Nope, just spill it anywhere convenient. 265 unsigned Align = RC->getAlignment(); 266 unsigned StackAlign = TFI->getStackAlignment(); 267 268 // We may not be able to satisfy the desired alignment specification of 269 // the TargetRegisterClass if the stack alignment is smaller. Use the 270 // min. 271 Align = std::min(Align, StackAlign); 272 FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true); 273 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx; 274 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx; 275 } else { 276 // Spill it to the stack where we must. 277 FrameIdx = MFI->CreateFixedObject(RC->getSize(), FixedSlot->Offset, true); 278 } 279 280 I->setFrameIdx(FrameIdx); 281 } 282 283 MFI->setCalleeSavedInfo(CSI); 284 } 285 286 /// insertCSRSpillsAndRestores - Insert spill and restore code for 287 /// callee saved registers used in the function, handling shrink wrapping. 288 /// 289 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) { 290 // Get callee saved register information. 291 MachineFrameInfo *MFI = Fn.getFrameInfo(); 292 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo(); 293 294 MFI->setCalleeSavedInfoValid(true); 295 296 // Early exit if no callee saved registers are modified! 297 if (CSI.empty()) 298 return; 299 300 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo(); 301 const TargetFrameLowering *TFI = Fn.getTarget().getFrameLowering(); 302 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo(); 303 MachineBasicBlock::iterator I; 304 305 if (!ShrinkWrapThisFunction) { 306 // Spill using target interface. 307 I = EntryBlock->begin(); 308 if (!TFI->spillCalleeSavedRegisters(*EntryBlock, I, CSI, TRI)) { 309 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 310 // Add the callee-saved register as live-in. 311 // It's killed at the spill. 312 EntryBlock->addLiveIn(CSI[i].getReg()); 313 314 // Insert the spill to the stack frame. 315 unsigned Reg = CSI[i].getReg(); 316 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg); 317 TII.storeRegToStackSlot(*EntryBlock, I, Reg, true, 318 CSI[i].getFrameIdx(), RC, TRI); 319 } 320 } 321 322 // Restore using target interface. 323 for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) { 324 MachineBasicBlock* MBB = ReturnBlocks[ri]; 325 I = MBB->end(); --I; 326 327 // Skip over all terminator instructions, which are part of the return 328 // sequence. 329 MachineBasicBlock::iterator I2 = I; 330 while (I2 != MBB->begin() && (--I2)->isTerminator()) 331 I = I2; 332 333 bool AtStart = I == MBB->begin(); 334 MachineBasicBlock::iterator BeforeI = I; 335 if (!AtStart) 336 --BeforeI; 337 338 // Restore all registers immediately before the return and any 339 // terminators that precede it. 340 if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) { 341 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 342 unsigned Reg = CSI[i].getReg(); 343 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg); 344 TII.loadRegFromStackSlot(*MBB, I, Reg, 345 CSI[i].getFrameIdx(), 346 RC, TRI); 347 assert(I != MBB->begin() && 348 "loadRegFromStackSlot didn't insert any code!"); 349 // Insert in reverse order. loadRegFromStackSlot can insert 350 // multiple instructions. 351 if (AtStart) 352 I = MBB->begin(); 353 else { 354 I = BeforeI; 355 ++I; 356 } 357 } 358 } 359 } 360 return; 361 } 362 363 // Insert spills. 364 std::vector<CalleeSavedInfo> blockCSI; 365 for (CSRegBlockMap::iterator BI = CSRSave.begin(), 366 BE = CSRSave.end(); BI != BE; ++BI) { 367 MachineBasicBlock* MBB = BI->first; 368 CSRegSet save = BI->second; 369 370 if (save.empty()) 371 continue; 372 373 blockCSI.clear(); 374 for (CSRegSet::iterator RI = save.begin(), 375 RE = save.end(); RI != RE; ++RI) { 376 blockCSI.push_back(CSI[*RI]); 377 } 378 assert(blockCSI.size() > 0 && 379 "Could not collect callee saved register info"); 380 381 I = MBB->begin(); 382 383 // When shrink wrapping, use stack slot stores/loads. 384 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) { 385 // Add the callee-saved register as live-in. 386 // It's killed at the spill. 387 MBB->addLiveIn(blockCSI[i].getReg()); 388 389 // Insert the spill to the stack frame. 390 unsigned Reg = blockCSI[i].getReg(); 391 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg); 392 TII.storeRegToStackSlot(*MBB, I, Reg, 393 true, 394 blockCSI[i].getFrameIdx(), 395 RC, TRI); 396 } 397 } 398 399 for (CSRegBlockMap::iterator BI = CSRRestore.begin(), 400 BE = CSRRestore.end(); BI != BE; ++BI) { 401 MachineBasicBlock* MBB = BI->first; 402 CSRegSet restore = BI->second; 403 404 if (restore.empty()) 405 continue; 406 407 blockCSI.clear(); 408 for (CSRegSet::iterator RI = restore.begin(), 409 RE = restore.end(); RI != RE; ++RI) { 410 blockCSI.push_back(CSI[*RI]); 411 } 412 assert(blockCSI.size() > 0 && 413 "Could not find callee saved register info"); 414 415 // If MBB is empty and needs restores, insert at the _beginning_. 416 if (MBB->empty()) { 417 I = MBB->begin(); 418 } else { 419 I = MBB->end(); 420 --I; 421 422 // Skip over all terminator instructions, which are part of the 423 // return sequence. 424 if (! I->isTerminator()) { 425 ++I; 426 } else { 427 MachineBasicBlock::iterator I2 = I; 428 while (I2 != MBB->begin() && (--I2)->isTerminator()) 429 I = I2; 430 } 431 } 432 433 bool AtStart = I == MBB->begin(); 434 MachineBasicBlock::iterator BeforeI = I; 435 if (!AtStart) 436 --BeforeI; 437 438 // Restore all registers immediately before the return and any 439 // terminators that precede it. 440 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) { 441 unsigned Reg = blockCSI[i].getReg(); 442 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg); 443 TII.loadRegFromStackSlot(*MBB, I, Reg, 444 blockCSI[i].getFrameIdx(), 445 RC, TRI); 446 assert(I != MBB->begin() && 447 "loadRegFromStackSlot didn't insert any code!"); 448 // Insert in reverse order. loadRegFromStackSlot can insert 449 // multiple instructions. 450 if (AtStart) 451 I = MBB->begin(); 452 else { 453 I = BeforeI; 454 ++I; 455 } 456 } 457 } 458 } 459 460 /// AdjustStackOffset - Helper function used to adjust the stack frame offset. 461 static inline void 462 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx, 463 bool StackGrowsDown, int64_t &Offset, 464 unsigned &MaxAlign) { 465 // If the stack grows down, add the object size to find the lowest address. 466 if (StackGrowsDown) 467 Offset += MFI->getObjectSize(FrameIdx); 468 469 unsigned Align = MFI->getObjectAlignment(FrameIdx); 470 471 // If the alignment of this object is greater than that of the stack, then 472 // increase the stack alignment to match. 473 MaxAlign = std::max(MaxAlign, Align); 474 475 // Adjust to alignment boundary. 476 Offset = (Offset + Align - 1) / Align * Align; 477 478 if (StackGrowsDown) { 479 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n"); 480 MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset 481 } else { 482 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n"); 483 MFI->setObjectOffset(FrameIdx, Offset); 484 Offset += MFI->getObjectSize(FrameIdx); 485 } 486 } 487 488 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the 489 /// abstract stack objects. 490 /// 491 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) { 492 const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering(); 493 494 bool StackGrowsDown = 495 TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown; 496 497 // Loop over all of the stack objects, assigning sequential addresses... 498 MachineFrameInfo *MFI = Fn.getFrameInfo(); 499 500 // Start at the beginning of the local area. 501 // The Offset is the distance from the stack top in the direction 502 // of stack growth -- so it's always nonnegative. 503 int LocalAreaOffset = TFI.getOffsetOfLocalArea(); 504 if (StackGrowsDown) 505 LocalAreaOffset = -LocalAreaOffset; 506 assert(LocalAreaOffset >= 0 507 && "Local area offset should be in direction of stack growth"); 508 int64_t Offset = LocalAreaOffset; 509 510 // If there are fixed sized objects that are preallocated in the local area, 511 // non-fixed objects can't be allocated right at the start of local area. 512 // We currently don't support filling in holes in between fixed sized 513 // objects, so we adjust 'Offset' to point to the end of last fixed sized 514 // preallocated object. 515 for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) { 516 int64_t FixedOff; 517 if (StackGrowsDown) { 518 // The maximum distance from the stack pointer is at lower address of 519 // the object -- which is given by offset. For down growing stack 520 // the offset is negative, so we negate the offset to get the distance. 521 FixedOff = -MFI->getObjectOffset(i); 522 } else { 523 // The maximum distance from the start pointer is at the upper 524 // address of the object. 525 FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i); 526 } 527 if (FixedOff > Offset) Offset = FixedOff; 528 } 529 530 // First assign frame offsets to stack objects that are used to spill 531 // callee saved registers. 532 if (StackGrowsDown) { 533 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) { 534 // If the stack grows down, we need to add the size to find the lowest 535 // address of the object. 536 Offset += MFI->getObjectSize(i); 537 538 unsigned Align = MFI->getObjectAlignment(i); 539 // Adjust to alignment boundary 540 Offset = (Offset+Align-1)/Align*Align; 541 542 MFI->setObjectOffset(i, -Offset); // Set the computed offset 543 } 544 } else { 545 int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex; 546 for (int i = MaxCSFI; i >= MinCSFI ; --i) { 547 unsigned Align = MFI->getObjectAlignment(i); 548 // Adjust to alignment boundary 549 Offset = (Offset+Align-1)/Align*Align; 550 551 MFI->setObjectOffset(i, Offset); 552 Offset += MFI->getObjectSize(i); 553 } 554 } 555 556 unsigned MaxAlign = MFI->getMaxAlignment(); 557 558 // Make sure the special register scavenging spill slot is closest to the 559 // frame pointer if a frame pointer is required. 560 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo(); 561 if (RS && TFI.hasFP(Fn) && RegInfo->useFPForScavengingIndex(Fn) && 562 !RegInfo->needsStackRealignment(Fn)) { 563 SmallVector<int, 2> SFIs; 564 RS->getScavengingFrameIndices(SFIs); 565 for (SmallVector<int, 2>::iterator I = SFIs.begin(), 566 IE = SFIs.end(); I != IE; ++I) 567 AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign); 568 } 569 570 // FIXME: Once this is working, then enable flag will change to a target 571 // check for whether the frame is large enough to want to use virtual 572 // frame index registers. Functions which don't want/need this optimization 573 // will continue to use the existing code path. 574 if (MFI->getUseLocalStackAllocationBlock()) { 575 unsigned Align = MFI->getLocalFrameMaxAlign(); 576 577 // Adjust to alignment boundary. 578 Offset = (Offset + Align - 1) / Align * Align; 579 580 DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n"); 581 582 // Resolve offsets for objects in the local block. 583 for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) { 584 std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i); 585 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second; 586 DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" << 587 FIOffset << "]\n"); 588 MFI->setObjectOffset(Entry.first, FIOffset); 589 } 590 // Allocate the local block 591 Offset += MFI->getLocalFrameSize(); 592 593 MaxAlign = std::max(Align, MaxAlign); 594 } 595 596 // Make sure that the stack protector comes before the local variables on the 597 // stack. 598 SmallSet<int, 16> LargeStackObjs; 599 if (MFI->getStackProtectorIndex() >= 0) { 600 AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown, 601 Offset, MaxAlign); 602 603 // Assign large stack objects first. 604 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) { 605 if (MFI->isObjectPreAllocated(i) && 606 MFI->getUseLocalStackAllocationBlock()) 607 continue; 608 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex) 609 continue; 610 if (RS && RS->isScavengingFrameIndex((int)i)) 611 continue; 612 if (MFI->isDeadObjectIndex(i)) 613 continue; 614 if (MFI->getStackProtectorIndex() == (int)i) 615 continue; 616 if (!MFI->MayNeedStackProtector(i)) 617 continue; 618 619 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign); 620 LargeStackObjs.insert(i); 621 } 622 } 623 624 // Then assign frame offsets to stack objects that are not used to spill 625 // callee saved registers. 626 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) { 627 if (MFI->isObjectPreAllocated(i) && 628 MFI->getUseLocalStackAllocationBlock()) 629 continue; 630 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex) 631 continue; 632 if (RS && RS->isScavengingFrameIndex((int)i)) 633 continue; 634 if (MFI->isDeadObjectIndex(i)) 635 continue; 636 if (MFI->getStackProtectorIndex() == (int)i) 637 continue; 638 if (LargeStackObjs.count(i)) 639 continue; 640 641 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign); 642 } 643 644 // Make sure the special register scavenging spill slot is closest to the 645 // stack pointer. 646 if (RS && (!TFI.hasFP(Fn) || RegInfo->needsStackRealignment(Fn) || 647 !RegInfo->useFPForScavengingIndex(Fn))) { 648 SmallVector<int, 2> SFIs; 649 RS->getScavengingFrameIndices(SFIs); 650 for (SmallVector<int, 2>::iterator I = SFIs.begin(), 651 IE = SFIs.end(); I != IE; ++I) 652 AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign); 653 } 654 655 if (!TFI.targetHandlesStackFrameRounding()) { 656 // If we have reserved argument space for call sites in the function 657 // immediately on entry to the current function, count it as part of the 658 // overall stack size. 659 if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn)) 660 Offset += MFI->getMaxCallFrameSize(); 661 662 // Round up the size to a multiple of the alignment. If the function has 663 // any calls or alloca's, align to the target's StackAlignment value to 664 // ensure that the callee's frame or the alloca data is suitably aligned; 665 // otherwise, for leaf functions, align to the TransientStackAlignment 666 // value. 667 unsigned StackAlign; 668 if (MFI->adjustsStack() || MFI->hasVarSizedObjects() || 669 (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0)) 670 StackAlign = TFI.getStackAlignment(); 671 else 672 StackAlign = TFI.getTransientStackAlignment(); 673 674 // If the frame pointer is eliminated, all frame offsets will be relative to 675 // SP not FP. Align to MaxAlign so this works. 676 StackAlign = std::max(StackAlign, MaxAlign); 677 unsigned AlignMask = StackAlign - 1; 678 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask); 679 } 680 681 // Update frame info to pretend that this is part of the stack... 682 int64_t StackSize = Offset - LocalAreaOffset; 683 MFI->setStackSize(StackSize); 684 NumBytesStackSpace += StackSize; 685 } 686 687 /// insertPrologEpilogCode - Scan the function for modified callee saved 688 /// registers, insert spill code for these callee saved registers, then add 689 /// prolog and epilog code to the function. 690 /// 691 void PEI::insertPrologEpilogCode(MachineFunction &Fn) { 692 const TargetFrameLowering &TFI = *Fn.getTarget().getFrameLowering(); 693 694 // Add prologue to the function... 695 TFI.emitPrologue(Fn); 696 697 // Add epilogue to restore the callee-save registers in each exiting block 698 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) { 699 // If last instruction is a return instruction, add an epilogue 700 if (!I->empty() && I->back().isReturn()) 701 TFI.emitEpilogue(Fn, *I); 702 } 703 704 // Emit additional code that is required to support segmented stacks, if 705 // we've been asked for it. This, when linked with a runtime with support 706 // for segmented stacks (libgcc is one), will result in allocating stack 707 // space in small chunks instead of one large contiguous block. 708 if (Fn.getTarget().Options.EnableSegmentedStacks) 709 TFI.adjustForSegmentedStacks(Fn); 710 711 // Emit additional code that is required to explicitly handle the stack in 712 // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The 713 // approach is rather similar to that of Segmented Stacks, but it uses a 714 // different conditional check and another BIF for allocating more stack 715 // space. 716 if (Fn.getFunction()->getCallingConv() == CallingConv::HiPE) 717 TFI.adjustForHiPEPrologue(Fn); 718 } 719 720 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical 721 /// register references and actual offsets. 722 /// 723 void PEI::replaceFrameIndices(MachineFunction &Fn) { 724 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do? 725 726 const TargetMachine &TM = Fn.getTarget(); 727 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!"); 728 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo(); 729 const TargetRegisterInfo &TRI = *TM.getRegisterInfo(); 730 const TargetFrameLowering *TFI = TM.getFrameLowering(); 731 bool StackGrowsDown = 732 TFI->getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown; 733 int FrameSetupOpcode = TII.getCallFrameSetupOpcode(); 734 int FrameDestroyOpcode = TII.getCallFrameDestroyOpcode(); 735 736 for (MachineFunction::iterator BB = Fn.begin(), 737 E = Fn.end(); BB != E; ++BB) { 738 #ifndef NDEBUG 739 int SPAdjCount = 0; // frame setup / destroy count. 740 #endif 741 int SPAdj = 0; // SP offset due to call frame setup / destroy. 742 if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB); 743 744 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) { 745 746 if (I->getOpcode() == FrameSetupOpcode || 747 I->getOpcode() == FrameDestroyOpcode) { 748 #ifndef NDEBUG 749 // Track whether we see even pairs of them 750 SPAdjCount += I->getOpcode() == FrameSetupOpcode ? 1 : -1; 751 #endif 752 // Remember how much SP has been adjusted to create the call 753 // frame. 754 int Size = I->getOperand(0).getImm(); 755 756 if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) || 757 (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode)) 758 Size = -Size; 759 760 SPAdj += Size; 761 762 MachineBasicBlock::iterator PrevI = BB->end(); 763 if (I != BB->begin()) PrevI = prior(I); 764 TFI->eliminateCallFramePseudoInstr(Fn, *BB, I); 765 766 // Visit the instructions created by eliminateCallFramePseudoInstr(). 767 if (PrevI == BB->end()) 768 I = BB->begin(); // The replaced instr was the first in the block. 769 else 770 I = llvm::next(PrevI); 771 continue; 772 } 773 774 MachineInstr *MI = I; 775 bool DoIncr = true; 776 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 777 if (!MI->getOperand(i).isFI()) 778 continue; 779 780 // Some instructions (e.g. inline asm instructions) can have 781 // multiple frame indices and/or cause eliminateFrameIndex 782 // to insert more than one instruction. We need the register 783 // scavenger to go through all of these instructions so that 784 // it can update its register information. We keep the 785 // iterator at the point before insertion so that we can 786 // revisit them in full. 787 bool AtBeginning = (I == BB->begin()); 788 if (!AtBeginning) --I; 789 790 // If this instruction has a FrameIndex operand, we need to 791 // use that target machine register info object to eliminate 792 // it. 793 TRI.eliminateFrameIndex(MI, SPAdj, i, 794 FrameIndexVirtualScavenging ? NULL : RS); 795 796 // Reset the iterator if we were at the beginning of the BB. 797 if (AtBeginning) { 798 I = BB->begin(); 799 DoIncr = false; 800 } 801 802 MI = 0; 803 break; 804 } 805 806 if (DoIncr && I != BB->end()) ++I; 807 808 // Update register states. 809 if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI); 810 } 811 812 // If we have evenly matched pairs of frame setup / destroy instructions, 813 // make sure the adjustments come out to zero. If we don't have matched 814 // pairs, we can't be sure the missing bit isn't in another basic block 815 // due to a custom inserter playing tricks, so just asserting SPAdj==0 816 // isn't sufficient. See tMOVCC on Thumb1, for example. 817 assert((SPAdjCount || SPAdj == 0) && 818 "Unbalanced call frame setup / destroy pairs?"); 819 } 820 } 821 822 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers 823 /// with physical registers. Use the register scavenger to find an 824 /// appropriate register to use. 825 /// 826 /// FIXME: Iterating over the instruction stream is unnecessary. We can simply 827 /// iterate over the vreg use list, which at this point only contains machine 828 /// operands for which eliminateFrameIndex need a new scratch reg. 829 void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) { 830 // Run through the instructions and find any virtual registers. 831 for (MachineFunction::iterator BB = Fn.begin(), 832 E = Fn.end(); BB != E; ++BB) { 833 RS->enterBasicBlock(BB); 834 835 int SPAdj = 0; 836 837 // The instruction stream may change in the loop, so check BB->end() 838 // directly. 839 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) { 840 // We might end up here again with a NULL iterator if we scavenged a 841 // register for which we inserted spill code for definition by what was 842 // originally the first instruction in BB. 843 if (I == MachineBasicBlock::iterator(NULL)) 844 I = BB->begin(); 845 846 MachineInstr *MI = I; 847 MachineBasicBlock::iterator J = llvm::next(I); 848 MachineBasicBlock::iterator P = I == BB->begin() ? 849 MachineBasicBlock::iterator(NULL) : llvm::prior(I); 850 851 // RS should process this instruction before we might scavenge at this 852 // location. This is because we might be replacing a virtual register 853 // defined by this instruction, and if so, registers killed by this 854 // instruction are available, and defined registers are not. 855 RS->forward(I); 856 857 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 858 if (MI->getOperand(i).isReg()) { 859 MachineOperand &MO = MI->getOperand(i); 860 unsigned Reg = MO.getReg(); 861 if (Reg == 0) 862 continue; 863 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 864 continue; 865 866 // When we first encounter a new virtual register, it 867 // must be a definition. 868 assert(MI->getOperand(i).isDef() && 869 "frame index virtual missing def!"); 870 // Scavenge a new scratch register 871 const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg); 872 unsigned ScratchReg = RS->scavengeRegister(RC, J, SPAdj); 873 874 ++NumScavengedRegs; 875 876 // Replace this reference to the virtual register with the 877 // scratch register. 878 assert (ScratchReg && "Missing scratch register!"); 879 Fn.getRegInfo().replaceRegWith(Reg, ScratchReg); 880 881 // Because this instruction was processed by the RS before this 882 // register was allocated, make sure that the RS now records the 883 // register as being used. 884 RS->setUsed(ScratchReg); 885 } 886 } 887 888 // If the scavenger needed to use one of its spill slots, the 889 // spill code will have been inserted in between I and J. This is a 890 // problem because we need the spill code before I: Move I to just 891 // prior to J. 892 if (I != llvm::prior(J)) { 893 BB->splice(J, BB, I); 894 895 // Before we move I, we need to prepare the RS to visit I again. 896 // Specifically, RS will assert if it sees uses of registers that 897 // it believes are undefined. Because we have already processed 898 // register kills in I, when it visits I again, it will believe that 899 // those registers are undefined. To avoid this situation, unprocess 900 // the instruction I. 901 assert(RS->getCurrentPosition() == I && 902 "The register scavenger has an unexpected position"); 903 I = P; 904 RS->unprocess(P); 905 } else 906 ++I; 907 } 908 } 909 } 910