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 MachineRegisterInfo &MRI = MF.getRegInfo(); 454 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 455 for (MachineBasicBlock *MBB : Visited) { 456 MCPhysReg Reg = CSI[i].getReg(); 457 // Add the callee-saved register as live-in. 458 // It's killed at the spill. 459 if (!MRI.isReserved(Reg) && !MBB->isLiveIn(Reg)) 460 MBB->addLiveIn(Reg); 461 } 462 } 463 } 464 465 /// insertCSRSpillsAndRestores - Insert spill and restore code for 466 /// callee saved registers used in the function. 467 /// 468 static void insertCSRSpillsAndRestores(MachineFunction &Fn, 469 const MBBVector &SaveBlocks, 470 const MBBVector &RestoreBlocks) { 471 // Get callee saved register information. 472 MachineFrameInfo &MFI = Fn.getFrameInfo(); 473 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo(); 474 475 MFI.setCalleeSavedInfoValid(true); 476 477 // Early exit if no callee saved registers are modified! 478 if (CSI.empty()) 479 return; 480 481 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo(); 482 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering(); 483 const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo(); 484 MachineBasicBlock::iterator I; 485 486 // Spill using target interface. 487 for (MachineBasicBlock *SaveBlock : SaveBlocks) { 488 I = SaveBlock->begin(); 489 if (!TFI->spillCalleeSavedRegisters(*SaveBlock, I, CSI, TRI)) { 490 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 491 // Insert the spill to the stack frame. 492 unsigned Reg = CSI[i].getReg(); 493 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg); 494 TII.storeRegToStackSlot(*SaveBlock, I, Reg, true, CSI[i].getFrameIdx(), 495 RC, TRI); 496 } 497 } 498 // Update the live-in information of all the blocks up to the save point. 499 updateLiveness(Fn); 500 } 501 502 // Restore using target interface. 503 for (MachineBasicBlock *MBB : RestoreBlocks) { 504 I = MBB->end(); 505 506 // Skip over all terminator instructions, which are part of the return 507 // sequence. 508 MachineBasicBlock::iterator I2 = I; 509 while (I2 != MBB->begin() && (--I2)->isTerminator()) 510 I = I2; 511 512 bool AtStart = I == MBB->begin(); 513 MachineBasicBlock::iterator BeforeI = I; 514 if (!AtStart) 515 --BeforeI; 516 517 // Restore all registers immediately before the return and any 518 // terminators that precede it. 519 if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) { 520 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 521 unsigned Reg = CSI[i].getReg(); 522 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg); 523 TII.loadRegFromStackSlot(*MBB, I, Reg, CSI[i].getFrameIdx(), RC, TRI); 524 assert(I != MBB->begin() && 525 "loadRegFromStackSlot didn't insert any code!"); 526 // Insert in reverse order. loadRegFromStackSlot can insert 527 // multiple instructions. 528 if (AtStart) 529 I = MBB->begin(); 530 else { 531 I = BeforeI; 532 ++I; 533 } 534 } 535 } 536 } 537 } 538 539 static void doSpillCalleeSavedRegs(MachineFunction &Fn, RegScavenger *RS, 540 unsigned &MinCSFrameIndex, 541 unsigned &MaxCSFrameIndex, 542 const MBBVector &SaveBlocks, 543 const MBBVector &RestoreBlocks) { 544 const Function *F = Fn.getFunction(); 545 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering(); 546 MinCSFrameIndex = std::numeric_limits<unsigned>::max(); 547 MaxCSFrameIndex = 0; 548 549 // Determine which of the registers in the callee save list should be saved. 550 BitVector SavedRegs; 551 TFI->determineCalleeSaves(Fn, SavedRegs, RS); 552 553 // Assign stack slots for any callee-saved registers that must be spilled. 554 assignCalleeSavedSpillSlots(Fn, SavedRegs, MinCSFrameIndex, MaxCSFrameIndex); 555 556 // Add the code to save and restore the callee saved registers. 557 if (!F->hasFnAttribute(Attribute::Naked)) 558 insertCSRSpillsAndRestores(Fn, SaveBlocks, RestoreBlocks); 559 } 560 561 /// AdjustStackOffset - Helper function used to adjust the stack frame offset. 562 static inline void 563 AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx, 564 bool StackGrowsDown, int64_t &Offset, 565 unsigned &MaxAlign, unsigned Skew) { 566 // If the stack grows down, add the object size to find the lowest address. 567 if (StackGrowsDown) 568 Offset += MFI.getObjectSize(FrameIdx); 569 570 unsigned Align = MFI.getObjectAlignment(FrameIdx); 571 572 // If the alignment of this object is greater than that of the stack, then 573 // increase the stack alignment to match. 574 MaxAlign = std::max(MaxAlign, Align); 575 576 // Adjust to alignment boundary. 577 Offset = alignTo(Offset, Align, Skew); 578 579 if (StackGrowsDown) { 580 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n"); 581 MFI.setObjectOffset(FrameIdx, -Offset); // Set the computed offset 582 } else { 583 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n"); 584 MFI.setObjectOffset(FrameIdx, Offset); 585 Offset += MFI.getObjectSize(FrameIdx); 586 } 587 } 588 589 /// Compute which bytes of fixed and callee-save stack area are unused and keep 590 /// track of them in StackBytesFree. 591 /// 592 static inline void 593 computeFreeStackSlots(MachineFrameInfo &MFI, bool StackGrowsDown, 594 unsigned MinCSFrameIndex, unsigned MaxCSFrameIndex, 595 int64_t FixedCSEnd, BitVector &StackBytesFree) { 596 // Avoid undefined int64_t -> int conversion below in extreme case. 597 if (FixedCSEnd > std::numeric_limits<int>::max()) 598 return; 599 600 StackBytesFree.resize(FixedCSEnd, true); 601 602 SmallVector<int, 16> AllocatedFrameSlots; 603 // Add fixed objects. 604 for (int i = MFI.getObjectIndexBegin(); i != 0; ++i) 605 AllocatedFrameSlots.push_back(i); 606 // Add callee-save objects. 607 for (int i = MinCSFrameIndex; i <= (int)MaxCSFrameIndex; ++i) 608 AllocatedFrameSlots.push_back(i); 609 610 for (int i : AllocatedFrameSlots) { 611 // These are converted from int64_t, but they should always fit in int 612 // because of the FixedCSEnd check above. 613 int ObjOffset = MFI.getObjectOffset(i); 614 int ObjSize = MFI.getObjectSize(i); 615 int ObjStart, ObjEnd; 616 if (StackGrowsDown) { 617 // ObjOffset is negative when StackGrowsDown is true. 618 ObjStart = -ObjOffset - ObjSize; 619 ObjEnd = -ObjOffset; 620 } else { 621 ObjStart = ObjOffset; 622 ObjEnd = ObjOffset + ObjSize; 623 } 624 // Ignore fixed holes that are in the previous stack frame. 625 if (ObjEnd > 0) 626 StackBytesFree.reset(ObjStart, ObjEnd); 627 } 628 } 629 630 /// Assign frame object to an unused portion of the stack in the fixed stack 631 /// object range. Return true if the allocation was successful. 632 /// 633 static inline bool scavengeStackSlot(MachineFrameInfo &MFI, int FrameIdx, 634 bool StackGrowsDown, unsigned MaxAlign, 635 BitVector &StackBytesFree) { 636 if (MFI.isVariableSizedObjectIndex(FrameIdx)) 637 return false; 638 639 if (StackBytesFree.none()) { 640 // clear it to speed up later scavengeStackSlot calls to 641 // StackBytesFree.none() 642 StackBytesFree.clear(); 643 return false; 644 } 645 646 unsigned ObjAlign = MFI.getObjectAlignment(FrameIdx); 647 if (ObjAlign > MaxAlign) 648 return false; 649 650 int64_t ObjSize = MFI.getObjectSize(FrameIdx); 651 int FreeStart; 652 for (FreeStart = StackBytesFree.find_first(); FreeStart != -1; 653 FreeStart = StackBytesFree.find_next(FreeStart)) { 654 655 // Check that free space has suitable alignment. 656 unsigned ObjStart = StackGrowsDown ? FreeStart + ObjSize : FreeStart; 657 if (alignTo(ObjStart, ObjAlign) != ObjStart) 658 continue; 659 660 if (FreeStart + ObjSize > StackBytesFree.size()) 661 return false; 662 663 bool AllBytesFree = true; 664 for (unsigned Byte = 0; Byte < ObjSize; ++Byte) 665 if (!StackBytesFree.test(FreeStart + Byte)) { 666 AllBytesFree = false; 667 break; 668 } 669 if (AllBytesFree) 670 break; 671 } 672 673 if (FreeStart == -1) 674 return false; 675 676 if (StackGrowsDown) { 677 int ObjStart = -(FreeStart + ObjSize); 678 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP[" << ObjStart 679 << "]\n"); 680 MFI.setObjectOffset(FrameIdx, ObjStart); 681 } else { 682 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP[" << FreeStart 683 << "]\n"); 684 MFI.setObjectOffset(FrameIdx, FreeStart); 685 } 686 687 StackBytesFree.reset(FreeStart, FreeStart + ObjSize); 688 return true; 689 } 690 691 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e., 692 /// those required to be close to the Stack Protector) to stack offsets. 693 static void 694 AssignProtectedObjSet(const StackObjSet &UnassignedObjs, 695 SmallSet<int, 16> &ProtectedObjs, 696 MachineFrameInfo &MFI, bool StackGrowsDown, 697 int64_t &Offset, unsigned &MaxAlign, unsigned Skew) { 698 699 for (StackObjSet::const_iterator I = UnassignedObjs.begin(), 700 E = UnassignedObjs.end(); I != E; ++I) { 701 int i = *I; 702 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign, Skew); 703 ProtectedObjs.insert(i); 704 } 705 } 706 707 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the 708 /// abstract stack objects. 709 /// 710 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) { 711 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering(); 712 StackProtector *SP = &getAnalysis<StackProtector>(); 713 714 bool StackGrowsDown = 715 TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown; 716 717 // Loop over all of the stack objects, assigning sequential addresses... 718 MachineFrameInfo &MFI = Fn.getFrameInfo(); 719 720 // Start at the beginning of the local area. 721 // The Offset is the distance from the stack top in the direction 722 // of stack growth -- so it's always nonnegative. 723 int LocalAreaOffset = TFI.getOffsetOfLocalArea(); 724 if (StackGrowsDown) 725 LocalAreaOffset = -LocalAreaOffset; 726 assert(LocalAreaOffset >= 0 727 && "Local area offset should be in direction of stack growth"); 728 int64_t Offset = LocalAreaOffset; 729 730 // Skew to be applied to alignment. 731 unsigned Skew = TFI.getStackAlignmentSkew(Fn); 732 733 // If there are fixed sized objects that are preallocated in the local area, 734 // non-fixed objects can't be allocated right at the start of local area. 735 // Adjust 'Offset' to point to the end of last fixed sized preallocated 736 // object. 737 for (int i = MFI.getObjectIndexBegin(); i != 0; ++i) { 738 int64_t FixedOff; 739 if (StackGrowsDown) { 740 // The maximum distance from the stack pointer is at lower address of 741 // the object -- which is given by offset. For down growing stack 742 // the offset is negative, so we negate the offset to get the distance. 743 FixedOff = -MFI.getObjectOffset(i); 744 } else { 745 // The maximum distance from the start pointer is at the upper 746 // address of the object. 747 FixedOff = MFI.getObjectOffset(i) + MFI.getObjectSize(i); 748 } 749 if (FixedOff > Offset) Offset = FixedOff; 750 } 751 752 // First assign frame offsets to stack objects that are used to spill 753 // callee saved registers. 754 if (StackGrowsDown) { 755 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) { 756 // If the stack grows down, we need to add the size to find the lowest 757 // address of the object. 758 Offset += MFI.getObjectSize(i); 759 760 unsigned Align = MFI.getObjectAlignment(i); 761 // Adjust to alignment boundary 762 Offset = alignTo(Offset, Align, Skew); 763 764 DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << -Offset << "]\n"); 765 MFI.setObjectOffset(i, -Offset); // Set the computed offset 766 } 767 } else if (MaxCSFrameIndex >= MinCSFrameIndex) { 768 // Be careful about underflow in comparisons agains MinCSFrameIndex. 769 for (unsigned i = MaxCSFrameIndex; i != MinCSFrameIndex - 1; --i) { 770 if (MFI.isDeadObjectIndex(i)) 771 continue; 772 773 unsigned Align = MFI.getObjectAlignment(i); 774 // Adjust to alignment boundary 775 Offset = alignTo(Offset, Align, Skew); 776 777 DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << Offset << "]\n"); 778 MFI.setObjectOffset(i, Offset); 779 Offset += MFI.getObjectSize(i); 780 } 781 } 782 783 // FixedCSEnd is the stack offset to the end of the fixed and callee-save 784 // stack area. 785 int64_t FixedCSEnd = Offset; 786 unsigned MaxAlign = MFI.getMaxAlignment(); 787 788 // Make sure the special register scavenging spill slot is closest to the 789 // incoming stack pointer if a frame pointer is required and is closer 790 // to the incoming rather than the final stack pointer. 791 const TargetRegisterInfo *RegInfo = Fn.getSubtarget().getRegisterInfo(); 792 bool EarlyScavengingSlots = (TFI.hasFP(Fn) && 793 TFI.isFPCloseToIncomingSP() && 794 RegInfo->useFPForScavengingIndex(Fn) && 795 !RegInfo->needsStackRealignment(Fn)); 796 if (RS && EarlyScavengingSlots) { 797 SmallVector<int, 2> SFIs; 798 RS->getScavengingFrameIndices(SFIs); 799 for (SmallVectorImpl<int>::iterator I = SFIs.begin(), 800 IE = SFIs.end(); I != IE; ++I) 801 AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew); 802 } 803 804 // FIXME: Once this is working, then enable flag will change to a target 805 // check for whether the frame is large enough to want to use virtual 806 // frame index registers. Functions which don't want/need this optimization 807 // will continue to use the existing code path. 808 if (MFI.getUseLocalStackAllocationBlock()) { 809 unsigned Align = MFI.getLocalFrameMaxAlign(); 810 811 // Adjust to alignment boundary. 812 Offset = alignTo(Offset, Align, Skew); 813 814 DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n"); 815 816 // Resolve offsets for objects in the local block. 817 for (unsigned i = 0, e = MFI.getLocalFrameObjectCount(); i != e; ++i) { 818 std::pair<int, int64_t> Entry = MFI.getLocalFrameObjectMap(i); 819 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second; 820 DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" << 821 FIOffset << "]\n"); 822 MFI.setObjectOffset(Entry.first, FIOffset); 823 } 824 // Allocate the local block 825 Offset += MFI.getLocalFrameSize(); 826 827 MaxAlign = std::max(Align, MaxAlign); 828 } 829 830 // Retrieve the Exception Handler registration node. 831 int EHRegNodeFrameIndex = INT_MAX; 832 if (const WinEHFuncInfo *FuncInfo = Fn.getWinEHFuncInfo()) 833 EHRegNodeFrameIndex = FuncInfo->EHRegNodeFrameIndex; 834 835 // Make sure that the stack protector comes before the local variables on the 836 // stack. 837 SmallSet<int, 16> ProtectedObjs; 838 if (MFI.getStackProtectorIndex() >= 0) { 839 StackObjSet LargeArrayObjs; 840 StackObjSet SmallArrayObjs; 841 StackObjSet AddrOfObjs; 842 843 AdjustStackOffset(MFI, MFI.getStackProtectorIndex(), StackGrowsDown, 844 Offset, MaxAlign, Skew); 845 846 // Assign large stack objects first. 847 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) { 848 if (MFI.isObjectPreAllocated(i) && 849 MFI.getUseLocalStackAllocationBlock()) 850 continue; 851 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex) 852 continue; 853 if (RS && RS->isScavengingFrameIndex((int)i)) 854 continue; 855 if (MFI.isDeadObjectIndex(i)) 856 continue; 857 if (MFI.getStackProtectorIndex() == (int)i || 858 EHRegNodeFrameIndex == (int)i) 859 continue; 860 861 switch (SP->getSSPLayout(MFI.getObjectAllocation(i))) { 862 case StackProtector::SSPLK_None: 863 continue; 864 case StackProtector::SSPLK_SmallArray: 865 SmallArrayObjs.insert(i); 866 continue; 867 case StackProtector::SSPLK_AddrOf: 868 AddrOfObjs.insert(i); 869 continue; 870 case StackProtector::SSPLK_LargeArray: 871 LargeArrayObjs.insert(i); 872 continue; 873 } 874 llvm_unreachable("Unexpected SSPLayoutKind."); 875 } 876 877 AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown, 878 Offset, MaxAlign, Skew); 879 AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown, 880 Offset, MaxAlign, Skew); 881 AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown, 882 Offset, MaxAlign, Skew); 883 } 884 885 SmallVector<int, 8> ObjectsToAllocate; 886 887 // Then prepare to assign frame offsets to stack objects that are not used to 888 // spill callee saved registers. 889 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) { 890 if (MFI.isObjectPreAllocated(i) && MFI.getUseLocalStackAllocationBlock()) 891 continue; 892 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex) 893 continue; 894 if (RS && RS->isScavengingFrameIndex((int)i)) 895 continue; 896 if (MFI.isDeadObjectIndex(i)) 897 continue; 898 if (MFI.getStackProtectorIndex() == (int)i || 899 EHRegNodeFrameIndex == (int)i) 900 continue; 901 if (ProtectedObjs.count(i)) 902 continue; 903 904 // Add the objects that we need to allocate to our working set. 905 ObjectsToAllocate.push_back(i); 906 } 907 908 // Allocate the EH registration node first if one is present. 909 if (EHRegNodeFrameIndex != INT_MAX) 910 AdjustStackOffset(MFI, EHRegNodeFrameIndex, StackGrowsDown, Offset, 911 MaxAlign, Skew); 912 913 // Give the targets a chance to order the objects the way they like it. 914 if (Fn.getTarget().getOptLevel() != CodeGenOpt::None && 915 Fn.getTarget().Options.StackSymbolOrdering) 916 TFI.orderFrameObjects(Fn, ObjectsToAllocate); 917 918 // Keep track of which bytes in the fixed and callee-save range are used so we 919 // can use the holes when allocating later stack objects. Only do this if 920 // stack protector isn't being used and the target requests it and we're 921 // optimizing. 922 BitVector StackBytesFree; 923 if (!ObjectsToAllocate.empty() && 924 Fn.getTarget().getOptLevel() != CodeGenOpt::None && 925 MFI.getStackProtectorIndex() < 0 && TFI.enableStackSlotScavenging(Fn)) 926 computeFreeStackSlots(MFI, StackGrowsDown, MinCSFrameIndex, MaxCSFrameIndex, 927 FixedCSEnd, StackBytesFree); 928 929 // Now walk the objects and actually assign base offsets to them. 930 for (auto &Object : ObjectsToAllocate) 931 if (!scavengeStackSlot(MFI, Object, StackGrowsDown, MaxAlign, 932 StackBytesFree)) 933 AdjustStackOffset(MFI, Object, StackGrowsDown, Offset, MaxAlign, Skew); 934 935 // Make sure the special register scavenging spill slot is closest to the 936 // stack pointer. 937 if (RS && !EarlyScavengingSlots) { 938 SmallVector<int, 2> SFIs; 939 RS->getScavengingFrameIndices(SFIs); 940 for (SmallVectorImpl<int>::iterator I = SFIs.begin(), 941 IE = SFIs.end(); I != IE; ++I) 942 AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew); 943 } 944 945 if (!TFI.targetHandlesStackFrameRounding()) { 946 // If we have reserved argument space for call sites in the function 947 // immediately on entry to the current function, count it as part of the 948 // overall stack size. 949 if (MFI.adjustsStack() && TFI.hasReservedCallFrame(Fn)) 950 Offset += MFI.getMaxCallFrameSize(); 951 952 // Round up the size to a multiple of the alignment. If the function has 953 // any calls or alloca's, align to the target's StackAlignment value to 954 // ensure that the callee's frame or the alloca data is suitably aligned; 955 // otherwise, for leaf functions, align to the TransientStackAlignment 956 // value. 957 unsigned StackAlign; 958 if (MFI.adjustsStack() || MFI.hasVarSizedObjects() || 959 (RegInfo->needsStackRealignment(Fn) && MFI.getObjectIndexEnd() != 0)) 960 StackAlign = TFI.getStackAlignment(); 961 else 962 StackAlign = TFI.getTransientStackAlignment(); 963 964 // If the frame pointer is eliminated, all frame offsets will be relative to 965 // SP not FP. Align to MaxAlign so this works. 966 StackAlign = std::max(StackAlign, MaxAlign); 967 Offset = alignTo(Offset, StackAlign, Skew); 968 } 969 970 // Update frame info to pretend that this is part of the stack... 971 int64_t StackSize = Offset - LocalAreaOffset; 972 MFI.setStackSize(StackSize); 973 NumBytesStackSpace += StackSize; 974 } 975 976 /// insertPrologEpilogCode - Scan the function for modified callee saved 977 /// registers, insert spill code for these callee saved registers, then add 978 /// prolog and epilog code to the function. 979 /// 980 void PEI::insertPrologEpilogCode(MachineFunction &Fn) { 981 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering(); 982 983 // Add prologue to the function... 984 for (MachineBasicBlock *SaveBlock : SaveBlocks) 985 TFI.emitPrologue(Fn, *SaveBlock); 986 987 // Add epilogue to restore the callee-save registers in each exiting block. 988 for (MachineBasicBlock *RestoreBlock : RestoreBlocks) 989 TFI.emitEpilogue(Fn, *RestoreBlock); 990 991 for (MachineBasicBlock *SaveBlock : SaveBlocks) 992 TFI.inlineStackProbe(Fn, *SaveBlock); 993 994 // Emit additional code that is required to support segmented stacks, if 995 // we've been asked for it. This, when linked with a runtime with support 996 // for segmented stacks (libgcc is one), will result in allocating stack 997 // space in small chunks instead of one large contiguous block. 998 if (Fn.shouldSplitStack()) { 999 for (MachineBasicBlock *SaveBlock : SaveBlocks) 1000 TFI.adjustForSegmentedStacks(Fn, *SaveBlock); 1001 } 1002 1003 // Emit additional code that is required to explicitly handle the stack in 1004 // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The 1005 // approach is rather similar to that of Segmented Stacks, but it uses a 1006 // different conditional check and another BIF for allocating more stack 1007 // space. 1008 if (Fn.getFunction()->getCallingConv() == CallingConv::HiPE) 1009 for (MachineBasicBlock *SaveBlock : SaveBlocks) 1010 TFI.adjustForHiPEPrologue(Fn, *SaveBlock); 1011 } 1012 1013 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical 1014 /// register references and actual offsets. 1015 /// 1016 void PEI::replaceFrameIndices(MachineFunction &Fn) { 1017 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering(); 1018 if (!TFI.needsFrameIndexResolution(Fn)) return; 1019 1020 // Store SPAdj at exit of a basic block. 1021 SmallVector<int, 8> SPState; 1022 SPState.resize(Fn.getNumBlockIDs()); 1023 df_iterator_default_set<MachineBasicBlock*> Reachable; 1024 1025 // Iterate over the reachable blocks in DFS order. 1026 for (auto DFI = df_ext_begin(&Fn, Reachable), DFE = df_ext_end(&Fn, Reachable); 1027 DFI != DFE; ++DFI) { 1028 int SPAdj = 0; 1029 // Check the exit state of the DFS stack predecessor. 1030 if (DFI.getPathLength() >= 2) { 1031 MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2); 1032 assert(Reachable.count(StackPred) && 1033 "DFS stack predecessor is already visited.\n"); 1034 SPAdj = SPState[StackPred->getNumber()]; 1035 } 1036 MachineBasicBlock *BB = *DFI; 1037 replaceFrameIndices(BB, Fn, SPAdj); 1038 SPState[BB->getNumber()] = SPAdj; 1039 } 1040 1041 // Handle the unreachable blocks. 1042 for (auto &BB : Fn) { 1043 if (Reachable.count(&BB)) 1044 // Already handled in DFS traversal. 1045 continue; 1046 int SPAdj = 0; 1047 replaceFrameIndices(&BB, Fn, SPAdj); 1048 } 1049 } 1050 1051 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn, 1052 int &SPAdj) { 1053 assert(Fn.getSubtarget().getRegisterInfo() && 1054 "getRegisterInfo() must be implemented!"); 1055 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo(); 1056 const TargetRegisterInfo &TRI = *Fn.getSubtarget().getRegisterInfo(); 1057 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering(); 1058 1059 if (RS && FrameIndexEliminationScavenging) 1060 RS->enterBasicBlock(*BB); 1061 1062 bool InsideCallSequence = false; 1063 1064 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) { 1065 1066 if (TII.isFrameInstr(*I)) { 1067 InsideCallSequence = TII.isFrameSetup(*I); 1068 SPAdj += TII.getSPAdjust(*I); 1069 I = TFI->eliminateCallFramePseudoInstr(Fn, *BB, I); 1070 continue; 1071 } 1072 1073 MachineInstr &MI = *I; 1074 bool DoIncr = true; 1075 bool DidFinishLoop = true; 1076 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 1077 if (!MI.getOperand(i).isFI()) 1078 continue; 1079 1080 // Frame indices in debug values are encoded in a target independent 1081 // way with simply the frame index and offset rather than any 1082 // target-specific addressing mode. 1083 if (MI.isDebugValue()) { 1084 assert(i == 0 && "Frame indices can only appear as the first " 1085 "operand of a DBG_VALUE machine instruction"); 1086 unsigned Reg; 1087 MachineOperand &Offset = MI.getOperand(1); 1088 Offset.setImm( 1089 Offset.getImm() + 1090 TFI->getFrameIndexReference(Fn, MI.getOperand(0).getIndex(), Reg)); 1091 MI.getOperand(0).ChangeToRegister(Reg, false /*isDef*/); 1092 continue; 1093 } 1094 1095 // TODO: This code should be commoned with the code for 1096 // PATCHPOINT. There's no good reason for the difference in 1097 // implementation other than historical accident. The only 1098 // remaining difference is the unconditional use of the stack 1099 // pointer as the base register. 1100 if (MI.getOpcode() == TargetOpcode::STATEPOINT) { 1101 assert((!MI.isDebugValue() || i == 0) && 1102 "Frame indicies can only appear as the first operand of a " 1103 "DBG_VALUE machine instruction"); 1104 unsigned Reg; 1105 MachineOperand &Offset = MI.getOperand(i + 1); 1106 int refOffset = TFI->getFrameIndexReferencePreferSP( 1107 Fn, MI.getOperand(i).getIndex(), Reg, /*IgnoreSPUpdates*/ false); 1108 Offset.setImm(Offset.getImm() + refOffset); 1109 MI.getOperand(i).ChangeToRegister(Reg, false /*isDef*/); 1110 continue; 1111 } 1112 1113 // Some instructions (e.g. inline asm instructions) can have 1114 // multiple frame indices and/or cause eliminateFrameIndex 1115 // to insert more than one instruction. We need the register 1116 // scavenger to go through all of these instructions so that 1117 // it can update its register information. We keep the 1118 // iterator at the point before insertion so that we can 1119 // revisit them in full. 1120 bool AtBeginning = (I == BB->begin()); 1121 if (!AtBeginning) --I; 1122 1123 // If this instruction has a FrameIndex operand, we need to 1124 // use that target machine register info object to eliminate 1125 // it. 1126 TRI.eliminateFrameIndex(MI, SPAdj, i, 1127 FrameIndexEliminationScavenging ? RS : nullptr); 1128 1129 // Reset the iterator if we were at the beginning of the BB. 1130 if (AtBeginning) { 1131 I = BB->begin(); 1132 DoIncr = false; 1133 } 1134 1135 DidFinishLoop = false; 1136 break; 1137 } 1138 1139 // If we are looking at a call sequence, we need to keep track of 1140 // the SP adjustment made by each instruction in the sequence. 1141 // This includes both the frame setup/destroy pseudos (handled above), 1142 // as well as other instructions that have side effects w.r.t the SP. 1143 // Note that this must come after eliminateFrameIndex, because 1144 // if I itself referred to a frame index, we shouldn't count its own 1145 // adjustment. 1146 if (DidFinishLoop && InsideCallSequence) 1147 SPAdj += TII.getSPAdjust(MI); 1148 1149 if (DoIncr && I != BB->end()) ++I; 1150 1151 // Update register states. 1152 if (RS && FrameIndexEliminationScavenging && DidFinishLoop) 1153 RS->forward(MI); 1154 } 1155 } 1156 1157 /// doScavengeFrameVirtualRegs - Replace all frame index virtual registers 1158 /// with physical registers. Use the register scavenger to find an 1159 /// appropriate register to use. 1160 /// 1161 /// FIXME: Iterating over the instruction stream is unnecessary. We can simply 1162 /// iterate over the vreg use list, which at this point only contains machine 1163 /// operands for which eliminateFrameIndex need a new scratch reg. 1164 static void 1165 doScavengeFrameVirtualRegs(MachineFunction &MF, RegScavenger *RS) { 1166 // Run through the instructions and find any virtual registers. 1167 MachineRegisterInfo &MRI = MF.getRegInfo(); 1168 for (MachineBasicBlock &MBB : MF) { 1169 RS->enterBasicBlock(MBB); 1170 1171 int SPAdj = 0; 1172 1173 // The instruction stream may change in the loop, so check MBB.end() 1174 // directly. 1175 for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ) { 1176 // We might end up here again with a NULL iterator if we scavenged a 1177 // register for which we inserted spill code for definition by what was 1178 // originally the first instruction in MBB. 1179 if (I == MachineBasicBlock::iterator(nullptr)) 1180 I = MBB.begin(); 1181 1182 const MachineInstr &MI = *I; 1183 MachineBasicBlock::iterator J = std::next(I); 1184 MachineBasicBlock::iterator P = 1185 I == MBB.begin() ? MachineBasicBlock::iterator(nullptr) 1186 : std::prev(I); 1187 1188 // RS should process this instruction before we might scavenge at this 1189 // location. This is because we might be replacing a virtual register 1190 // defined by this instruction, and if so, registers killed by this 1191 // instruction are available, and defined registers are not. 1192 RS->forward(I); 1193 1194 for (const MachineOperand &MO : MI.operands()) { 1195 if (!MO.isReg()) 1196 continue; 1197 unsigned Reg = MO.getReg(); 1198 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 1199 continue; 1200 1201 // When we first encounter a new virtual register, it 1202 // must be a definition. 1203 assert(MO.isDef() && "frame index virtual missing def!"); 1204 // Scavenge a new scratch register 1205 const TargetRegisterClass *RC = MRI.getRegClass(Reg); 1206 unsigned ScratchReg = RS->scavengeRegister(RC, J, SPAdj); 1207 1208 ++NumScavengedRegs; 1209 1210 // Replace this reference to the virtual register with the 1211 // scratch register. 1212 assert(ScratchReg && "Missing scratch register!"); 1213 MRI.replaceRegWith(Reg, ScratchReg); 1214 1215 // Because this instruction was processed by the RS before this 1216 // register was allocated, make sure that the RS now records the 1217 // register as being used. 1218 RS->setRegUsed(ScratchReg); 1219 } 1220 1221 // If the scavenger needed to use one of its spill slots, the 1222 // spill code will have been inserted in between I and J. This is a 1223 // problem because we need the spill code before I: Move I to just 1224 // prior to J. 1225 if (I != std::prev(J)) { 1226 MBB.splice(J, &MBB, I); 1227 1228 // Before we move I, we need to prepare the RS to visit I again. 1229 // Specifically, RS will assert if it sees uses of registers that 1230 // it believes are undefined. Because we have already processed 1231 // register kills in I, when it visits I again, it will believe that 1232 // those registers are undefined. To avoid this situation, unprocess 1233 // the instruction I. 1234 assert(RS->getCurrentPosition() == I && 1235 "The register scavenger has an unexpected position"); 1236 I = P; 1237 RS->unprocess(P); 1238 } else 1239 ++I; 1240 } 1241 } 1242 1243 MF.getProperties().set(MachineFunctionProperties::Property::NoVRegs); 1244 } 1245