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 //===----------------------------------------------------------------------===// 18 19 #include "llvm/ADT/IndexedMap.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/SetVector.h" 22 #include "llvm/ADT/SmallSet.h" 23 #include "llvm/ADT/Statistic.h" 24 #include "llvm/CodeGen/MachineDominators.h" 25 #include "llvm/CodeGen/MachineFrameInfo.h" 26 #include "llvm/CodeGen/MachineInstr.h" 27 #include "llvm/CodeGen/MachineLoopInfo.h" 28 #include "llvm/CodeGen/MachineModuleInfo.h" 29 #include "llvm/CodeGen/MachineRegisterInfo.h" 30 #include "llvm/CodeGen/Passes.h" 31 #include "llvm/CodeGen/RegisterScavenging.h" 32 #include "llvm/CodeGen/StackProtector.h" 33 #include "llvm/CodeGen/WinEHFuncInfo.h" 34 #include "llvm/IR/DiagnosticInfo.h" 35 #include "llvm/IR/InlineAsm.h" 36 #include "llvm/IR/LLVMContext.h" 37 #include "llvm/Support/CommandLine.h" 38 #include "llvm/Support/Compiler.h" 39 #include "llvm/Support/Debug.h" 40 #include "llvm/Support/raw_ostream.h" 41 #include "llvm/Target/TargetFrameLowering.h" 42 #include "llvm/Target/TargetInstrInfo.h" 43 #include "llvm/Target/TargetMachine.h" 44 #include "llvm/Target/TargetRegisterInfo.h" 45 #include "llvm/Target/TargetSubtargetInfo.h" 46 #include <climits> 47 48 using namespace llvm; 49 50 #define DEBUG_TYPE "pei" 51 52 namespace { 53 class PEI : public MachineFunctionPass { 54 public: 55 static char ID; 56 PEI() : MachineFunctionPass(ID) { 57 initializePEIPass(*PassRegistry::getPassRegistry()); 58 } 59 60 void getAnalysisUsage(AnalysisUsage &AU) const override; 61 62 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract 63 /// frame indexes with appropriate references. 64 /// 65 bool runOnMachineFunction(MachineFunction &Fn) override; 66 67 private: 68 RegScavenger *RS; 69 70 // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved 71 // stack frame indexes. 72 unsigned MinCSFrameIndex, MaxCSFrameIndex; 73 74 // Save and Restore blocks of the current function. Typically there is a 75 // single save block, unless Windows EH funclets are involved. 76 SmallVector<MachineBasicBlock *, 1> SaveBlocks; 77 SmallVector<MachineBasicBlock *, 4> RestoreBlocks; 78 79 // Flag to control whether to use the register scavenger to resolve 80 // frame index materialization registers. Set according to 81 // TRI->requiresFrameIndexScavenging() for the current function. 82 bool FrameIndexVirtualScavenging; 83 84 void calculateSets(MachineFunction &Fn); 85 void calculateCallsInformation(MachineFunction &Fn); 86 void assignCalleeSavedSpillSlots(MachineFunction &Fn, 87 const BitVector &SavedRegs); 88 void insertCSRSpillsAndRestores(MachineFunction &Fn); 89 void calculateFrameObjectOffsets(MachineFunction &Fn); 90 void replaceFrameIndices(MachineFunction &Fn); 91 void replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn, 92 int &SPAdj); 93 void scavengeFrameVirtualRegs(MachineFunction &Fn); 94 void insertPrologEpilogCode(MachineFunction &Fn); 95 96 // Convenience for recognizing return blocks. 97 bool isReturnBlock(const MachineBasicBlock *MBB) const; 98 }; 99 } // namespace 100 101 char PEI::ID = 0; 102 char &llvm::PrologEpilogCodeInserterID = PEI::ID; 103 104 static cl::opt<unsigned> 105 WarnStackSize("warn-stack-size", cl::Hidden, cl::init((unsigned)-1), 106 cl::desc("Warn for stack size bigger than the given" 107 " number")); 108 109 INITIALIZE_PASS_BEGIN(PEI, "prologepilog", 110 "Prologue/Epilogue Insertion", false, false) 111 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 112 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 113 INITIALIZE_PASS_DEPENDENCY(StackProtector) 114 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) 115 INITIALIZE_PASS_END(PEI, "prologepilog", 116 "Prologue/Epilogue Insertion & Frame Finalization", 117 false, false) 118 119 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged"); 120 STATISTIC(NumBytesStackSpace, 121 "Number of bytes used for stack in all functions"); 122 123 void PEI::getAnalysisUsage(AnalysisUsage &AU) const { 124 AU.setPreservesCFG(); 125 AU.addPreserved<MachineLoopInfo>(); 126 AU.addPreserved<MachineDominatorTree>(); 127 AU.addRequired<StackProtector>(); 128 AU.addRequired<TargetPassConfig>(); 129 MachineFunctionPass::getAnalysisUsage(AU); 130 } 131 132 bool PEI::isReturnBlock(const MachineBasicBlock* MBB) const { 133 return (MBB && !MBB->empty() && MBB->back().isReturn()); 134 } 135 136 /// Compute the set of return blocks 137 void PEI::calculateSets(MachineFunction &Fn) { 138 const MachineFrameInfo *MFI = Fn.getFrameInfo(); 139 140 // Even when we do not change any CSR, we still want to insert the 141 // prologue and epilogue of the function. 142 // So set the save points for those. 143 144 // Use the points found by shrink-wrapping, if any. 145 if (MFI->getSavePoint()) { 146 SaveBlocks.push_back(MFI->getSavePoint()); 147 assert(MFI->getRestorePoint() && "Both restore and save must be set"); 148 MachineBasicBlock *RestoreBlock = MFI->getRestorePoint(); 149 // If RestoreBlock does not have any successor and is not a return block 150 // then the end point is unreachable and we do not need to insert any 151 // epilogue. 152 if (!RestoreBlock->succ_empty() || isReturnBlock(RestoreBlock)) 153 RestoreBlocks.push_back(RestoreBlock); 154 return; 155 } 156 157 // Save refs to entry and return blocks. 158 SaveBlocks.push_back(Fn.begin()); 159 for (MachineBasicBlock &MBB : Fn) { 160 if (MBB.isEHFuncletEntry()) 161 SaveBlocks.push_back(&MBB); 162 if (isReturnBlock(&MBB)) 163 RestoreBlocks.push_back(&MBB); 164 } 165 } 166 167 /// StackObjSet - A set of stack object indexes 168 typedef SmallSetVector<int, 8> StackObjSet; 169 170 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract 171 /// frame indexes with appropriate references. 172 /// 173 bool PEI::runOnMachineFunction(MachineFunction &Fn) { 174 const Function* F = Fn.getFunction(); 175 const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo(); 176 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering(); 177 178 assert(!Fn.getRegInfo().getNumVirtRegs() && "Regalloc must assign all vregs"); 179 180 RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : nullptr; 181 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn); 182 183 // Calculate the MaxCallFrameSize and AdjustsStack variables for the 184 // function's frame information. Also eliminates call frame pseudo 185 // instructions. 186 calculateCallsInformation(Fn); 187 188 // Determine which of the registers in the callee save list should be saved. 189 BitVector SavedRegs; 190 TFI->determineCalleeSaves(Fn, SavedRegs, RS); 191 192 // Insert spill code for any callee saved registers that are modified. 193 assignCalleeSavedSpillSlots(Fn, SavedRegs); 194 195 // Determine placement of CSR spill/restore code: 196 // place all spills in the entry block, all restores in return blocks. 197 calculateSets(Fn); 198 199 // Add the code to save and restore the callee saved registers 200 if (!F->hasFnAttribute(Attribute::Naked)) 201 insertCSRSpillsAndRestores(Fn); 202 203 // Allow the target machine to make final modifications to the function 204 // before the frame layout is finalized. 205 TFI->processFunctionBeforeFrameFinalized(Fn, RS); 206 207 // Calculate actual frame offsets for all abstract stack objects... 208 calculateFrameObjectOffsets(Fn); 209 210 // Add prolog and epilog code to the function. This function is required 211 // to align the stack frame as necessary for any stack variables or 212 // called functions. Because of this, calculateCalleeSavedRegisters() 213 // must be called before this function in order to set the AdjustsStack 214 // and MaxCallFrameSize variables. 215 if (!F->hasFnAttribute(Attribute::Naked)) 216 insertPrologEpilogCode(Fn); 217 218 // Replace all MO_FrameIndex operands with physical register references 219 // and actual offsets. 220 // 221 replaceFrameIndices(Fn); 222 223 // If register scavenging is needed, as we've enabled doing it as a 224 // post-pass, scavenge the virtual registers that frame index elimination 225 // inserted. 226 if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging) 227 scavengeFrameVirtualRegs(Fn); 228 229 // Clear any vregs created by virtual scavenging. 230 Fn.getRegInfo().clearVirtRegs(); 231 232 // Warn on stack size when we exceeds the given limit. 233 MachineFrameInfo *MFI = Fn.getFrameInfo(); 234 uint64_t StackSize = MFI->getStackSize(); 235 if (WarnStackSize.getNumOccurrences() > 0 && WarnStackSize < StackSize) { 236 DiagnosticInfoStackSize DiagStackSize(*F, StackSize); 237 F->getContext().diagnose(DiagStackSize); 238 } 239 240 delete RS; 241 SaveBlocks.clear(); 242 RestoreBlocks.clear(); 243 return true; 244 } 245 246 /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack 247 /// variables for the function's frame information and eliminate call frame 248 /// pseudo instructions. 249 void PEI::calculateCallsInformation(MachineFunction &Fn) { 250 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo(); 251 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering(); 252 MachineFrameInfo *MFI = Fn.getFrameInfo(); 253 254 unsigned MaxCallFrameSize = 0; 255 bool AdjustsStack = MFI->adjustsStack(); 256 257 // Get the function call frame set-up and tear-down instruction opcode 258 unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode(); 259 unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode(); 260 261 // Early exit for targets which have no call frame setup/destroy pseudo 262 // instructions. 263 if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u) 264 return; 265 266 std::vector<MachineBasicBlock::iterator> FrameSDOps; 267 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) 268 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) 269 if (I->getOpcode() == FrameSetupOpcode || 270 I->getOpcode() == FrameDestroyOpcode) { 271 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo" 272 " instructions should have a single immediate argument!"); 273 unsigned Size = I->getOperand(0).getImm(); 274 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size; 275 AdjustsStack = true; 276 FrameSDOps.push_back(I); 277 } else if (I->isInlineAsm()) { 278 // Some inline asm's need a stack frame, as indicated by operand 1. 279 unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 280 if (ExtraInfo & InlineAsm::Extra_IsAlignStack) 281 AdjustsStack = true; 282 } 283 284 MFI->setAdjustsStack(AdjustsStack); 285 MFI->setMaxCallFrameSize(MaxCallFrameSize); 286 287 for (std::vector<MachineBasicBlock::iterator>::iterator 288 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) { 289 MachineBasicBlock::iterator I = *i; 290 291 // If call frames are not being included as part of the stack frame, and 292 // the target doesn't indicate otherwise, remove the call frame pseudos 293 // here. The sub/add sp instruction pairs are still inserted, but we don't 294 // need to track the SP adjustment for frame index elimination. 295 if (TFI->canSimplifyCallFramePseudos(Fn)) 296 TFI->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I); 297 } 298 } 299 300 void PEI::assignCalleeSavedSpillSlots(MachineFunction &F, 301 const BitVector &SavedRegs) { 302 // These are used to keep track the callee-save area. Initialize them. 303 MinCSFrameIndex = INT_MAX; 304 MaxCSFrameIndex = 0; 305 306 if (SavedRegs.empty()) 307 return; 308 309 const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo(); 310 const MCPhysReg *CSRegs = RegInfo->getCalleeSavedRegs(&F); 311 312 std::vector<CalleeSavedInfo> CSI; 313 for (unsigned i = 0; CSRegs[i]; ++i) { 314 unsigned Reg = CSRegs[i]; 315 if (SavedRegs.test(Reg)) 316 CSI.push_back(CalleeSavedInfo(Reg)); 317 } 318 319 const TargetFrameLowering *TFI = F.getSubtarget().getFrameLowering(); 320 MachineFrameInfo *MFI = F.getFrameInfo(); 321 if (!TFI->assignCalleeSavedSpillSlots(F, RegInfo, CSI)) { 322 // If target doesn't implement this, use generic code. 323 324 if (CSI.empty()) 325 return; // Early exit if no callee saved registers are modified! 326 327 unsigned NumFixedSpillSlots; 328 const TargetFrameLowering::SpillSlot *FixedSpillSlots = 329 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots); 330 331 // Now that we know which registers need to be saved and restored, allocate 332 // stack slots for them. 333 for (std::vector<CalleeSavedInfo>::iterator I = CSI.begin(), E = CSI.end(); 334 I != E; ++I) { 335 unsigned Reg = I->getReg(); 336 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg); 337 338 int FrameIdx; 339 if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) { 340 I->setFrameIdx(FrameIdx); 341 continue; 342 } 343 344 // Check to see if this physreg must be spilled to a particular stack slot 345 // on this target. 346 const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots; 347 while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots && 348 FixedSlot->Reg != Reg) 349 ++FixedSlot; 350 351 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) { 352 // Nope, just spill it anywhere convenient. 353 unsigned Align = RC->getAlignment(); 354 unsigned StackAlign = TFI->getStackAlignment(); 355 356 // We may not be able to satisfy the desired alignment specification of 357 // the TargetRegisterClass if the stack alignment is smaller. Use the 358 // min. 359 Align = std::min(Align, StackAlign); 360 FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true); 361 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx; 362 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx; 363 } else { 364 // Spill it to the stack where we must. 365 FrameIdx = 366 MFI->CreateFixedSpillStackObject(RC->getSize(), FixedSlot->Offset); 367 } 368 369 I->setFrameIdx(FrameIdx); 370 } 371 } 372 373 MFI->setCalleeSavedInfo(CSI); 374 } 375 376 /// Helper function to update the liveness information for the callee-saved 377 /// registers. 378 static void updateLiveness(MachineFunction &MF) { 379 MachineFrameInfo *MFI = MF.getFrameInfo(); 380 // Visited will contain all the basic blocks that are in the region 381 // where the callee saved registers are alive: 382 // - Anything that is not Save or Restore -> LiveThrough. 383 // - Save -> LiveIn. 384 // - Restore -> LiveOut. 385 // The live-out is not attached to the block, so no need to keep 386 // Restore in this set. 387 SmallPtrSet<MachineBasicBlock *, 8> Visited; 388 SmallVector<MachineBasicBlock *, 8> WorkList; 389 MachineBasicBlock *Entry = &MF.front(); 390 MachineBasicBlock *Save = MFI->getSavePoint(); 391 392 if (!Save) 393 Save = Entry; 394 395 if (Entry != Save) { 396 WorkList.push_back(Entry); 397 Visited.insert(Entry); 398 } 399 Visited.insert(Save); 400 401 MachineBasicBlock *Restore = MFI->getRestorePoint(); 402 if (Restore) 403 // By construction Restore cannot be visited, otherwise it 404 // means there exists a path to Restore that does not go 405 // through Save. 406 WorkList.push_back(Restore); 407 408 while (!WorkList.empty()) { 409 const MachineBasicBlock *CurBB = WorkList.pop_back_val(); 410 // By construction, the region that is after the save point is 411 // dominated by the Save and post-dominated by the Restore. 412 if (CurBB == Save) 413 continue; 414 // Enqueue all the successors not already visited. 415 // Those are by construction either before Save or after Restore. 416 for (MachineBasicBlock *SuccBB : CurBB->successors()) 417 if (Visited.insert(SuccBB).second) 418 WorkList.push_back(SuccBB); 419 } 420 421 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo(); 422 423 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 424 for (MachineBasicBlock *MBB : Visited) 425 // Add the callee-saved register as live-in. 426 // It's killed at the spill. 427 MBB->addLiveIn(CSI[i].getReg()); 428 } 429 } 430 431 /// insertCSRSpillsAndRestores - Insert spill and restore code for 432 /// callee saved registers used in the function. 433 /// 434 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) { 435 // Get callee saved register information. 436 MachineFrameInfo *MFI = Fn.getFrameInfo(); 437 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo(); 438 439 MFI->setCalleeSavedInfoValid(true); 440 441 // Early exit if no callee saved registers are modified! 442 if (CSI.empty()) 443 return; 444 445 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo(); 446 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering(); 447 const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo(); 448 MachineBasicBlock::iterator I; 449 450 // Spill using target interface. 451 for (MachineBasicBlock *SaveBlock : SaveBlocks) { 452 I = SaveBlock->begin(); 453 if (!TFI->spillCalleeSavedRegisters(*SaveBlock, I, CSI, TRI)) { 454 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 455 // Insert the spill to the stack frame. 456 unsigned Reg = CSI[i].getReg(); 457 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg); 458 TII.storeRegToStackSlot(*SaveBlock, I, Reg, true, CSI[i].getFrameIdx(), 459 RC, TRI); 460 } 461 } 462 // Update the live-in information of all the blocks up to the save point. 463 updateLiveness(Fn); 464 } 465 466 // Restore using target interface. 467 for (MachineBasicBlock *MBB : RestoreBlocks) { 468 I = MBB->end(); 469 470 // Skip over all terminator instructions, which are part of the return 471 // sequence. 472 MachineBasicBlock::iterator I2 = I; 473 while (I2 != MBB->begin() && (--I2)->isTerminator()) 474 I = I2; 475 476 bool AtStart = I == MBB->begin(); 477 MachineBasicBlock::iterator BeforeI = I; 478 if (!AtStart) 479 --BeforeI; 480 481 // Restore all registers immediately before the return and any 482 // terminators that precede it. 483 if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) { 484 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 485 unsigned Reg = CSI[i].getReg(); 486 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg); 487 TII.loadRegFromStackSlot(*MBB, I, Reg, CSI[i].getFrameIdx(), RC, TRI); 488 assert(I != MBB->begin() && 489 "loadRegFromStackSlot didn't insert any code!"); 490 // Insert in reverse order. loadRegFromStackSlot can insert 491 // multiple instructions. 492 if (AtStart) 493 I = MBB->begin(); 494 else { 495 I = BeforeI; 496 ++I; 497 } 498 } 499 } 500 } 501 } 502 503 /// AdjustStackOffset - Helper function used to adjust the stack frame offset. 504 static inline void 505 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx, 506 bool StackGrowsDown, int64_t &Offset, 507 unsigned &MaxAlign) { 508 // If the stack grows down, add the object size to find the lowest address. 509 if (StackGrowsDown) 510 Offset += MFI->getObjectSize(FrameIdx); 511 512 unsigned Align = MFI->getObjectAlignment(FrameIdx); 513 514 // If the alignment of this object is greater than that of the stack, then 515 // increase the stack alignment to match. 516 MaxAlign = std::max(MaxAlign, Align); 517 518 // Adjust to alignment boundary. 519 Offset = (Offset + Align - 1) / Align * Align; 520 521 if (StackGrowsDown) { 522 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n"); 523 MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset 524 } else { 525 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n"); 526 MFI->setObjectOffset(FrameIdx, Offset); 527 Offset += MFI->getObjectSize(FrameIdx); 528 } 529 } 530 531 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e., 532 /// those required to be close to the Stack Protector) to stack offsets. 533 static void 534 AssignProtectedObjSet(const StackObjSet &UnassignedObjs, 535 SmallSet<int, 16> &ProtectedObjs, 536 MachineFrameInfo *MFI, bool StackGrowsDown, 537 int64_t &Offset, unsigned &MaxAlign) { 538 539 for (StackObjSet::const_iterator I = UnassignedObjs.begin(), 540 E = UnassignedObjs.end(); I != E; ++I) { 541 int i = *I; 542 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign); 543 ProtectedObjs.insert(i); 544 } 545 } 546 547 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the 548 /// abstract stack objects. 549 /// 550 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) { 551 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering(); 552 StackProtector *SP = &getAnalysis<StackProtector>(); 553 554 bool StackGrowsDown = 555 TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown; 556 557 // Loop over all of the stack objects, assigning sequential addresses... 558 MachineFrameInfo *MFI = Fn.getFrameInfo(); 559 560 // Start at the beginning of the local area. 561 // The Offset is the distance from the stack top in the direction 562 // of stack growth -- so it's always nonnegative. 563 int LocalAreaOffset = TFI.getOffsetOfLocalArea(); 564 if (StackGrowsDown) 565 LocalAreaOffset = -LocalAreaOffset; 566 assert(LocalAreaOffset >= 0 567 && "Local area offset should be in direction of stack growth"); 568 int64_t Offset = LocalAreaOffset; 569 570 // If there are fixed sized objects that are preallocated in the local area, 571 // non-fixed objects can't be allocated right at the start of local area. 572 // We currently don't support filling in holes in between fixed sized 573 // objects, so we adjust 'Offset' to point to the end of last fixed sized 574 // preallocated object. 575 for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) { 576 int64_t FixedOff; 577 if (StackGrowsDown) { 578 // The maximum distance from the stack pointer is at lower address of 579 // the object -- which is given by offset. For down growing stack 580 // the offset is negative, so we negate the offset to get the distance. 581 FixedOff = -MFI->getObjectOffset(i); 582 } else { 583 // The maximum distance from the start pointer is at the upper 584 // address of the object. 585 FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i); 586 } 587 if (FixedOff > Offset) Offset = FixedOff; 588 } 589 590 // First assign frame offsets to stack objects that are used to spill 591 // callee saved registers. 592 if (StackGrowsDown) { 593 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) { 594 // If the stack grows down, we need to add the size to find the lowest 595 // address of the object. 596 Offset += MFI->getObjectSize(i); 597 598 unsigned Align = MFI->getObjectAlignment(i); 599 // Adjust to alignment boundary 600 Offset = RoundUpToAlignment(Offset, Align); 601 602 MFI->setObjectOffset(i, -Offset); // Set the computed offset 603 } 604 } else { 605 int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex; 606 for (int i = MaxCSFI; i >= MinCSFI ; --i) { 607 unsigned Align = MFI->getObjectAlignment(i); 608 // Adjust to alignment boundary 609 Offset = RoundUpToAlignment(Offset, Align); 610 611 MFI->setObjectOffset(i, Offset); 612 Offset += MFI->getObjectSize(i); 613 } 614 } 615 616 unsigned MaxAlign = MFI->getMaxAlignment(); 617 618 // Make sure the special register scavenging spill slot is closest to the 619 // incoming stack pointer if a frame pointer is required and is closer 620 // to the incoming rather than the final stack pointer. 621 const TargetRegisterInfo *RegInfo = Fn.getSubtarget().getRegisterInfo(); 622 bool EarlyScavengingSlots = (TFI.hasFP(Fn) && 623 TFI.isFPCloseToIncomingSP() && 624 RegInfo->useFPForScavengingIndex(Fn) && 625 !RegInfo->needsStackRealignment(Fn)); 626 if (RS && EarlyScavengingSlots) { 627 SmallVector<int, 2> SFIs; 628 RS->getScavengingFrameIndices(SFIs); 629 for (SmallVectorImpl<int>::iterator I = SFIs.begin(), 630 IE = SFIs.end(); I != IE; ++I) 631 AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign); 632 } 633 634 // FIXME: Once this is working, then enable flag will change to a target 635 // check for whether the frame is large enough to want to use virtual 636 // frame index registers. Functions which don't want/need this optimization 637 // will continue to use the existing code path. 638 if (MFI->getUseLocalStackAllocationBlock()) { 639 unsigned Align = MFI->getLocalFrameMaxAlign(); 640 641 // Adjust to alignment boundary. 642 Offset = RoundUpToAlignment(Offset, Align); 643 644 DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n"); 645 646 // Resolve offsets for objects in the local block. 647 for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) { 648 std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i); 649 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second; 650 DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" << 651 FIOffset << "]\n"); 652 MFI->setObjectOffset(Entry.first, FIOffset); 653 } 654 // Allocate the local block 655 Offset += MFI->getLocalFrameSize(); 656 657 MaxAlign = std::max(Align, MaxAlign); 658 } 659 660 // Make sure that the stack protector comes before the local variables on the 661 // stack. 662 SmallSet<int, 16> ProtectedObjs; 663 if (MFI->getStackProtectorIndex() >= 0) { 664 StackObjSet LargeArrayObjs; 665 StackObjSet SmallArrayObjs; 666 StackObjSet AddrOfObjs; 667 668 AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown, 669 Offset, MaxAlign); 670 671 // Assign large stack objects first. 672 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) { 673 if (MFI->isObjectPreAllocated(i) && 674 MFI->getUseLocalStackAllocationBlock()) 675 continue; 676 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex) 677 continue; 678 if (RS && RS->isScavengingFrameIndex((int)i)) 679 continue; 680 if (MFI->isDeadObjectIndex(i)) 681 continue; 682 if (MFI->getStackProtectorIndex() == (int)i) 683 continue; 684 685 switch (SP->getSSPLayout(MFI->getObjectAllocation(i))) { 686 case StackProtector::SSPLK_None: 687 continue; 688 case StackProtector::SSPLK_SmallArray: 689 SmallArrayObjs.insert(i); 690 continue; 691 case StackProtector::SSPLK_AddrOf: 692 AddrOfObjs.insert(i); 693 continue; 694 case StackProtector::SSPLK_LargeArray: 695 LargeArrayObjs.insert(i); 696 continue; 697 } 698 llvm_unreachable("Unexpected SSPLayoutKind."); 699 } 700 701 AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown, 702 Offset, MaxAlign); 703 AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown, 704 Offset, MaxAlign); 705 AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown, 706 Offset, MaxAlign); 707 } 708 709 // Then assign frame offsets to stack objects that are not used to spill 710 // callee saved registers. 711 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) { 712 if (MFI->isObjectPreAllocated(i) && 713 MFI->getUseLocalStackAllocationBlock()) 714 continue; 715 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex) 716 continue; 717 if (RS && RS->isScavengingFrameIndex((int)i)) 718 continue; 719 if (MFI->isDeadObjectIndex(i)) 720 continue; 721 if (MFI->getStackProtectorIndex() == (int)i) 722 continue; 723 if (ProtectedObjs.count(i)) 724 continue; 725 726 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign); 727 } 728 729 // Make sure the special register scavenging spill slot is closest to the 730 // stack pointer. 731 if (RS && !EarlyScavengingSlots) { 732 SmallVector<int, 2> SFIs; 733 RS->getScavengingFrameIndices(SFIs); 734 for (SmallVectorImpl<int>::iterator I = SFIs.begin(), 735 IE = SFIs.end(); I != IE; ++I) 736 AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign); 737 } 738 739 if (!TFI.targetHandlesStackFrameRounding()) { 740 // If we have reserved argument space for call sites in the function 741 // immediately on entry to the current function, count it as part of the 742 // overall stack size. 743 if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn)) 744 Offset += MFI->getMaxCallFrameSize(); 745 746 // Round up the size to a multiple of the alignment. If the function has 747 // any calls or alloca's, align to the target's StackAlignment value to 748 // ensure that the callee's frame or the alloca data is suitably aligned; 749 // otherwise, for leaf functions, align to the TransientStackAlignment 750 // value. 751 unsigned StackAlign; 752 if (MFI->adjustsStack() || MFI->hasVarSizedObjects() || 753 (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0)) 754 StackAlign = TFI.getStackAlignment(); 755 else 756 StackAlign = TFI.getTransientStackAlignment(); 757 758 // If the frame pointer is eliminated, all frame offsets will be relative to 759 // SP not FP. Align to MaxAlign so this works. 760 StackAlign = std::max(StackAlign, MaxAlign); 761 Offset = RoundUpToAlignment(Offset, StackAlign); 762 } 763 764 // Update frame info to pretend that this is part of the stack... 765 int64_t StackSize = Offset - LocalAreaOffset; 766 MFI->setStackSize(StackSize); 767 NumBytesStackSpace += StackSize; 768 } 769 770 /// insertPrologEpilogCode - Scan the function for modified callee saved 771 /// registers, insert spill code for these callee saved registers, then add 772 /// prolog and epilog code to the function. 773 /// 774 void PEI::insertPrologEpilogCode(MachineFunction &Fn) { 775 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering(); 776 777 // Add prologue to the function... 778 for (MachineBasicBlock *SaveBlock : SaveBlocks) 779 TFI.emitPrologue(Fn, *SaveBlock); 780 781 // Add epilogue to restore the callee-save registers in each exiting block. 782 for (MachineBasicBlock *RestoreBlock : RestoreBlocks) 783 TFI.emitEpilogue(Fn, *RestoreBlock); 784 785 // Emit additional code that is required to support segmented stacks, if 786 // we've been asked for it. This, when linked with a runtime with support 787 // for segmented stacks (libgcc is one), will result in allocating stack 788 // space in small chunks instead of one large contiguous block. 789 if (Fn.shouldSplitStack()) { 790 for (MachineBasicBlock *SaveBlock : SaveBlocks) 791 TFI.adjustForSegmentedStacks(Fn, *SaveBlock); 792 } 793 794 // Emit additional code that is required to explicitly handle the stack in 795 // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The 796 // approach is rather similar to that of Segmented Stacks, but it uses a 797 // different conditional check and another BIF for allocating more stack 798 // space. 799 if (Fn.getFunction()->getCallingConv() == CallingConv::HiPE) 800 for (MachineBasicBlock *SaveBlock : SaveBlocks) 801 TFI.adjustForHiPEPrologue(Fn, *SaveBlock); 802 } 803 804 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical 805 /// register references and actual offsets. 806 /// 807 void PEI::replaceFrameIndices(MachineFunction &Fn) { 808 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering(); 809 if (!TFI.needsFrameIndexResolution(Fn)) return; 810 811 MachineModuleInfo &MMI = Fn.getMMI(); 812 const Function *F = Fn.getFunction(); 813 const Function *ParentF = MMI.getWinEHParent(F); 814 unsigned FrameReg; 815 if (F == ParentF) { 816 WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(Fn.getFunction()); 817 // FIXME: This should be unconditional but we have bugs in the preparation 818 // pass. 819 if (FuncInfo.UnwindHelpFrameIdx != INT_MAX) 820 FuncInfo.UnwindHelpFrameOffset = TFI.getFrameIndexReferenceFromSP( 821 Fn, FuncInfo.UnwindHelpFrameIdx, FrameReg); 822 } else if (MMI.hasWinEHFuncInfo(F)) { 823 WinEHFuncInfo &FuncInfo = MMI.getWinEHFuncInfo(Fn.getFunction()); 824 auto I = FuncInfo.CatchHandlerParentFrameObjIdx.find(F); 825 if (I != FuncInfo.CatchHandlerParentFrameObjIdx.end()) 826 FuncInfo.CatchHandlerParentFrameObjOffset[F] = 827 TFI.getFrameIndexReferenceFromSP(Fn, I->second, FrameReg); 828 } 829 830 // Store SPAdj at exit of a basic block. 831 SmallVector<int, 8> SPState; 832 SPState.resize(Fn.getNumBlockIDs()); 833 SmallPtrSet<MachineBasicBlock*, 8> Reachable; 834 835 // Iterate over the reachable blocks in DFS order. 836 for (auto DFI = df_ext_begin(&Fn, Reachable), DFE = df_ext_end(&Fn, Reachable); 837 DFI != DFE; ++DFI) { 838 int SPAdj = 0; 839 // Check the exit state of the DFS stack predecessor. 840 if (DFI.getPathLength() >= 2) { 841 MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2); 842 assert(Reachable.count(StackPred) && 843 "DFS stack predecessor is already visited.\n"); 844 SPAdj = SPState[StackPred->getNumber()]; 845 } 846 MachineBasicBlock *BB = *DFI; 847 replaceFrameIndices(BB, Fn, SPAdj); 848 SPState[BB->getNumber()] = SPAdj; 849 } 850 851 // Handle the unreachable blocks. 852 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) { 853 if (Reachable.count(BB)) 854 // Already handled in DFS traversal. 855 continue; 856 int SPAdj = 0; 857 replaceFrameIndices(BB, Fn, SPAdj); 858 } 859 } 860 861 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn, 862 int &SPAdj) { 863 assert(Fn.getSubtarget().getRegisterInfo() && 864 "getRegisterInfo() must be implemented!"); 865 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo(); 866 const TargetRegisterInfo &TRI = *Fn.getSubtarget().getRegisterInfo(); 867 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering(); 868 unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode(); 869 unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode(); 870 871 if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB); 872 873 bool InsideCallSequence = false; 874 875 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) { 876 877 if (I->getOpcode() == FrameSetupOpcode || 878 I->getOpcode() == FrameDestroyOpcode) { 879 InsideCallSequence = (I->getOpcode() == FrameSetupOpcode); 880 SPAdj += TII.getSPAdjust(I); 881 882 MachineBasicBlock::iterator PrevI = BB->end(); 883 if (I != BB->begin()) PrevI = std::prev(I); 884 TFI->eliminateCallFramePseudoInstr(Fn, *BB, I); 885 886 // Visit the instructions created by eliminateCallFramePseudoInstr(). 887 if (PrevI == BB->end()) 888 I = BB->begin(); // The replaced instr was the first in the block. 889 else 890 I = std::next(PrevI); 891 continue; 892 } 893 894 MachineInstr *MI = I; 895 bool DoIncr = true; 896 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 897 if (!MI->getOperand(i).isFI()) 898 continue; 899 900 // Frame indicies in debug values are encoded in a target independent 901 // way with simply the frame index and offset rather than any 902 // target-specific addressing mode. 903 if (MI->isDebugValue()) { 904 assert(i == 0 && "Frame indicies can only appear as the first " 905 "operand of a DBG_VALUE machine instruction"); 906 unsigned Reg; 907 MachineOperand &Offset = MI->getOperand(1); 908 Offset.setImm(Offset.getImm() + 909 TFI->getFrameIndexReference( 910 Fn, MI->getOperand(0).getIndex(), Reg)); 911 MI->getOperand(0).ChangeToRegister(Reg, false /*isDef*/); 912 continue; 913 } 914 915 // TODO: This code should be commoned with the code for 916 // PATCHPOINT. There's no good reason for the difference in 917 // implementation other than historical accident. The only 918 // remaining difference is the unconditional use of the stack 919 // pointer as the base register. 920 if (MI->getOpcode() == TargetOpcode::STATEPOINT) { 921 assert((!MI->isDebugValue() || i == 0) && 922 "Frame indicies can only appear as the first operand of a " 923 "DBG_VALUE machine instruction"); 924 unsigned Reg; 925 MachineOperand &Offset = MI->getOperand(i + 1); 926 const unsigned refOffset = 927 TFI->getFrameIndexReferenceFromSP(Fn, MI->getOperand(i).getIndex(), 928 Reg); 929 930 Offset.setImm(Offset.getImm() + refOffset); 931 MI->getOperand(i).ChangeToRegister(Reg, false /*isDef*/); 932 continue; 933 } 934 935 // Some instructions (e.g. inline asm instructions) can have 936 // multiple frame indices and/or cause eliminateFrameIndex 937 // to insert more than one instruction. We need the register 938 // scavenger to go through all of these instructions so that 939 // it can update its register information. We keep the 940 // iterator at the point before insertion so that we can 941 // revisit them in full. 942 bool AtBeginning = (I == BB->begin()); 943 if (!AtBeginning) --I; 944 945 // If this instruction has a FrameIndex operand, we need to 946 // use that target machine register info object to eliminate 947 // it. 948 TRI.eliminateFrameIndex(MI, SPAdj, i, 949 FrameIndexVirtualScavenging ? nullptr : RS); 950 951 // Reset the iterator if we were at the beginning of the BB. 952 if (AtBeginning) { 953 I = BB->begin(); 954 DoIncr = false; 955 } 956 957 MI = nullptr; 958 break; 959 } 960 961 // If we are looking at a call sequence, we need to keep track of 962 // the SP adjustment made by each instruction in the sequence. 963 // This includes both the frame setup/destroy pseudos (handled above), 964 // as well as other instructions that have side effects w.r.t the SP. 965 // Note that this must come after eliminateFrameIndex, because 966 // if I itself referred to a frame index, we shouldn't count its own 967 // adjustment. 968 if (MI && InsideCallSequence) 969 SPAdj += TII.getSPAdjust(MI); 970 971 if (DoIncr && I != BB->end()) ++I; 972 973 // Update register states. 974 if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI); 975 } 976 } 977 978 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers 979 /// with physical registers. Use the register scavenger to find an 980 /// appropriate register to use. 981 /// 982 /// FIXME: Iterating over the instruction stream is unnecessary. We can simply 983 /// iterate over the vreg use list, which at this point only contains machine 984 /// operands for which eliminateFrameIndex need a new scratch reg. 985 void 986 PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) { 987 // Run through the instructions and find any virtual registers. 988 for (MachineFunction::iterator BB = Fn.begin(), 989 E = Fn.end(); BB != E; ++BB) { 990 RS->enterBasicBlock(BB); 991 992 int SPAdj = 0; 993 994 // The instruction stream may change in the loop, so check BB->end() 995 // directly. 996 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) { 997 // We might end up here again with a NULL iterator if we scavenged a 998 // register for which we inserted spill code for definition by what was 999 // originally the first instruction in BB. 1000 if (I == MachineBasicBlock::iterator(nullptr)) 1001 I = BB->begin(); 1002 1003 MachineInstr *MI = I; 1004 MachineBasicBlock::iterator J = std::next(I); 1005 MachineBasicBlock::iterator P = 1006 I == BB->begin() ? MachineBasicBlock::iterator(nullptr) 1007 : std::prev(I); 1008 1009 // RS should process this instruction before we might scavenge at this 1010 // location. This is because we might be replacing a virtual register 1011 // defined by this instruction, and if so, registers killed by this 1012 // instruction are available, and defined registers are not. 1013 RS->forward(I); 1014 1015 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 1016 if (MI->getOperand(i).isReg()) { 1017 MachineOperand &MO = MI->getOperand(i); 1018 unsigned Reg = MO.getReg(); 1019 if (Reg == 0) 1020 continue; 1021 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 1022 continue; 1023 1024 // When we first encounter a new virtual register, it 1025 // must be a definition. 1026 assert(MI->getOperand(i).isDef() && 1027 "frame index virtual missing def!"); 1028 // Scavenge a new scratch register 1029 const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg); 1030 unsigned ScratchReg = RS->scavengeRegister(RC, J, SPAdj); 1031 1032 ++NumScavengedRegs; 1033 1034 // Replace this reference to the virtual register with the 1035 // scratch register. 1036 assert (ScratchReg && "Missing scratch register!"); 1037 Fn.getRegInfo().replaceRegWith(Reg, ScratchReg); 1038 1039 // Because this instruction was processed by the RS before this 1040 // register was allocated, make sure that the RS now records the 1041 // register as being used. 1042 RS->setRegUsed(ScratchReg); 1043 } 1044 } 1045 1046 // If the scavenger needed to use one of its spill slots, the 1047 // spill code will have been inserted in between I and J. This is a 1048 // problem because we need the spill code before I: Move I to just 1049 // prior to J. 1050 if (I != std::prev(J)) { 1051 BB->splice(J, BB, I); 1052 1053 // Before we move I, we need to prepare the RS to visit I again. 1054 // Specifically, RS will assert if it sees uses of registers that 1055 // it believes are undefined. Because we have already processed 1056 // register kills in I, when it visits I again, it will believe that 1057 // those registers are undefined. To avoid this situation, unprocess 1058 // the instruction I. 1059 assert(RS->getCurrentPosition() == I && 1060 "The register scavenger has an unexpected position"); 1061 I = P; 1062 RS->unprocess(P); 1063 } else 1064 ++I; 1065 } 1066 } 1067 } 1068