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 #include "PrologEpilogInserter.h" 23 #include "llvm/CodeGen/MachineDominators.h" 24 #include "llvm/CodeGen/MachineLoopInfo.h" 25 #include "llvm/CodeGen/MachineInstr.h" 26 #include "llvm/CodeGen/MachineFrameInfo.h" 27 #include "llvm/CodeGen/MachineModuleInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/RegisterScavenging.h" 30 #include "llvm/Target/TargetMachine.h" 31 #include "llvm/Target/TargetRegisterInfo.h" 32 #include "llvm/Target/TargetFrameInfo.h" 33 #include "llvm/Target/TargetInstrInfo.h" 34 #include "llvm/Support/Compiler.h" 35 #include "llvm/ADT/STLExtras.h" 36 #include <climits> 37 38 using namespace llvm; 39 40 char PEI::ID = 0; 41 42 static RegisterPass<PEI> 43 X("prologepilog", "Prologue/Epilogue Insertion"); 44 45 /// createPrologEpilogCodeInserter - This function returns a pass that inserts 46 /// prolog and epilog code, and eliminates abstract frame references. 47 /// 48 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); } 49 50 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract 51 /// frame indexes with appropriate references. 52 /// 53 bool PEI::runOnMachineFunction(MachineFunction &Fn) { 54 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo(); 55 RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL; 56 57 // Get MachineModuleInfo so that we can track the construction of the 58 // frame. 59 if (MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>()) 60 Fn.getFrameInfo()->setMachineModuleInfo(MMI); 61 62 // Allow the target machine to make some adjustments to the function 63 // e.g. UsedPhysRegs before calculateCalleeSavedRegisters. 64 TRI->processFunctionBeforeCalleeSavedScan(Fn, RS); 65 66 // Scan the function for modified callee saved registers and insert spill 67 // code for any callee saved registers that are modified. Also calculate 68 // the MaxCallFrameSize and HasCalls variables for the function's frame 69 // information and eliminates call frame pseudo instructions. 70 calculateCalleeSavedRegisters(Fn); 71 72 // Determine placement of CSR spill/restore code: 73 // - with shrink wrapping, place spills and restores to tightly 74 // enclose regions in the Machine CFG of the function where 75 // they are used. Without shrink wrapping 76 // - default (no shrink wrapping), place all spills in the 77 // entry block, all restores in return blocks. 78 placeCSRSpillsAndRestores(Fn); 79 80 // Add the code to save and restore the callee saved registers 81 insertCSRSpillsAndRestores(Fn); 82 83 // Allow the target machine to make final modifications to the function 84 // before the frame layout is finalized. 85 TRI->processFunctionBeforeFrameFinalized(Fn); 86 87 // Calculate actual frame offsets for all abstract stack objects... 88 calculateFrameObjectOffsets(Fn); 89 90 // Add prolog and epilog code to the function. This function is required 91 // to align the stack frame as necessary for any stack variables or 92 // called functions. Because of this, calculateCalleeSavedRegisters 93 // must be called before this function in order to set the HasCalls 94 // and MaxCallFrameSize variables. 95 insertPrologEpilogCode(Fn); 96 97 // Replace all MO_FrameIndex operands with physical register references 98 // and actual offsets. 99 // 100 replaceFrameIndices(Fn); 101 102 delete RS; 103 clearAllSets(); 104 return true; 105 } 106 107 #if 0 108 void PEI::getAnalysisUsage(AnalysisUsage &AU) const { 109 AU.setPreservesCFG(); 110 if (ShrinkWrapping || ShrinkWrapFunc != "") { 111 AU.addRequired<MachineLoopInfo>(); 112 AU.addRequired<MachineDominatorTree>(); 113 } 114 AU.addPreserved<MachineLoopInfo>(); 115 AU.addPreserved<MachineDominatorTree>(); 116 MachineFunctionPass::getAnalysisUsage(AU); 117 } 118 #endif 119 120 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved 121 /// registers. Also calculate the MaxCallFrameSize and HasCalls variables for 122 /// the function's frame information and eliminates call frame pseudo 123 /// instructions. 124 /// 125 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) { 126 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo(); 127 const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo(); 128 129 // Get the callee saved register list... 130 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(&Fn); 131 132 // Get the function call frame set-up and tear-down instruction opcode 133 int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode(); 134 int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode(); 135 136 // These are used to keep track the callee-save area. Initialize them. 137 MinCSFrameIndex = INT_MAX; 138 MaxCSFrameIndex = 0; 139 140 // Early exit for targets which have no callee saved registers and no call 141 // frame setup/destroy pseudo instructions. 142 if ((CSRegs == 0 || CSRegs[0] == 0) && 143 FrameSetupOpcode == -1 && FrameDestroyOpcode == -1) 144 return; 145 146 unsigned MaxCallFrameSize = 0; 147 bool HasCalls = false; 148 149 std::vector<MachineBasicBlock::iterator> FrameSDOps; 150 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) 151 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) 152 if (I->getOpcode() == FrameSetupOpcode || 153 I->getOpcode() == FrameDestroyOpcode) { 154 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo" 155 " instructions should have a single immediate argument!"); 156 unsigned Size = I->getOperand(0).getImm(); 157 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size; 158 HasCalls = true; 159 FrameSDOps.push_back(I); 160 } 161 162 MachineFrameInfo *FFI = Fn.getFrameInfo(); 163 FFI->setHasCalls(HasCalls); 164 FFI->setMaxCallFrameSize(MaxCallFrameSize); 165 166 for (std::vector<MachineBasicBlock::iterator>::iterator 167 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) { 168 MachineBasicBlock::iterator I = *i; 169 170 // If call frames are not being included as part of the stack frame, and 171 // there is no dynamic allocation (therefore referencing frame slots off 172 // sp), leave the pseudo ops alone. We'll eliminate them later. 173 if (RegInfo->hasReservedCallFrame(Fn) || RegInfo->hasFP(Fn)) 174 RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I); 175 } 176 177 // Now figure out which *callee saved* registers are modified by the current 178 // function, thus needing to be saved and restored in the prolog/epilog. 179 const TargetRegisterClass * const *CSRegClasses = 180 RegInfo->getCalleeSavedRegClasses(&Fn); 181 182 std::vector<CalleeSavedInfo> CSI; 183 for (unsigned i = 0; CSRegs[i]; ++i) { 184 unsigned Reg = CSRegs[i]; 185 if (Fn.getRegInfo().isPhysRegUsed(Reg)) { 186 // If the reg is modified, save it! 187 CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i])); 188 } else { 189 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg); 190 *AliasSet; ++AliasSet) { // Check alias registers too. 191 if (Fn.getRegInfo().isPhysRegUsed(*AliasSet)) { 192 CSI.push_back(CalleeSavedInfo(Reg, CSRegClasses[i])); 193 break; 194 } 195 } 196 } 197 } 198 199 if (CSI.empty()) 200 return; // Early exit if no callee saved registers are modified! 201 202 unsigned NumFixedSpillSlots; 203 const std::pair<unsigned,int> *FixedSpillSlots = 204 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots); 205 206 // Now that we know which registers need to be saved and restored, allocate 207 // stack slots for them. 208 for (std::vector<CalleeSavedInfo>::iterator 209 I = CSI.begin(), E = CSI.end(); I != E; ++I) { 210 unsigned Reg = I->getReg(); 211 const TargetRegisterClass *RC = I->getRegClass(); 212 213 // Check to see if this physreg must be spilled to a particular stack slot 214 // on this target. 215 const std::pair<unsigned,int> *FixedSlot = FixedSpillSlots; 216 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots && 217 FixedSlot->first != Reg) 218 ++FixedSlot; 219 220 int FrameIdx; 221 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) { 222 // Nope, just spill it anywhere convenient. 223 unsigned Align = RC->getAlignment(); 224 unsigned StackAlign = TFI->getStackAlignment(); 225 226 // We may not be able to satisfy the desired alignment specification of 227 // the TargetRegisterClass if the stack alignment is smaller. Use the 228 // min. 229 Align = std::min(Align, StackAlign); 230 FrameIdx = FFI->CreateStackObject(RC->getSize(), Align); 231 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx; 232 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx; 233 } else { 234 // Spill it to the stack where we must. 235 FrameIdx = FFI->CreateFixedObject(RC->getSize(), FixedSlot->second); 236 } 237 238 I->setFrameIdx(FrameIdx); 239 } 240 241 FFI->setCalleeSavedInfo(CSI); 242 } 243 244 /// insertCSRSpillsAndRestores - Insert spill and restore code for 245 /// callee saved registers used in the function, handling shrink wrapping. 246 /// 247 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) { 248 // Get callee saved register information. 249 MachineFrameInfo *FFI = Fn.getFrameInfo(); 250 const std::vector<CalleeSavedInfo> &CSI = FFI->getCalleeSavedInfo(); 251 252 // Early exit if no callee saved registers are modified! 253 if (CSI.empty()) 254 return; 255 256 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo(); 257 MachineBasicBlock::iterator I; 258 259 if (! ShrinkWrapThisFunction) { 260 // Spill using target interface. 261 I = EntryBlock->begin(); 262 if (!TII.spillCalleeSavedRegisters(*EntryBlock, I, CSI)) { 263 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 264 // Add the callee-saved register as live-in. 265 // It's killed at the spill. 266 EntryBlock->addLiveIn(CSI[i].getReg()); 267 268 // Insert the spill to the stack frame. 269 TII.storeRegToStackSlot(*EntryBlock, I, CSI[i].getReg(), true, 270 CSI[i].getFrameIdx(), CSI[i].getRegClass()); 271 } 272 } 273 274 // Restore using target interface. 275 for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) { 276 MachineBasicBlock* MBB = ReturnBlocks[ri]; 277 I = MBB->end(); --I; 278 279 // Skip over all terminator instructions, which are part of the return 280 // sequence. 281 MachineBasicBlock::iterator I2 = I; 282 while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator()) 283 I = I2; 284 285 bool AtStart = I == MBB->begin(); 286 MachineBasicBlock::iterator BeforeI = I; 287 if (!AtStart) 288 --BeforeI; 289 290 // Restore all registers immediately before the return and any 291 // terminators that preceed it. 292 if (!TII.restoreCalleeSavedRegisters(*MBB, I, CSI)) { 293 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 294 TII.loadRegFromStackSlot(*MBB, I, CSI[i].getReg(), 295 CSI[i].getFrameIdx(), 296 CSI[i].getRegClass()); 297 assert(I != MBB->begin() && 298 "loadRegFromStackSlot didn't insert any code!"); 299 // Insert in reverse order. loadRegFromStackSlot can insert 300 // multiple instructions. 301 if (AtStart) 302 I = MBB->begin(); 303 else { 304 I = BeforeI; 305 ++I; 306 } 307 } 308 } 309 } 310 return; 311 } 312 313 // Insert spills. 314 std::vector<CalleeSavedInfo> blockCSI; 315 for (CSRegBlockMap::iterator BI = CSRSave.begin(), 316 BE = CSRSave.end(); BI != BE; ++BI) { 317 MachineBasicBlock* MBB = BI->first; 318 CSRegSet save = BI->second; 319 320 if (save.empty()) 321 continue; 322 323 blockCSI.clear(); 324 for (CSRegSet::iterator RI = save.begin(), 325 RE = save.end(); RI != RE; ++RI) { 326 blockCSI.push_back(CSI[*RI]); 327 } 328 assert(blockCSI.size() > 0 && 329 "Could not collect callee saved register info"); 330 331 I = MBB->begin(); 332 333 // When shrink wrapping, use stack slot stores/loads. 334 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) { 335 // Add the callee-saved register as live-in. 336 // It's killed at the spill. 337 MBB->addLiveIn(blockCSI[i].getReg()); 338 339 // Insert the spill to the stack frame. 340 TII.storeRegToStackSlot(*MBB, I, blockCSI[i].getReg(), 341 true, 342 blockCSI[i].getFrameIdx(), 343 blockCSI[i].getRegClass()); 344 } 345 } 346 347 for (CSRegBlockMap::iterator BI = CSRRestore.begin(), 348 BE = CSRRestore.end(); BI != BE; ++BI) { 349 MachineBasicBlock* MBB = BI->first; 350 CSRegSet restore = BI->second; 351 352 if (restore.empty()) 353 continue; 354 355 blockCSI.clear(); 356 for (CSRegSet::iterator RI = restore.begin(), 357 RE = restore.end(); RI != RE; ++RI) { 358 blockCSI.push_back(CSI[*RI]); 359 } 360 assert(blockCSI.size() > 0 && 361 "Could not find callee saved register info"); 362 363 // If MBB is empty and needs restores, insert at the _beginning_. 364 if (MBB->empty()) { 365 I = MBB->begin(); 366 } else { 367 I = MBB->end(); 368 --I; 369 370 // Skip over all terminator instructions, which are part of the 371 // return sequence. 372 if (! I->getDesc().isTerminator()) { 373 ++I; 374 } else { 375 MachineBasicBlock::iterator I2 = I; 376 while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator()) 377 I = I2; 378 } 379 } 380 381 bool AtStart = I == MBB->begin(); 382 MachineBasicBlock::iterator BeforeI = I; 383 if (!AtStart) 384 --BeforeI; 385 386 // Restore all registers immediately before the return and any 387 // terminators that preceed it. 388 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) { 389 TII.loadRegFromStackSlot(*MBB, I, blockCSI[i].getReg(), 390 blockCSI[i].getFrameIdx(), 391 blockCSI[i].getRegClass()); 392 assert(I != MBB->begin() && 393 "loadRegFromStackSlot didn't insert any code!"); 394 // Insert in reverse order. loadRegFromStackSlot can insert 395 // multiple instructions. 396 if (AtStart) 397 I = MBB->begin(); 398 else { 399 I = BeforeI; 400 ++I; 401 } 402 } 403 } 404 } 405 406 /// AdjustStackOffset - Helper function used to adjust the stack frame offset. 407 static inline void 408 AdjustStackOffset(MachineFrameInfo *FFI, int FrameIdx, 409 bool StackGrowsDown, int64_t &Offset, 410 unsigned &MaxAlign) { 411 // If stack grows down, we need to add size of find the lowest address of the 412 // object. 413 if (StackGrowsDown) 414 Offset += FFI->getObjectSize(FrameIdx); 415 416 unsigned Align = FFI->getObjectAlignment(FrameIdx); 417 418 // If the alignment of this object is greater than that of the stack, then 419 // increase the stack alignment to match. 420 MaxAlign = std::max(MaxAlign, Align); 421 422 // Adjust to alignment boundary. 423 Offset = (Offset + Align - 1) / Align * Align; 424 425 if (StackGrowsDown) { 426 FFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset 427 } else { 428 FFI->setObjectOffset(FrameIdx, Offset); 429 Offset += FFI->getObjectSize(FrameIdx); 430 } 431 } 432 433 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the 434 /// abstract stack objects. 435 /// 436 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) { 437 const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo(); 438 439 bool StackGrowsDown = 440 TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown; 441 442 // Loop over all of the stack objects, assigning sequential addresses... 443 MachineFrameInfo *FFI = Fn.getFrameInfo(); 444 445 unsigned MaxAlign = FFI->getMaxAlignment(); 446 447 // Start at the beginning of the local area. 448 // The Offset is the distance from the stack top in the direction 449 // of stack growth -- so it's always nonnegative. 450 int64_t Offset = TFI.getOffsetOfLocalArea(); 451 if (StackGrowsDown) 452 Offset = -Offset; 453 assert(Offset >= 0 454 && "Local area offset should be in direction of stack growth"); 455 456 // If there are fixed sized objects that are preallocated in the local area, 457 // non-fixed objects can't be allocated right at the start of local area. 458 // We currently don't support filling in holes in between fixed sized 459 // objects, so we adjust 'Offset' to point to the end of last fixed sized 460 // preallocated object. 461 for (int i = FFI->getObjectIndexBegin(); i != 0; ++i) { 462 int64_t FixedOff; 463 if (StackGrowsDown) { 464 // The maximum distance from the stack pointer is at lower address of 465 // the object -- which is given by offset. For down growing stack 466 // the offset is negative, so we negate the offset to get the distance. 467 FixedOff = -FFI->getObjectOffset(i); 468 } else { 469 // The maximum distance from the start pointer is at the upper 470 // address of the object. 471 FixedOff = FFI->getObjectOffset(i) + FFI->getObjectSize(i); 472 } 473 if (FixedOff > Offset) Offset = FixedOff; 474 } 475 476 // First assign frame offsets to stack objects that are used to spill 477 // callee saved registers. 478 if (StackGrowsDown) { 479 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) { 480 // If stack grows down, we need to add size of find the lowest 481 // address of the object. 482 Offset += FFI->getObjectSize(i); 483 484 unsigned Align = FFI->getObjectAlignment(i); 485 // If the alignment of this object is greater than that of the stack, 486 // then increase the stack alignment to match. 487 MaxAlign = std::max(MaxAlign, Align); 488 // Adjust to alignment boundary 489 Offset = (Offset+Align-1)/Align*Align; 490 491 FFI->setObjectOffset(i, -Offset); // Set the computed offset 492 } 493 } else { 494 int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex; 495 for (int i = MaxCSFI; i >= MinCSFI ; --i) { 496 unsigned Align = FFI->getObjectAlignment(i); 497 // If the alignment of this object is greater than that of the stack, 498 // then increase the stack alignment to match. 499 MaxAlign = std::max(MaxAlign, Align); 500 // Adjust to alignment boundary 501 Offset = (Offset+Align-1)/Align*Align; 502 503 FFI->setObjectOffset(i, Offset); 504 Offset += FFI->getObjectSize(i); 505 } 506 } 507 508 // Make sure the special register scavenging spill slot is closest to the 509 // frame pointer if a frame pointer is required. 510 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo(); 511 if (RS && RegInfo->hasFP(Fn)) { 512 int SFI = RS->getScavengingFrameIndex(); 513 if (SFI >= 0) 514 AdjustStackOffset(FFI, SFI, StackGrowsDown, Offset, MaxAlign); 515 } 516 517 // Make sure that the stack protector comes before the local variables on the 518 // stack. 519 if (FFI->getStackProtectorIndex() >= 0) 520 AdjustStackOffset(FFI, FFI->getStackProtectorIndex(), StackGrowsDown, 521 Offset, MaxAlign); 522 523 // Then assign frame offsets to stack objects that are not used to spill 524 // callee saved registers. 525 for (unsigned i = 0, e = FFI->getObjectIndexEnd(); i != e; ++i) { 526 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex) 527 continue; 528 if (RS && (int)i == RS->getScavengingFrameIndex()) 529 continue; 530 if (FFI->isDeadObjectIndex(i)) 531 continue; 532 if (FFI->getStackProtectorIndex() == (int)i) 533 continue; 534 535 AdjustStackOffset(FFI, i, StackGrowsDown, Offset, MaxAlign); 536 } 537 538 // Make sure the special register scavenging spill slot is closest to the 539 // stack pointer. 540 if (RS && !RegInfo->hasFP(Fn)) { 541 int SFI = RS->getScavengingFrameIndex(); 542 if (SFI >= 0) 543 AdjustStackOffset(FFI, SFI, StackGrowsDown, Offset, MaxAlign); 544 } 545 546 // Round up the size to a multiple of the alignment, but only if there are 547 // calls or alloca's in the function. This ensures that any calls to 548 // subroutines have their stack frames suitable aligned. 549 // Also do this if we need runtime alignment of the stack. In this case 550 // offsets will be relative to SP not FP; round up the stack size so this 551 // works. 552 if (!RegInfo->targetHandlesStackFrameRounding() && 553 (FFI->hasCalls() || FFI->hasVarSizedObjects() || 554 (RegInfo->needsStackRealignment(Fn) && 555 FFI->getObjectIndexEnd() != 0))) { 556 // If we have reserved argument space for call sites in the function 557 // immediately on entry to the current function, count it as part of the 558 // overall stack size. 559 if (RegInfo->hasReservedCallFrame(Fn)) 560 Offset += FFI->getMaxCallFrameSize(); 561 562 unsigned AlignMask = std::max(TFI.getStackAlignment(),MaxAlign) - 1; 563 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask); 564 } 565 566 // Update frame info to pretend that this is part of the stack... 567 FFI->setStackSize(Offset+TFI.getOffsetOfLocalArea()); 568 569 // Remember the required stack alignment in case targets need it to perform 570 // dynamic stack alignment. 571 FFI->setMaxAlignment(MaxAlign); 572 } 573 574 575 /// insertPrologEpilogCode - Scan the function for modified callee saved 576 /// registers, insert spill code for these callee saved registers, then add 577 /// prolog and epilog code to the function. 578 /// 579 void PEI::insertPrologEpilogCode(MachineFunction &Fn) { 580 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo(); 581 582 // Add prologue to the function... 583 TRI->emitPrologue(Fn); 584 585 // Add epilogue to restore the callee-save registers in each exiting block 586 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) { 587 // If last instruction is a return instruction, add an epilogue 588 if (!I->empty() && I->back().getDesc().isReturn()) 589 TRI->emitEpilogue(Fn, *I); 590 } 591 } 592 593 594 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical 595 /// register references and actual offsets. 596 /// 597 void PEI::replaceFrameIndices(MachineFunction &Fn) { 598 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do? 599 600 const TargetMachine &TM = Fn.getTarget(); 601 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!"); 602 const TargetRegisterInfo &TRI = *TM.getRegisterInfo(); 603 const TargetFrameInfo *TFI = TM.getFrameInfo(); 604 bool StackGrowsDown = 605 TFI->getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown; 606 int FrameSetupOpcode = TRI.getCallFrameSetupOpcode(); 607 int FrameDestroyOpcode = TRI.getCallFrameDestroyOpcode(); 608 609 for (MachineFunction::iterator BB = Fn.begin(), 610 E = Fn.end(); BB != E; ++BB) { 611 int SPAdj = 0; // SP offset due to call frame setup / destroy. 612 if (RS) RS->enterBasicBlock(BB); 613 614 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) { 615 if (I->getOpcode() == TargetInstrInfo::DECLARE) { 616 // Ignore it. 617 ++I; 618 continue; 619 } 620 621 if (I->getOpcode() == FrameSetupOpcode || 622 I->getOpcode() == FrameDestroyOpcode) { 623 // Remember how much SP has been adjusted to create the call 624 // frame. 625 int Size = I->getOperand(0).getImm(); 626 627 if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) || 628 (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode)) 629 Size = -Size; 630 631 SPAdj += Size; 632 633 MachineBasicBlock::iterator PrevI = BB->end(); 634 if (I != BB->begin()) PrevI = prior(I); 635 TRI.eliminateCallFramePseudoInstr(Fn, *BB, I); 636 637 // Visit the instructions created by eliminateCallFramePseudoInstr(). 638 if (PrevI == BB->end()) 639 I = BB->begin(); // The replaced instr was the first in the block. 640 else 641 I = next(PrevI); 642 continue; 643 } 644 645 MachineInstr *MI = I; 646 bool DoIncr = true; 647 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) 648 if (MI->getOperand(i).isFI()) { 649 // Some instructions (e.g. inline asm instructions) can have 650 // multiple frame indices and/or cause eliminateFrameIndex 651 // to insert more than one instruction. We need the register 652 // scavenger to go through all of these instructions so that 653 // it can update its register information. We keep the 654 // iterator at the point before insertion so that we can 655 // revisit them in full. 656 bool AtBeginning = (I == BB->begin()); 657 if (!AtBeginning) --I; 658 659 // If this instruction has a FrameIndex operand, we need to 660 // use that target machine register info object to eliminate 661 // it. 662 663 TRI.eliminateFrameIndex(MI, SPAdj, RS); 664 665 // Reset the iterator if we were at the beginning of the BB. 666 if (AtBeginning) { 667 I = BB->begin(); 668 DoIncr = false; 669 } 670 671 MI = 0; 672 break; 673 } 674 675 if (DoIncr && I != BB->end()) ++I; 676 677 // Update register states. 678 if (RS && MI) RS->forward(MI); 679 } 680 681 assert(SPAdj == 0 && "Unbalanced call frame setup / destroy pairs?"); 682 } 683 } 684 685