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