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