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