LLVM 24.0.0git
PrologEpilogInserter.cpp
Go to the documentation of this file.
1//===- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function ---===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass is responsible for finalizing the functions frame layout, saving
10// callee saved registers, and for emitting prolog & epilog code for the
11// function.
12//
13// This pass must be run after register allocation. After this pass is
14// executed, it is illegal to construct MO_FrameIndex operands.
15//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/ADT/BitVector.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/SmallSet.h"
25#include "llvm/ADT/Statistic.h"
38#include "llvm/CodeGen/PEI.h"
47#include "llvm/IR/Attributes.h"
48#include "llvm/IR/CallingConv.h"
51#include "llvm/IR/Function.h"
52#include "llvm/IR/LLVMContext.h"
54#include "llvm/Pass.h"
56#include "llvm/Support/Debug.h"
62#include <algorithm>
63#include <cassert>
64#include <cstdint>
65#include <limits>
66#include <utility>
67#include <vector>
68
69using namespace llvm;
70
71#define DEBUG_TYPE "prolog-epilog"
72
74
75STATISTIC(NumLeafFuncWithSpills, "Number of leaf functions with CSRs");
76STATISTIC(NumFuncSeen, "Number of functions seen in PEI");
77
78
79namespace {
80
81class PEIImpl {
82 RegScavenger *RS = nullptr;
83
84 // Save and Restore blocks of the current function. Typically there is a
85 // single save block, unless Windows EH funclets are involved.
86 MBBVector SaveBlocks;
87 MBBVector RestoreBlocks;
88
89 // Flag to control whether to use the register scavenger to resolve
90 // frame index materialization registers. Set according to
91 // TRI->requiresFrameIndexScavenging() for the current function.
92 bool FrameIndexVirtualScavenging = false;
93
94 // Flag to control whether the scavenger should be passed even though
95 // FrameIndexVirtualScavenging is used.
96 bool FrameIndexEliminationScavenging = false;
97
98 // Emit remarks.
100
101 void calculateCallFrameInfo(MachineFunction &MF);
102 void calculateSaveRestoreBlocks(MachineFunction &MF);
103 void spillCalleeSavedRegs(MachineFunction &MF);
104
105 void calculateFrameObjectOffsets(MachineFunction &MF);
106 void replaceFrameIndices(MachineFunction &MF);
107 void replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &MF,
108 int &SPAdj);
109 // Frame indices in debug values are encoded in a target independent
110 // way with simply the frame index and offset rather than any
111 // target-specific addressing mode.
112 bool replaceFrameIndexDebugInstr(MachineFunction &MF, MachineInstr &MI,
113 unsigned OpIdx, int SPAdj = 0);
114 // Does same as replaceFrameIndices but using the backward MIR walk and
115 // backward register scavenger walk.
116 void replaceFrameIndicesBackward(MachineFunction &MF);
117 void replaceFrameIndicesBackward(MachineBasicBlock *BB, MachineFunction &MF,
118 int &SPAdj);
119
120 void insertPrologEpilogCode(MachineFunction &MF);
121 void insertZeroCallUsedRegs(MachineFunction &MF);
122
123public:
124 PEIImpl(MachineOptimizationRemarkEmitter *ORE) : ORE(ORE) {}
125 bool run(MachineFunction &MF);
126};
127
128class PEILegacy : public MachineFunctionPass {
129public:
130 static char ID;
131
132 PEILegacy() : MachineFunctionPass(ID) {}
133
134 void getAnalysisUsage(AnalysisUsage &AU) const override;
135
136 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract
137 /// frame indexes with appropriate references.
138 bool runOnMachineFunction(MachineFunction &MF) override;
139};
140
141} // end anonymous namespace
142
143char PEILegacy::ID = 0;
144
146
147INITIALIZE_PASS_BEGIN(PEILegacy, DEBUG_TYPE, "Prologue/Epilogue Insertion",
148 false, false)
153 "Prologue/Epilogue Insertion & Frame Finalization", false,
154 false)
155
157 return new PEILegacy();
158}
159
160STATISTIC(NumBytesStackSpace,
161 "Number of bytes used for stack in all functions");
162
163void PEILegacy::getAnalysisUsage(AnalysisUsage &AU) const {
164 AU.setPreservesCFG();
167}
168
169/// StackObjSet - A set of stack object indexes
171
174
175/// Stash DBG_VALUEs that describe parameters and which are placed at the start
176/// of the block. Later on, after the prologue code has been emitted, the
177/// stashed DBG_VALUEs will be reinserted at the start of the block.
179 SavedDbgValuesMap &EntryDbgValues) {
181
182 for (auto &MI : MBB) {
183 if (!MI.isDebugInstr())
184 break;
185 if (!MI.isDebugValue() || !MI.getDebugVariable()->isParameter())
186 continue;
187 if (any_of(MI.debug_operands(),
188 [](const MachineOperand &MO) { return MO.isFI(); })) {
189 // We can only emit valid locations for frame indices after the frame
190 // setup, so do not stash away them.
191 FrameIndexValues.push_back(&MI);
192 continue;
193 }
194 const DILocalVariable *Var = MI.getDebugVariable();
195 const DIExpression *Expr = MI.getDebugExpression();
196 auto Overlaps = [Var, Expr](const MachineInstr *DV) {
197 return Var == DV->getDebugVariable() &&
198 Expr->fragmentsOverlap(DV->getDebugExpression());
199 };
200 // See if the debug value overlaps with any preceding debug value that will
201 // not be stashed. If that is the case, then we can't stash this value, as
202 // we would then reorder the values at reinsertion.
203 if (llvm::none_of(FrameIndexValues, Overlaps))
204 EntryDbgValues[&MBB].push_back(&MI);
205 }
206
207 // Remove stashed debug values from the block.
208 if (auto It = EntryDbgValues.find(&MBB); It != EntryDbgValues.end())
209 for (auto *MI : It->second)
210 MI->removeFromParent();
211}
212
213bool PEIImpl::run(MachineFunction &MF) {
214 NumFuncSeen++;
215 const Function &F = MF.getFunction();
216 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
217 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
218
219 RS = TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : nullptr;
220 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(MF);
221
222 // Spill frame pointer and/or base pointer registers if they are clobbered.
223 // It is placed before call frame instruction elimination so it will not mess
224 // with stack arguments.
225 TFI->spillFPBP(MF);
226
227 // Calculate the MaxCallFrameSize value for the function's frame
228 // information. Also eliminates call frame pseudo instructions.
229 calculateCallFrameInfo(MF);
230
231 // Determine placement of CSR spill/restore code and prolog/epilog code:
232 // place all spills in the entry block, all restores in return blocks.
233 calculateSaveRestoreBlocks(MF);
234
235 // Stash away DBG_VALUEs that should not be moved by insertion of prolog code.
236 SavedDbgValuesMap EntryDbgValues;
237 for (MachineBasicBlock *SaveBlock : SaveBlocks)
238 stashEntryDbgValues(*SaveBlock, EntryDbgValues);
239
240 // Handle CSR spilling and restoring, for targets that need it.
242 spillCalleeSavedRegs(MF);
243
244 // Allow the target machine to make final modifications to the function
245 // before the frame layout is finalized.
247
248 // Calculate actual frame offsets for all abstract stack objects...
249 calculateFrameObjectOffsets(MF);
250
251 // Add prolog and epilog code to the function. This function is required
252 // to align the stack frame as necessary for any stack variables or
253 // called functions. Because of this, calculateCalleeSavedRegisters()
254 // must be called before this function in order to set the AdjustsStack
255 // and MaxCallFrameSize variables.
256 if (!F.hasFnAttribute(Attribute::Naked))
257 insertPrologEpilogCode(MF);
258
259 // Reinsert stashed debug values at the start of the entry blocks.
260 for (auto &I : EntryDbgValues)
261 I.first->insert(I.first->begin(), I.second.begin(), I.second.end());
262
263 // Allow the target machine to make final modifications to the function
264 // before the frame layout is finalized.
266
267 // Replace all MO_FrameIndex operands with physical register references
268 // and actual offsets.
269 if (TFI->needsFrameIndexResolution(MF)) {
270 // Allow the target to determine this after knowing the frame size.
271 FrameIndexEliminationScavenging =
272 (RS && !FrameIndexVirtualScavenging) ||
273 TRI->requiresFrameIndexReplacementScavenging(MF);
274
275 if (TRI->eliminateFrameIndicesBackwards())
276 replaceFrameIndicesBackward(MF);
277 else
278 replaceFrameIndices(MF);
279 }
280
281 // If register scavenging is needed, as we've enabled doing it as a
282 // post-pass, scavenge the virtual registers that frame index elimination
283 // inserted.
284 if (TRI->requiresRegisterScavenging(MF) && FrameIndexVirtualScavenging)
286
287 // Warn on stack size when we exceeds the given limit.
288 MachineFrameInfo &MFI = MF.getFrameInfo();
289 uint64_t StackSize = MFI.getStackSize();
290
291 uint64_t Threshold = TFI->getStackThreshold();
292 if (MF.getFunction().hasFnAttribute("warn-stack-size")) {
293 bool Failed = MF.getFunction()
294 .getFnAttribute("warn-stack-size")
296 .getAsInteger(10, Threshold);
297 // Verifier should have caught this.
298 assert(!Failed && "Invalid warn-stack-size fn attr value");
299 (void)Failed;
300 }
301 uint64_t UnsafeStackSize = MFI.getUnsafeStackSize();
302 if (MF.getFunction().hasFnAttribute(Attribute::SafeStack))
303 StackSize += UnsafeStackSize;
304
305 if (StackSize > Threshold) {
306 DiagnosticInfoStackSize DiagStackSize(F, StackSize, Threshold, DS_Warning);
307 F.getContext().diagnose(DiagStackSize);
308 int64_t SpillSize = 0;
309 for (int Idx = MFI.getObjectIndexBegin(), End = MFI.getObjectIndexEnd();
310 Idx != End; ++Idx) {
311 if (MFI.isSpillSlotObjectIndex(Idx))
312 SpillSize += MFI.getObjectSize(Idx);
313 }
314
315 [[maybe_unused]] float SpillPct =
316 static_cast<float>(SpillSize) / static_cast<float>(StackSize);
318 dbgs() << formatv("{0}/{1} ({3:P}) spills, {2}/{1} ({4:P}) variables",
319 SpillSize, StackSize, StackSize - SpillSize, SpillPct,
320 1.0f - SpillPct));
321 if (UnsafeStackSize != 0) {
322 LLVM_DEBUG(dbgs() << formatv(", {0}/{2} ({1:P}) unsafe stack",
323 UnsafeStackSize,
324 static_cast<float>(UnsafeStackSize) /
325 static_cast<float>(StackSize),
326 StackSize));
327 }
328 LLVM_DEBUG(dbgs() << "\n");
329 }
330
331 ORE->emit([&]() {
332 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "StackSize",
334 &MF.front())
335 << ore::NV("NumStackBytes", StackSize)
336 << " stack bytes in function '"
337 << ore::NV("Function", MF.getFunction().getName()) << "'";
338 });
339
340 // Emit any remarks implemented for the target, based on final frame layout.
341 TFI->emitRemarks(MF, ORE);
342
343 delete RS;
344 SaveBlocks.clear();
345 RestoreBlocks.clear();
346 MFI.clearSavePoints();
347 MFI.clearRestorePoints();
348 return true;
349}
350
351/// runOnMachineFunction - Insert prolog/epilog code and replace abstract
352/// frame indexes with appropriate references.
353bool PEILegacy::runOnMachineFunction(MachineFunction &MF) {
354 MachineOptimizationRemarkEmitter *ORE =
355 &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE();
356 return PEIImpl(ORE).run(MF);
357}
358
359PreservedAnalyses
369
370/// Calculate the MaxCallFrameSize variable for the function's frame
371/// information and eliminate call frame pseudo instructions.
372void PEIImpl::calculateCallFrameInfo(MachineFunction &MF) {
375 MachineFrameInfo &MFI = MF.getFrameInfo();
376
377 // Get the function call frame set-up and tear-down instruction opcode
378 unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode();
379 unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode();
380
381 // Early exit for targets which have no call frame setup/destroy pseudo
382 // instructions.
383 if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u)
384 return;
385
386 // (Re-)Compute the MaxCallFrameSize.
387 [[maybe_unused]] uint64_t MaxCFSIn =
389 std::vector<MachineBasicBlock::iterator> FrameSDOps;
390 MFI.computeMaxCallFrameSize(MF, &FrameSDOps);
391 assert(MFI.getMaxCallFrameSize() <= MaxCFSIn &&
392 "Recomputing MaxCFS gave a larger value.");
393 assert((FrameSDOps.empty() || MF.getFrameInfo().adjustsStack()) &&
394 "AdjustsStack not set in presence of a frame pseudo instruction.");
395
396 if (TFI->canSimplifyCallFramePseudos(MF)) {
397 // If call frames are not being included as part of the stack frame, and
398 // the target doesn't indicate otherwise, remove the call frame pseudos
399 // here. The sub/add sp instruction pairs are still inserted, but we don't
400 // need to track the SP adjustment for frame index elimination.
401 for (MachineBasicBlock::iterator I : FrameSDOps)
402 TFI->eliminateCallFramePseudoInstr(MF, *I->getParent(), I);
403
404 // We can't track the call frame size after call frame pseudos have been
405 // eliminated. Set it to zero everywhere to keep MachineVerifier happy.
406 for (MachineBasicBlock &MBB : MF)
407 MBB.setCallFrameSize(0);
408 }
409}
410
411/// Compute the sets of entry and return blocks for saving and restoring
412/// callee-saved registers, and placing prolog and epilog code.
413void PEIImpl::calculateSaveRestoreBlocks(MachineFunction &MF) {
414 const MachineFrameInfo &MFI = MF.getFrameInfo();
415 // Even when we do not change any CSR, we still want to insert the
416 // prologue and epilogue of the function.
417 // So set the save points for those.
418
419 // Use the points found by shrink-wrapping, if any.
420 if (!MFI.getSavePoints().empty()) {
421 assert(MFI.getSavePoints().size() == 1 &&
422 "Multiple save points are not yet supported!");
423 const auto &SavePoint = *MFI.getSavePoints().begin();
424 SaveBlocks.push_back(SavePoint.first);
425 assert(MFI.getRestorePoints().size() == 1 &&
426 "Multiple restore points are not yet supported!");
427 const auto &RestorePoint = *MFI.getRestorePoints().begin();
428 MachineBasicBlock *RestoreBlock = RestorePoint.first;
429 // If RestoreBlock does not have any successor and is not a return block
430 // then the end point is unreachable and we do not need to insert any
431 // epilogue.
432 if (!RestoreBlock->succ_empty() || RestoreBlock->isReturnBlock())
433 RestoreBlocks.push_back(RestoreBlock);
434 return;
435 }
436
437 // Save refs to entry and return blocks.
438 SaveBlocks.push_back(&MF.front());
439 for (MachineBasicBlock &MBB : MF) {
440 if (MBB.isEHFuncletEntry())
441 SaveBlocks.push_back(&MBB);
442 if (MBB.isReturnBlock())
443 RestoreBlocks.push_back(&MBB);
444 }
445}
446
448 const BitVector &SavedRegs) {
449 if (SavedRegs.empty())
450 return;
451
452 const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo();
453 const MCPhysReg *CSRegs = F.getRegInfo().getCalleeSavedRegs();
454 BitVector CSMask(SavedRegs.size());
455
456 for (unsigned i = 0; CSRegs[i]; ++i)
457 CSMask.set(CSRegs[i]);
458
459 std::vector<CalleeSavedInfo> CSI;
460 for (unsigned i = 0; CSRegs[i]; ++i) {
461 unsigned Reg = CSRegs[i];
462 if (SavedRegs.test(Reg)) {
463 bool SavedSuper = false;
464 for (const MCPhysReg &SuperReg : RegInfo->superregs(Reg)) {
465 // Some backends set all aliases for some registers as saved, such as
466 // Mips's $fp, so they appear in SavedRegs but not CSRegs.
467 if (SavedRegs.test(SuperReg) && CSMask.test(SuperReg)) {
468 SavedSuper = true;
469 break;
470 }
471 }
472
473 if (!SavedSuper)
474 CSI.push_back(CalleeSavedInfo(Reg));
475 }
476 }
477
478 const TargetFrameLowering *TFI = F.getSubtarget().getFrameLowering();
479 MachineFrameInfo &MFI = F.getFrameInfo();
480 if (!TFI->assignCalleeSavedSpillSlots(F, RegInfo, CSI)) {
481 // If target doesn't implement this, use generic code.
482
483 if (CSI.empty())
484 return; // Early exit if no callee saved registers are modified!
485
486 unsigned NumFixedSpillSlots;
487 const TargetFrameLowering::SpillSlot *FixedSpillSlots =
488 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots);
489
490 // Now that we know which registers need to be saved and restored, allocate
491 // stack slots for them.
492 for (auto &CS : CSI) {
493 // If the target has spilled this register to another register or already
494 // handled it , we don't need to allocate a stack slot.
495 if (CS.isSpilledToReg())
496 continue;
497
498 MCRegister Reg = CS.getReg();
499 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
500
501 int FrameIdx;
502 if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) {
503 CS.setFrameIdx(FrameIdx);
504 continue;
505 }
506
507 // Check to see if this physreg must be spilled to a particular stack slot
508 // on this target.
509 const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots;
510 while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots &&
511 FixedSlot->Reg != Reg)
512 ++FixedSlot;
513
514 unsigned Size = RegInfo->getSpillSize(*RC);
515 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) {
516 // Nope, just spill it anywhere convenient.
517 Align Alignment = RegInfo->getSpillAlign(*RC);
518 // We may not be able to satisfy the desired alignment specification of
519 // the TargetRegisterClass if the stack alignment is smaller. Use the
520 // min.
521 Alignment = std::min(Alignment, TFI->getStackAlign());
522 FrameIdx = MFI.CreateStackObject(Size, Alignment, true, nullptr,
523 RegInfo->getSpillStackID(*RC));
524 MFI.setIsCalleeSavedObjectIndex(FrameIdx, true);
525 } else {
526 // Spill it to the stack where we must.
527 FrameIdx = MFI.CreateFixedSpillStackObject(Size, FixedSlot->Offset);
528 }
529
530 CS.setFrameIdx(FrameIdx);
531 }
532 }
533
534 MFI.setCalleeSavedInfo(CSI);
535}
536
537/// Helper function to update the liveness information for the callee-saved
538/// registers.
540 MachineFrameInfo &MFI = MF.getFrameInfo();
541 // Visited will contain all the basic blocks that are in the region
542 // where the callee saved registers are alive:
543 // - Anything that is not Save or Restore -> LiveThrough.
544 // - Save -> LiveIn.
545 // - Restore -> LiveOut.
546 // The live-out is not attached to the block, so no need to keep
547 // Restore in this set.
550 MachineBasicBlock *Entry = &MF.front();
551
552 assert(MFI.getSavePoints().size() < 2 &&
553 "Multiple save points not yet supported!");
554 MachineBasicBlock *Save = MFI.getSavePoints().empty()
555 ? nullptr
556 : (*MFI.getSavePoints().begin()).first;
557
558 if (!Save)
559 Save = Entry;
560
561 if (Entry != Save) {
562 WorkList.push_back(Entry);
563 Visited.insert(Entry);
564 }
565 Visited.insert(Save);
566
567 assert(MFI.getRestorePoints().size() < 2 &&
568 "Multiple restore points not yet supported!");
569 MachineBasicBlock *Restore = MFI.getRestorePoints().empty()
570 ? nullptr
571 : (*MFI.getRestorePoints().begin()).first;
572 if (Restore)
573 // By construction Restore cannot be visited, otherwise it
574 // means there exists a path to Restore that does not go
575 // through Save.
576 WorkList.push_back(Restore);
577
578 while (!WorkList.empty()) {
579 const MachineBasicBlock *CurBB = WorkList.pop_back_val();
580 // By construction, the region that is after the save point is
581 // dominated by the Save and post-dominated by the Restore.
582 if (CurBB == Save && Save != Restore)
583 continue;
584 // Enqueue all the successors not already visited.
585 // Those are by construction either before Save or after Restore.
586 for (MachineBasicBlock *SuccBB : CurBB->successors())
587 if (Visited.insert(SuccBB).second)
588 WorkList.push_back(SuccBB);
589 }
590
591 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
592
594 for (const CalleeSavedInfo &I : CSI) {
595 for (MachineBasicBlock *MBB : Visited) {
596 MCRegister Reg = I.getReg();
597 // Add the callee-saved register as live-in.
598 // It's killed at the spill.
599 if (!MRI.isReserved(Reg) && !MBB->isLiveIn(Reg))
600 MBB->addLiveIn(Reg);
601 }
602 // If callee-saved register is spilled to another register rather than
603 // spilling to stack, the destination register has to be marked as live for
604 // each MBB between the prologue and epilogue so that it is not clobbered
605 // before it is reloaded in the epilogue. The Visited set contains all
606 // blocks outside of the region delimited by prologue/epilogue.
607 if (I.isSpilledToReg()) {
608 for (MachineBasicBlock &MBB : MF) {
609 if (Visited.count(&MBB))
610 continue;
611 MCRegister DstReg = I.getDstReg();
612 if (!MBB.isLiveIn(DstReg))
613 MBB.addLiveIn(DstReg);
614 }
615 }
616 }
617}
618
619/// Insert spill code for the callee-saved registers used in the function.
620static void insertCSRSaves(MachineBasicBlock &SaveBlock,
622 MachineFunction &MF = *SaveBlock.getParent();
626
627 MachineBasicBlock::iterator I = SaveBlock.begin();
628 if (!TFI->spillCalleeSavedRegisters(SaveBlock, I, CSI, TRI)) {
629 for (const CalleeSavedInfo &CS : CSI) {
630 TFI->spillCalleeSavedRegister(SaveBlock, I, CS, TII, TRI);
631 }
632 }
633}
634
635/// Insert restore code for the callee-saved registers used in the function.
636static void insertCSRRestores(MachineBasicBlock &RestoreBlock,
637 std::vector<CalleeSavedInfo> &CSI) {
638 MachineFunction &MF = *RestoreBlock.getParent();
642
643 // Restore all registers immediately before the return and any
644 // terminators that precede it.
646
647 if (!TFI->restoreCalleeSavedRegisters(RestoreBlock, I, CSI, TRI)) {
648 for (const CalleeSavedInfo &CI : reverse(CSI)) {
649 TFI->restoreCalleeSavedRegister(RestoreBlock, I, CI, TII, TRI);
650 }
651 }
652}
653
654void PEIImpl::spillCalleeSavedRegs(MachineFunction &MF) {
655 // We can't list this requirement in getRequiredProperties because some
656 // targets (WebAssembly) use virtual registers past this point, and the pass
657 // pipeline is set up without giving the passes a chance to look at the
658 // TargetMachine.
659 // FIXME: Find a way to express this in getRequiredProperties.
660 assert(MF.getProperties().hasNoVRegs());
661
662 const Function &F = MF.getFunction();
663 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
664 MachineFrameInfo &MFI = MF.getFrameInfo();
665
666 // Determine which of the registers in the callee save list should be saved.
667 BitVector SavedRegs;
668 TFI->determineCalleeSaves(MF, SavedRegs, RS);
669
670 // Assign stack slots for any callee-saved registers that must be spilled.
671 assignCalleeSavedSpillSlots(MF, SavedRegs);
672
673 // Add the code to save and restore the callee saved registers.
674 if (!F.hasFnAttribute(Attribute::Naked)) {
675 MFI.setCalleeSavedInfoValid(true);
676
677 std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo();
678
679 // Fill SavePoints and RestorePoints with CalleeSavedRegisters
680 if (!MFI.getSavePoints().empty()) {
681 SaveRestorePoints SaveRestorePts;
682 for (const auto &SavePoint : MFI.getSavePoints())
683 SaveRestorePts.insert({SavePoint.first, CSI});
684 MFI.setSavePoints(std::move(SaveRestorePts));
685
686 SaveRestorePts.clear();
687 for (const auto &RestorePoint : MFI.getRestorePoints())
688 SaveRestorePts.insert({RestorePoint.first, CSI});
689 MFI.setRestorePoints(std::move(SaveRestorePts));
690 }
691
692 if (!CSI.empty()) {
693 if (!MFI.hasCalls())
694 NumLeafFuncWithSpills++;
695
696 for (MachineBasicBlock *SaveBlock : SaveBlocks)
697 insertCSRSaves(*SaveBlock, CSI);
698
699 // Update the live-in information of all the blocks up to the save point.
700 updateLiveness(MF);
701
702 for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
703 insertCSRRestores(*RestoreBlock, CSI);
704 }
705 }
706}
707
708/// AdjustStackOffset - Helper function used to adjust the stack frame offset.
709static inline void AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx,
710 bool StackGrowsDown, int64_t &Offset,
711 Align &MaxAlign) {
712 // If the stack grows down, add the object size to find the lowest address.
713 if (StackGrowsDown)
714 Offset += MFI.getObjectSize(FrameIdx);
715
716 Align Alignment = MFI.getObjectAlign(FrameIdx);
717
718 // If the alignment of this object is greater than that of the stack, then
719 // increase the stack alignment to match.
720 MaxAlign = std::max(MaxAlign, Alignment);
721
722 // Adjust to alignment boundary.
723 Offset = alignTo(Offset, Alignment);
724
725 if (StackGrowsDown) {
726 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset
727 << "]\n");
728 MFI.setObjectOffset(FrameIdx, -Offset); // Set the computed offset
729 } else {
730 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset
731 << "]\n");
732 MFI.setObjectOffset(FrameIdx, Offset);
733 Offset += MFI.getObjectSize(FrameIdx);
734 }
735}
736
737/// Compute which bytes of fixed and callee-save stack area are unused and keep
738/// track of them in StackBytesFree.
740 bool StackGrowsDown,
741 int64_t FixedCSEnd,
742 BitVector &StackBytesFree) {
743 // Avoid undefined int64_t -> int conversion below in extreme case.
744 if (FixedCSEnd > std::numeric_limits<int>::max())
745 return;
746
747 StackBytesFree.resize(FixedCSEnd, true);
748
749 SmallVector<int, 16> AllocatedFrameSlots;
750 // Add fixed objects.
751 for (int i = MFI.getObjectIndexBegin(); i != 0; ++i)
752 // StackSlot scavenging is only implemented for the default stack.
754 AllocatedFrameSlots.push_back(i);
755 // Add callee-save objects if there are any.
756 for (int i = MFI.getObjectIndexBegin(); i < MFI.getObjectIndexEnd(); i++)
757 if (MFI.isCalleeSavedObjectIndex(i) &&
759 AllocatedFrameSlots.push_back(i);
760
761 for (int i : AllocatedFrameSlots) {
762 // These are converted from int64_t, but they should always fit in int
763 // because of the FixedCSEnd check above.
764 int ObjOffset = MFI.getObjectOffset(i);
765 int ObjSize = MFI.getObjectSize(i);
766 int ObjStart, ObjEnd;
767 if (StackGrowsDown) {
768 // ObjOffset is negative when StackGrowsDown is true.
769 ObjStart = -ObjOffset - ObjSize;
770 ObjEnd = -ObjOffset;
771 } else {
772 ObjStart = ObjOffset;
773 ObjEnd = ObjOffset + ObjSize;
774 }
775 // Ignore fixed holes that are in the previous stack frame.
776 if (ObjEnd > 0)
777 StackBytesFree.reset(ObjStart, ObjEnd);
778 }
779}
780
781/// Assign frame object to an unused portion of the stack in the fixed stack
782/// object range. Return true if the allocation was successful.
783static inline bool scavengeStackSlot(MachineFrameInfo &MFI, int FrameIdx,
784 bool StackGrowsDown, Align MaxAlign,
785 BitVector &StackBytesFree) {
786 if (MFI.isVariableSizedObjectIndex(FrameIdx))
787 return false;
788
789 if (StackBytesFree.none()) {
790 // clear it to speed up later scavengeStackSlot calls to
791 // StackBytesFree.none()
792 StackBytesFree.clear();
793 return false;
794 }
795
796 Align ObjAlign = MFI.getObjectAlign(FrameIdx);
797 if (ObjAlign > MaxAlign)
798 return false;
799
800 int64_t ObjSize = MFI.getObjectSize(FrameIdx);
801 int FreeStart;
802 for (FreeStart = StackBytesFree.find_first(); FreeStart != -1;
803 FreeStart = StackBytesFree.find_next(FreeStart)) {
804
805 // Check that free space has suitable alignment.
806 unsigned ObjStart = StackGrowsDown ? FreeStart + ObjSize : FreeStart;
807 if (alignTo(ObjStart, ObjAlign) != ObjStart)
808 continue;
809
810 if (FreeStart + ObjSize > StackBytesFree.size())
811 return false;
812
813 bool AllBytesFree = true;
814 for (unsigned Byte = 0; Byte < ObjSize; ++Byte)
815 if (!StackBytesFree.test(FreeStart + Byte)) {
816 AllBytesFree = false;
817 break;
818 }
819 if (AllBytesFree)
820 break;
821 }
822
823 if (FreeStart == -1)
824 return false;
825
826 if (StackGrowsDown) {
827 int ObjStart = -(FreeStart + ObjSize);
828 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP["
829 << ObjStart << "]\n");
830 MFI.setObjectOffset(FrameIdx, ObjStart);
831 } else {
832 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP["
833 << FreeStart << "]\n");
834 MFI.setObjectOffset(FrameIdx, FreeStart);
835 }
836
837 StackBytesFree.reset(FreeStart, FreeStart + ObjSize);
838 return true;
839}
840
841/// AssignProtectedObjSet - Helper function to assign large stack objects (i.e.,
842/// those required to be close to the Stack Protector) to stack offsets.
843static void AssignProtectedObjSet(const StackObjSet &UnassignedObjs,
844 SmallSet<int, 16> &ProtectedObjs,
845 MachineFrameInfo &MFI, bool StackGrowsDown,
846 int64_t &Offset, Align &MaxAlign) {
847
848 for (int i : UnassignedObjs) {
849 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign);
850 ProtectedObjs.insert(i);
851 }
852}
853
854/// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the
855/// abstract stack objects.
856void PEIImpl::calculateFrameObjectOffsets(MachineFunction &MF) {
857 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
858
859 bool StackGrowsDown =
861
862 // Loop over all of the stack objects, assigning sequential addresses...
863 MachineFrameInfo &MFI = MF.getFrameInfo();
864
865 // Start at the beginning of the local area.
866 // The Offset is the distance from the stack top in the direction
867 // of stack growth -- so it's always nonnegative.
868 int LocalAreaOffset = TFI.getOffsetOfLocalArea();
869 if (StackGrowsDown)
870 LocalAreaOffset = -LocalAreaOffset;
871 assert(LocalAreaOffset >= 0
872 && "Local area offset should be in direction of stack growth");
873 int64_t Offset = LocalAreaOffset;
874
875#ifdef EXPENSIVE_CHECKS
876 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i)
877 if (!MFI.isDeadObjectIndex(i) &&
879 assert(MFI.getObjectAlign(i) <= MFI.getMaxAlign() &&
880 "MaxAlignment is invalid");
881#endif
882
883 // If there are fixed sized objects that are preallocated in the local area,
884 // non-fixed objects can't be allocated right at the start of local area.
885 // Adjust 'Offset' to point to the end of last fixed sized preallocated
886 // object.
887 for (int i = MFI.getObjectIndexBegin(); i != 0; ++i) {
888 // Only allocate objects on the default stack.
890 continue;
891
892 int64_t FixedOff;
893 if (StackGrowsDown) {
894 // The maximum distance from the stack pointer is at lower address of
895 // the object -- which is given by offset. For down growing stack
896 // the offset is negative, so we negate the offset to get the distance.
897 FixedOff = -MFI.getObjectOffset(i);
898 } else {
899 // The maximum distance from the start pointer is at the upper
900 // address of the object.
901 FixedOff = MFI.getObjectOffset(i) + MFI.getObjectSize(i);
902 }
903 if (FixedOff > Offset) Offset = FixedOff;
904 }
905
906 Align MaxAlign = MFI.getMaxAlign();
907 // First assign frame offsets to stack objects that are used to spill
908 // callee saved registers.
909 auto AllFIs = seq(MFI.getObjectIndexBegin(), MFI.getObjectIndexEnd());
910 for (int FI : reverse_conditionally(AllFIs, /*Reverse=*/!StackGrowsDown)) {
911 // Only allocate objects on the default stack.
912 if (!MFI.isCalleeSavedObjectIndex(FI) ||
914 continue;
915
916 // TODO: should this just be if (MFI.isDeadObjectIndex(FI))
917 if (!StackGrowsDown && MFI.isDeadObjectIndex(FI))
918 continue;
919
920 AdjustStackOffset(MFI, FI, StackGrowsDown, Offset, MaxAlign);
921 }
922
923 assert(MaxAlign == MFI.getMaxAlign() &&
924 "MFI.getMaxAlign should already account for all callee-saved "
925 "registers without a fixed stack slot");
926
927 // FixedCSEnd is the stack offset to the end of the fixed and callee-save
928 // stack area.
929 int64_t FixedCSEnd = Offset;
930
931 // Make sure the special register scavenging spill slot is closest to the
932 // incoming stack pointer if a frame pointer is required and is closer
933 // to the incoming rather than the final stack pointer.
934 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
935 bool EarlyScavengingSlots = TFI.allocateScavengingFrameIndexesNearIncomingSP(MF);
936 if (RS && EarlyScavengingSlots) {
937 SmallVector<int, 2> SFIs;
939 for (int SFI : SFIs)
940 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
941 }
942
943 // FIXME: Once this is working, then enable flag will change to a target
944 // check for whether the frame is large enough to want to use virtual
945 // frame index registers. Functions which don't want/need this optimization
946 // will continue to use the existing code path.
948 Align Alignment = MFI.getLocalFrameMaxAlign();
949
950 // Adjust to alignment boundary.
951 Offset = alignTo(Offset, Alignment);
952
953 LLVM_DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n");
954
955 // Resolve offsets for objects in the local block.
956 for (unsigned i = 0, e = MFI.getLocalFrameObjectCount(); i != e; ++i) {
957 std::pair<int, int64_t> Entry = MFI.getLocalFrameObjectMap(i);
958 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second;
959 LLVM_DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" << FIOffset
960 << "]\n");
961 MFI.setObjectOffset(Entry.first, FIOffset);
962 }
963 // Allocate the local block
964 Offset += MFI.getLocalFrameSize();
965
966 MaxAlign = std::max(Alignment, MaxAlign);
967 }
968
969 // Retrieve the Exception Handler registration node.
970 int EHRegNodeFrameIndex = std::numeric_limits<int>::max();
971 if (const WinEHFuncInfo *FuncInfo = MF.getWinEHFuncInfo())
972 EHRegNodeFrameIndex = FuncInfo->EHRegNodeFrameIndex;
973
974 // Make sure that the stack protector comes before the local variables on the
975 // stack.
976 SmallSet<int, 16> ProtectedObjs;
977 if (MFI.hasStackProtectorIndex()) {
978 int StackProtectorFI = MFI.getStackProtectorIndex();
979 StackObjSet LargeArrayObjs;
980 StackObjSet SmallArrayObjs;
981 StackObjSet AddrOfObjs;
982
983 // If we need a stack protector, we need to make sure that
984 // LocalStackSlotPass didn't already allocate a slot for it.
985 // If we are told to use the LocalStackAllocationBlock, the stack protector
986 // is expected to be already pre-allocated.
987 if (MFI.getStackID(StackProtectorFI) != TargetStackID::Default) {
988 // If the stack protector isn't on the default stack then it's up to the
989 // target to set the stack offset.
990 assert(MFI.getObjectOffset(StackProtectorFI) != 0 &&
991 "Offset of stack protector on non-default stack expected to be "
992 "already set.");
994 "Stack protector on non-default stack expected to not be "
995 "pre-allocated by LocalStackSlotPass.");
996 } else if (!MFI.getUseLocalStackAllocationBlock()) {
997 AdjustStackOffset(MFI, StackProtectorFI, StackGrowsDown, Offset,
998 MaxAlign);
999 } else if (!MFI.isObjectPreAllocated(MFI.getStackProtectorIndex())) {
1001 "Stack protector not pre-allocated by LocalStackSlotPass.");
1002 }
1003
1004 // Assign large stack objects first.
1005 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1007 continue;
1008 if (MFI.isCalleeSavedObjectIndex(i))
1009 continue;
1010 if (RS && RS->isScavengingFrameIndex((int)i))
1011 continue;
1012 if (MFI.isDeadObjectIndex(i))
1013 continue;
1014 if (StackProtectorFI == (int)i || EHRegNodeFrameIndex == (int)i)
1015 continue;
1016 // Only allocate objects on the default stack.
1017 if (MFI.getStackID(i) != TargetStackID::Default)
1018 continue;
1019
1020 switch (MFI.getObjectSSPLayout(i)) {
1022 continue;
1024 SmallArrayObjs.insert(i);
1025 continue;
1027 AddrOfObjs.insert(i);
1028 continue;
1030 LargeArrayObjs.insert(i);
1031 continue;
1032 }
1033 llvm_unreachable("Unexpected SSPLayoutKind.");
1034 }
1035
1036 // We expect **all** the protected stack objects to be pre-allocated by
1037 // LocalStackSlotPass. If it turns out that PEI still has to allocate some
1038 // of them, we may end up messing up the expected order of the objects.
1040 !(LargeArrayObjs.empty() && SmallArrayObjs.empty() &&
1041 AddrOfObjs.empty()))
1042 llvm_unreachable("Found protected stack objects not pre-allocated by "
1043 "LocalStackSlotPass.");
1044
1045 AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
1046 Offset, MaxAlign);
1047 AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown,
1048 Offset, MaxAlign);
1049 AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown,
1050 Offset, MaxAlign);
1051 }
1052
1053 SmallVector<int, 8> ObjectsToAllocate;
1054
1055 // Then prepare to assign frame offsets to stack objects that are not used to
1056 // spill callee saved registers.
1057 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
1059 continue;
1060 if (MFI.isCalleeSavedObjectIndex(i))
1061 continue;
1062 if (RS && RS->isScavengingFrameIndex((int)i))
1063 continue;
1064 if (MFI.isDeadObjectIndex(i))
1065 continue;
1066 if (MFI.getStackProtectorIndex() == (int)i || EHRegNodeFrameIndex == (int)i)
1067 continue;
1068 if (ProtectedObjs.count(i))
1069 continue;
1070 // Only allocate objects on the default stack.
1071 if (MFI.getStackID(i) != TargetStackID::Default)
1072 continue;
1073
1074 // Add the objects that we need to allocate to our working set.
1075 ObjectsToAllocate.push_back(i);
1076 }
1077
1078 // Allocate the EH registration node first if one is present.
1079 if (EHRegNodeFrameIndex != std::numeric_limits<int>::max())
1080 AdjustStackOffset(MFI, EHRegNodeFrameIndex, StackGrowsDown, Offset,
1081 MaxAlign);
1082
1083 // Give the targets a chance to order the objects the way they like it.
1084 if (MF.getTarget().getOptLevel() != CodeGenOptLevel::None &&
1086 TFI.orderFrameObjects(MF, ObjectsToAllocate);
1087
1088 // Keep track of which bytes in the fixed and callee-save range are used so we
1089 // can use the holes when allocating later stack objects. Only do this if
1090 // stack protector isn't being used and the target requests it and we're
1091 // optimizing.
1092 BitVector StackBytesFree;
1093 if (!ObjectsToAllocate.empty() &&
1094 MF.getTarget().getOptLevel() != CodeGenOptLevel::None &&
1096 computeFreeStackSlots(MFI, StackGrowsDown, FixedCSEnd, StackBytesFree);
1097
1098 // Now walk the objects and actually assign base offsets to them.
1099 for (auto &Object : ObjectsToAllocate)
1100 if (!scavengeStackSlot(MFI, Object, StackGrowsDown, MaxAlign,
1101 StackBytesFree))
1102 AdjustStackOffset(MFI, Object, StackGrowsDown, Offset, MaxAlign);
1103
1104 // Make sure the special register scavenging spill slot is closest to the
1105 // stack pointer.
1106 if (RS && !EarlyScavengingSlots) {
1107 SmallVector<int, 2> SFIs;
1108 RS->getScavengingFrameIndices(SFIs);
1109 for (int SFI : SFIs)
1110 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign);
1111 }
1112
1114 // If we have reserved argument space for call sites in the function
1115 // immediately on entry to the current function, count it as part of the
1116 // overall stack size.
1117 if (MFI.adjustsStack() && TFI.hasReservedCallFrame(MF))
1118 Offset += MFI.getMaxCallFrameSize();
1119
1120 // Round up the size to a multiple of the alignment. If the function has
1121 // any calls or alloca's, align to the target's StackAlignment value to
1122 // ensure that the callee's frame or the alloca data is suitably aligned;
1123 // otherwise, for leaf functions, align to the TransientStackAlignment
1124 // value.
1125 Align StackAlign;
1126 if (MFI.adjustsStack() || MFI.hasVarSizedObjects() ||
1127 (RegInfo->hasStackRealignment(MF) && MFI.getObjectIndexEnd() != 0))
1128 StackAlign = TFI.getStackAlign();
1129 else
1130 StackAlign = TFI.getTransientStackAlign();
1131
1132 // If the frame pointer is eliminated, all frame offsets will be relative to
1133 // SP not FP. Align to MaxAlign so this works.
1134 StackAlign = std::max(StackAlign, MaxAlign);
1135 int64_t OffsetBeforeAlignment = Offset;
1136 Offset = alignTo(Offset, StackAlign);
1137
1138 // If we have increased the offset to fulfill the alignment constrants,
1139 // then the scavenging spill slots may become harder to reach from the
1140 // stack pointer, float them so they stay close.
1141 if (StackGrowsDown && OffsetBeforeAlignment != Offset && RS &&
1142 !EarlyScavengingSlots) {
1143 SmallVector<int, 2> SFIs;
1144 RS->getScavengingFrameIndices(SFIs);
1145 LLVM_DEBUG(if (!SFIs.empty()) llvm::dbgs()
1146 << "Adjusting emergency spill slots!\n";);
1147 int64_t Delta = Offset - OffsetBeforeAlignment;
1148 for (int SFI : SFIs) {
1150 << "Adjusting offset of emergency spill slot #" << SFI
1151 << " from " << MFI.getObjectOffset(SFI););
1152 MFI.setObjectOffset(SFI, MFI.getObjectOffset(SFI) - Delta);
1153 LLVM_DEBUG(llvm::dbgs() << " to " << MFI.getObjectOffset(SFI) << "\n";);
1154 }
1155 }
1156 }
1157
1158 // Update frame info to pretend that this is part of the stack...
1159 int64_t StackSize = Offset - LocalAreaOffset;
1160 MFI.setStackSize(StackSize);
1161 NumBytesStackSpace += StackSize;
1162}
1163
1164/// insertPrologEpilogCode - Scan the function for modified callee saved
1165/// registers, insert spill code for these callee saved registers, then add
1166/// prolog and epilog code to the function.
1167void PEIImpl::insertPrologEpilogCode(MachineFunction &MF) {
1168 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1169
1170 // Add prologue to the function...
1171 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1172 TFI.emitPrologue(MF, *SaveBlock);
1173
1174 // Add epilogue to restore the callee-save registers in each exiting block.
1175 for (MachineBasicBlock *RestoreBlock : RestoreBlocks)
1176 TFI.emitEpilogue(MF, *RestoreBlock);
1177
1178 // Zero call used registers before restoring callee-saved registers.
1179 insertZeroCallUsedRegs(MF);
1180
1181 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1182 TFI.inlineStackProbe(MF, *SaveBlock);
1183
1184 // Emit additional code that is required to support segmented stacks, if
1185 // we've been asked for it. This, when linked with a runtime with support
1186 // for segmented stacks (libgcc is one), will result in allocating stack
1187 // space in small chunks instead of one large contiguous block.
1188 if (MF.shouldSplitStack()) {
1189 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1190 TFI.adjustForSegmentedStacks(MF, *SaveBlock);
1191 }
1192
1193 // Emit additional code that is required to explicitly handle the stack in
1194 // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The
1195 // approach is rather similar to that of Segmented Stacks, but it uses a
1196 // different conditional check and another BIF for allocating more stack
1197 // space.
1198 if (MF.getFunction().getCallingConv() == CallingConv::HiPE)
1199 for (MachineBasicBlock *SaveBlock : SaveBlocks)
1200 TFI.adjustForHiPEPrologue(MF, *SaveBlock);
1201}
1202
1203/// insertZeroCallUsedRegs - Zero out call used registers.
1204void PEIImpl::insertZeroCallUsedRegs(MachineFunction &MF) {
1205 const Function &F = MF.getFunction();
1206
1207 if (!F.hasFnAttribute("zero-call-used-regs"))
1208 return;
1209
1210 using namespace ZeroCallUsedRegs;
1211
1212 ZeroCallUsedRegsKind ZeroRegsKind =
1213 StringSwitch<ZeroCallUsedRegsKind>(
1214 F.getFnAttribute("zero-call-used-regs").getValueAsString())
1215 .Case("skip", ZeroCallUsedRegsKind::Skip)
1216 .Case("used-gpr-arg", ZeroCallUsedRegsKind::UsedGPRArg)
1217 .Case("used-gpr", ZeroCallUsedRegsKind::UsedGPR)
1218 .Case("used-arg", ZeroCallUsedRegsKind::UsedArg)
1219 .Case("used", ZeroCallUsedRegsKind::Used)
1220 .Case("all-gpr-arg", ZeroCallUsedRegsKind::AllGPRArg)
1221 .Case("all-gpr", ZeroCallUsedRegsKind::AllGPR)
1222 .Case("all-arg", ZeroCallUsedRegsKind::AllArg)
1223 .Case("all", ZeroCallUsedRegsKind::All);
1224
1225 if (ZeroRegsKind == ZeroCallUsedRegsKind::Skip)
1226 return;
1227
1228 const bool OnlyGPR = static_cast<unsigned>(ZeroRegsKind) & ONLY_GPR;
1229 const bool OnlyUsed = static_cast<unsigned>(ZeroRegsKind) & ONLY_USED;
1230 const bool OnlyArg = static_cast<unsigned>(ZeroRegsKind) & ONLY_ARG;
1231
1232 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1233 const BitVector AllocatableSet(TRI.getAllocatableSet(MF));
1234
1235 // Mark all used registers.
1236 BitVector UsedRegs(TRI.getNumRegs());
1237 if (OnlyUsed)
1238 for (const MachineBasicBlock &MBB : MF)
1239 for (const MachineInstr &MI : MBB) {
1240 // skip debug instructions
1241 if (MI.isDebugInstr())
1242 continue;
1243
1244 for (const MachineOperand &MO : MI.operands()) {
1245 if (!MO.isReg())
1246 continue;
1247
1248 MCRegister Reg = MO.getReg();
1249 if (AllocatableSet[Reg.id()] && !MO.isImplicit() &&
1250 (MO.isDef() || MO.isUse()))
1251 UsedRegs.set(Reg.id());
1252 }
1253 }
1254
1255 // Get a list of registers that are used.
1256 BitVector LiveIns(TRI.getNumRegs());
1257 for (const MachineBasicBlock::RegisterMaskPair &LI : MF.front().liveins())
1258 LiveIns.set(LI.PhysReg);
1259
1260 BitVector RegsToZero(TRI.getNumRegs());
1261 for (MCRegister Reg : AllocatableSet.set_bits()) {
1262 // Skip over fixed registers.
1263 if (TRI.isFixedRegister(MF, Reg))
1264 continue;
1265
1266 // Want only general purpose registers.
1267 if (OnlyGPR && !TRI.isGeneralPurposeRegister(MF, Reg))
1268 continue;
1269
1270 // Want only used registers.
1271 if (OnlyUsed && !UsedRegs[Reg.id()])
1272 continue;
1273
1274 // Want only registers used for arguments.
1275 if (OnlyArg) {
1276 if (OnlyUsed) {
1277 for (MCRegister LiveReg : LiveIns.set_bits()) {
1278 if (TRI.regsOverlap(Reg, LiveReg))
1279 RegsToZero.set(LiveReg);
1280 }
1281 continue;
1282 } else if (!TRI.isArgumentRegister(MF, Reg)) {
1283 continue;
1284 }
1285 }
1286
1287 RegsToZero.set(Reg.id());
1288 }
1289
1290 // Don't clear registers that are live when leaving the function.
1291 for (const MachineBasicBlock &MBB : MF)
1292 for (const MachineInstr &MI : MBB.terminators()) {
1293 if (!MI.isReturn())
1294 continue;
1295
1296 for (const auto &MO : MI.operands()) {
1297 if (!MO.isReg())
1298 continue;
1299
1300 MCRegister Reg = MO.getReg();
1301 if (!Reg)
1302 continue;
1303
1304 // This picks up sibling registers (e.q. %al -> %ah).
1305 // FIXME: Mixing physical registers and register units is likely a bug.
1306 for (MCRegUnit Unit : TRI.regunits(Reg))
1307 RegsToZero.reset(static_cast<unsigned>(Unit));
1308
1309 for (MCPhysReg SReg : TRI.sub_and_superregs_inclusive(Reg))
1310 RegsToZero.reset(SReg);
1311 }
1312 }
1313
1314 // Don't need to clear registers that are used/clobbered by terminating
1315 // instructions.
1316 for (const MachineBasicBlock &MBB : MF) {
1317 if (!MBB.isReturnBlock())
1318 continue;
1319
1322 ++I) {
1323 for (const MachineOperand &MO : I->operands()) {
1324 if (!MO.isReg())
1325 continue;
1326
1327 MCRegister Reg = MO.getReg();
1328 if (!Reg)
1329 continue;
1330
1331 for (const MCPhysReg Reg : TRI.sub_and_superregs_inclusive(Reg))
1332 RegsToZero.reset(Reg);
1333 }
1334 }
1335 }
1336
1337 // Don't clear registers that must be preserved.
1338 for (const MCPhysReg *CSRegs = TRI.getCalleeSavedRegs(&MF);
1339 MCPhysReg CSReg = *CSRegs; ++CSRegs)
1340 for (MCRegister Reg : TRI.sub_and_superregs_inclusive(CSReg))
1341 RegsToZero.reset(Reg.id());
1342
1343 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1344 for (MachineBasicBlock &MBB : MF)
1345 if (MBB.isReturnBlock())
1346 TFI.emitZeroCallUsedRegs(RegsToZero, MBB, RS);
1347}
1348
1349/// Replace all FrameIndex operands with physical register references and actual
1350/// offsets.
1351void PEIImpl::replaceFrameIndicesBackward(MachineFunction &MF) {
1352 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1353
1354 for (auto &MBB : MF) {
1355 int SPAdj = 0;
1356 if (!MBB.succ_empty()) {
1357 // Get the SP adjustment for the end of MBB from the start of any of its
1358 // successors. They should all be the same.
1359 assert(all_of(MBB.successors(), [&MBB](const MachineBasicBlock *Succ) {
1360 return Succ->getCallFrameSize() ==
1361 (*MBB.succ_begin())->getCallFrameSize();
1362 }));
1363 const MachineBasicBlock &FirstSucc = **MBB.succ_begin();
1364 SPAdj = TFI.alignSPAdjust(FirstSucc.getCallFrameSize());
1366 SPAdj = -SPAdj;
1367 }
1368
1369 replaceFrameIndicesBackward(&MBB, MF, SPAdj);
1370
1371 // We can't track the call frame size after call frame pseudos have been
1372 // eliminated. Set it to zero everywhere to keep MachineVerifier happy.
1374 }
1375}
1376
1377/// replaceFrameIndices - Replace all MO_FrameIndex operands with physical
1378/// register references and actual offsets.
1379void PEIImpl::replaceFrameIndices(MachineFunction &MF) {
1380 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1381
1382 for (auto &MBB : MF) {
1383 int SPAdj = TFI.alignSPAdjust(MBB.getCallFrameSize());
1385 SPAdj = -SPAdj;
1386
1387 replaceFrameIndices(&MBB, MF, SPAdj);
1388
1389 // We can't track the call frame size after call frame pseudos have been
1390 // eliminated. Set it to zero everywhere to keep MachineVerifier happy.
1392 }
1393}
1394
1395bool PEIImpl::replaceFrameIndexDebugInstr(MachineFunction &MF, MachineInstr &MI,
1396 unsigned OpIdx, int SPAdj) {
1397 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
1398 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1399 if (MI.isDebugValue()) {
1400
1401 MachineOperand &Op = MI.getOperand(OpIdx);
1402 assert(MI.isDebugOperand(&Op) &&
1403 "Frame indices can only appear as a debug operand in a DBG_VALUE*"
1404 " machine instruction");
1405 Register Reg;
1406 unsigned FrameIdx = Op.getIndex();
1407 unsigned Size = MF.getFrameInfo().getObjectSize(FrameIdx);
1408
1409 StackOffset Offset = TFI->getFrameIndexReference(MF, FrameIdx, Reg);
1410 Op.ChangeToRegister(Reg, false /*isDef*/);
1411
1412 const DIExpression *DIExpr = MI.getDebugExpression();
1413
1414 // If we have a direct DBG_VALUE, and its location expression isn't
1415 // currently complex, then adding an offset will morph it into a
1416 // complex location that is interpreted as being a memory address.
1417 // This changes a pointer-valued variable to dereference that pointer,
1418 // which is incorrect. Fix by adding DW_OP_stack_value.
1419
1420 if (MI.isNonListDebugValue()) {
1421 unsigned PrependFlags = DIExpression::ApplyOffset;
1422 if (!MI.isIndirectDebugValue() && !DIExpr->isComplex())
1423 PrependFlags |= DIExpression::StackValue;
1424
1425 // If we have DBG_VALUE that is indirect and has a Implicit location
1426 // expression need to insert a deref before prepending a Memory
1427 // location expression. Also after doing this we change the DBG_VALUE
1428 // to be direct.
1429 if (MI.isIndirectDebugValue() && DIExpr->isImplicit()) {
1430 SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size};
1431 bool WithStackValue = true;
1432 DIExpr = DIExpression::prependOpcodes(DIExpr, Ops, WithStackValue);
1433 // Make the DBG_VALUE direct.
1434 MI.getDebugOffset().ChangeToRegister(0, false);
1435 }
1436 DIExpr = TRI.prependOffsetExpression(DIExpr, PrependFlags, Offset);
1437 } else {
1438 // The debug operand at DebugOpIndex was a frame index at offset
1439 // `Offset`; now the operand has been replaced with the frame
1440 // register, we must add Offset with `register x, plus Offset`.
1441 unsigned DebugOpIndex = MI.getDebugOperandIndex(&Op);
1443 TRI.getOffsetOpcodes(Offset, Ops);
1444 DIExpr = DIExpression::appendOpsToArg(DIExpr, Ops, DebugOpIndex);
1445 }
1446 MI.getDebugExpressionOp().setMetadata(DIExpr);
1447 return true;
1448 }
1449
1450 if (MI.isDebugPHI()) {
1451 // Allow stack ref to continue onwards.
1452 return true;
1453 }
1454
1455 // TODO: This code should be commoned with the code for
1456 // PATCHPOINT. There's no good reason for the difference in
1457 // implementation other than historical accident. The only
1458 // remaining difference is the unconditional use of the stack
1459 // pointer as the base register.
1460 if (MI.getOpcode() == TargetOpcode::STATEPOINT) {
1461 assert((!MI.isDebugValue() || OpIdx == 0) &&
1462 "Frame indices can only appear as the first operand of a "
1463 "DBG_VALUE machine instruction");
1464 Register Reg;
1465 MachineOperand &Offset = MI.getOperand(OpIdx + 1);
1466 StackOffset refOffset = TFI->getFrameIndexReferencePreferSP(
1467 MF, MI.getOperand(OpIdx).getIndex(), Reg, /*IgnoreSPUpdates*/ false);
1468 assert(!refOffset.getScalable() &&
1469 "Frame offsets with a scalable component are not supported");
1470 Offset.setImm(Offset.getImm() + refOffset.getFixed() + SPAdj);
1471 MI.getOperand(OpIdx).ChangeToRegister(Reg, false /*isDef*/);
1472 return true;
1473 }
1474 return false;
1475}
1476
1477void PEIImpl::replaceFrameIndicesBackward(MachineBasicBlock *BB,
1478 MachineFunction &MF, int &SPAdj) {
1480 "getRegisterInfo() must be implemented!");
1481
1482 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1483 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1484 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
1485
1486 RegScavenger *LocalRS = FrameIndexEliminationScavenging ? RS : nullptr;
1487 if (LocalRS)
1488 LocalRS->enterBasicBlockEnd(*BB);
1489
1490 for (MachineBasicBlock::iterator I = BB->end(); I != BB->begin();) {
1491 MachineInstr &MI = *std::prev(I);
1492
1493 if (TII.isFrameInstr(MI)) {
1494 SPAdj -= TII.getSPAdjust(MI);
1495 TFI.eliminateCallFramePseudoInstr(MF, *BB, &MI);
1496 continue;
1497 }
1498
1499 // Step backwards to get the liveness state at (immedately after) MI.
1500 if (LocalRS)
1501 LocalRS->backward(I);
1502
1503 bool RemovedMI = false;
1504 for (const auto &[Idx, Op] : enumerate(MI.operands())) {
1505 if (!Op.isFI())
1506 continue;
1507
1508 if (replaceFrameIndexDebugInstr(MF, MI, Idx, SPAdj))
1509 continue;
1510
1511 // Eliminate this FrameIndex operand.
1512 RemovedMI = TRI.eliminateFrameIndex(MI, SPAdj, Idx, LocalRS);
1513 if (RemovedMI)
1514 break;
1515 }
1516
1517 if (!RemovedMI)
1518 --I;
1519 }
1520}
1521
1522void PEIImpl::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &MF,
1523 int &SPAdj) {
1525 "getRegisterInfo() must be implemented!");
1526 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1527 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo();
1528 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering();
1529
1530 bool InsideCallSequence = false;
1531
1532 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) {
1533 if (TII.isFrameInstr(*I)) {
1534 InsideCallSequence = TII.isFrameSetup(*I);
1535 SPAdj += TII.getSPAdjust(*I);
1536 I = TFI->eliminateCallFramePseudoInstr(MF, *BB, I);
1537 continue;
1538 }
1539
1540 MachineInstr &MI = *I;
1541 bool DoIncr = true;
1542 bool DidFinishLoop = true;
1543 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
1544 if (!MI.getOperand(i).isFI())
1545 continue;
1546
1547 if (replaceFrameIndexDebugInstr(MF, MI, i, SPAdj))
1548 continue;
1549
1550 // Some instructions (e.g. inline asm instructions) can have
1551 // multiple frame indices and/or cause eliminateFrameIndex
1552 // to insert more than one instruction. We need the register
1553 // scavenger to go through all of these instructions so that
1554 // it can update its register information. We keep the
1555 // iterator at the point before insertion so that we can
1556 // revisit them in full.
1557 bool AtBeginning = (I == BB->begin());
1558 if (!AtBeginning) --I;
1559
1560 // If this instruction has a FrameIndex operand, we need to
1561 // use that target machine register info object to eliminate
1562 // it.
1563 TRI.eliminateFrameIndex(MI, SPAdj, i, RS);
1564
1565 // Reset the iterator if we were at the beginning of the BB.
1566 if (AtBeginning) {
1567 I = BB->begin();
1568 DoIncr = false;
1569 }
1570
1571 DidFinishLoop = false;
1572 break;
1573 }
1574
1575 // If we are looking at a call sequence, we need to keep track of
1576 // the SP adjustment made by each instruction in the sequence.
1577 // This includes both the frame setup/destroy pseudos (handled above),
1578 // as well as other instructions that have side effects w.r.t the SP.
1579 // Note that this must come after eliminateFrameIndex, because
1580 // if I itself referred to a frame index, we shouldn't count its own
1581 // adjustment.
1582 if (DidFinishLoop && InsideCallSequence)
1583 SPAdj += TII.getSPAdjust(MI);
1584
1585 if (DoIncr && I != BB->end())
1586 ++I;
1587 }
1588}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator MBBI
This file contains the simple types necessary to represent the attributes associated with functions a...
This file implements the BitVector class.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
===- MachineOptimizationRemarkEmitter.h - Opt Diagnostics -*- C++ -*-—===//
Register Reg
Register const TargetRegisterInfo * TRI
Promote Memory to Register
Definition Mem2Reg.cpp:110
MachineInstr unsigned OpIdx
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition PassSupport.h:42
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
Definition PassSupport.h:44
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
Definition PassSupport.h:39
static void insertCSRRestores(MachineBasicBlock &RestoreBlock, std::vector< CalleeSavedInfo > &CSI)
Insert restore code for the callee-saved registers used in the function.
SmallVector< MachineBasicBlock *, 4 > MBBVector
static bool scavengeStackSlot(MachineFrameInfo &MFI, int FrameIdx, bool StackGrowsDown, Align MaxAlign, BitVector &StackBytesFree)
Assign frame object to an unused portion of the stack in the fixed stack object range.
static void insertCSRSaves(MachineBasicBlock &SaveBlock, ArrayRef< CalleeSavedInfo > CSI)
Insert spill code for the callee-saved registers used in the function.
static void AssignProtectedObjSet(const StackObjSet &UnassignedObjs, SmallSet< int, 16 > &ProtectedObjs, MachineFrameInfo &MFI, bool StackGrowsDown, int64_t &Offset, Align &MaxAlign)
AssignProtectedObjSet - Helper function to assign large stack objects (i.e., those required to be clo...
static void AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx, bool StackGrowsDown, int64_t &Offset, Align &MaxAlign)
AdjustStackOffset - Helper function used to adjust the stack frame offset.
SmallDenseMap< MachineBasicBlock *, SmallVector< MachineInstr *, 4 >, 4 > SavedDbgValuesMap
static void computeFreeStackSlots(MachineFrameInfo &MFI, bool StackGrowsDown, int64_t FixedCSEnd, BitVector &StackBytesFree)
Compute which bytes of fixed and callee-save stack area are unused and keep track of them in StackByt...
static void updateLiveness(MachineFunction &MF)
Helper function to update the liveness information for the callee-saved registers.
SmallSetVector< int, 8 > StackObjSet
StackObjSet - A set of stack object indexes.
static void stashEntryDbgValues(MachineBasicBlock &MBB, SavedDbgValuesMap &EntryDbgValues)
Stash DBG_VALUEs that describe parameters and which are placed at the start of the block.
static void assignCalleeSavedSpillSlots(MachineFunction &F, const BitVector &SavedRegs)
This file declares the machine register scavenger class.
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:275
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM_ABI StringRef getValueAsString() const
Return the attribute's value as a string.
bool test(unsigned Idx) const
Returns true if bit Idx is set.
Definition BitVector.h:482
BitVector & reset()
Reset all bits in the bitvector.
Definition BitVector.h:409
int find_first() const
Returns the index of the first set bit, -1 if none of the bits are set.
Definition BitVector.h:317
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
Definition BitVector.h:355
void clear()
Removes all bits from the bitvector.
Definition BitVector.h:349
BitVector & set()
Set all bits in the bitvector.
Definition BitVector.h:366
int find_next(unsigned Prev) const
Returns the index of the next set bit following the "Prev" bit.
Definition BitVector.h:324
bool none() const
Returns true if none of the bits are set.
Definition BitVector.h:207
size_type size() const
Returns the number of bits in this bitvector.
Definition BitVector.h:178
bool empty() const
Returns whether there are no bits in this bitvector.
Definition BitVector.h:175
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
The CalleeSavedInfo class tracks the information need to locate where a callee saved register is in t...
DWARF expression.
LLVM_ABI bool isImplicit() const
Return whether this is an implicit location description.
static bool fragmentsOverlap(const FragmentInfo &A, const FragmentInfo &B)
Check if fragments overlap between a pair of FragmentInfos.
static LLVM_ABI DIExpression * appendOpsToArg(const DIExpression *Expr, ArrayRef< uint64_t > Ops, unsigned ArgNo, bool StackValue=false)
Create a copy of Expr by appending the given list of Ops to each instance of the operand DW_OP_LLVM_a...
LLVM_ABI bool isComplex() const
Return whether the location is computed on the expression stack, meaning it cannot be a simple regist...
static LLVM_ABI DIExpression * prependOpcodes(const DIExpression *Expr, SmallVectorImpl< uint64_t > &Ops, bool StackValue=false, bool EntryValue=false)
Prepend DIExpr with the given opcodes and optionally turn it into a stack value.
Attribute getFnAttribute(Attribute::AttrKind Kind) const
Return the attribute for the given attribute kind.
Definition Function.cpp:762
DISubprogram * getSubprogram() const
Get the attached subprogram.
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
Definition Function.h:272
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:727
Wrapper class representing physical registers. Should be passed by value.
Definition MCRegister.h:41
MachineInstrBundleIterator< const MachineInstr > const_iterator
void setCallFrameSize(unsigned N)
Set the call frame size on entry to this basic block.
bool isEHFuncletEntry() const
Returns true if this is the entry block of an EH funclet.
LLVM_ABI iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
bool isReturnBlock() const
Convenience function that returns true if the block ends in a return instruction.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
iterator_range< iterator > terminators()
unsigned getCallFrameSize() const
Return the call frame size on entry to this basic block.
iterator_range< succ_iterator > successors()
MachineInstrBundleIterator< MachineInstr > iterator
Analysis pass which computes a MachineDominatorTree.
The MachineFrameInfo class represents an abstract stack frame until prolog/epilog code is inserted.
bool hasVarSizedObjects() const
This method may be called any time after instruction selection is complete to determine if the stack ...
SSPLayoutKind getObjectSSPLayout(int ObjectIdx) const
bool isObjectPreAllocated(int ObjectIdx) const
Return true if the object was pre-allocated into the local block.
LLVM_ABI void computeMaxCallFrameSize(MachineFunction &MF, std::vector< MachineBasicBlock::iterator > *FrameSDOps=nullptr)
Computes the maximum size of a callframe.
uint64_t getStackSize() const
Return the number of bytes that must be allocated to hold all of the fixed size frame objects.
bool adjustsStack() const
Return true if this function adjusts the stack – e.g., when calling another function.
LLVM_ABI int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot, const AllocaInst *Alloca=nullptr, uint8_t ID=0)
Create a new statically sized stack object, returning a nonnegative identifier to represent it.
int64_t getLocalFrameObjectCount() const
Return the number of objects allocated into the local object block.
bool hasCalls() const
Return true if the current function has any function calls.
Align getMaxAlign() const
Return the alignment in bytes that this function must be aligned to, which is greater than the defaul...
Align getLocalFrameMaxAlign() const
Return the required alignment of the local object blob.
void setObjectOffset(int ObjectIdx, int64_t SPOffset)
Set the stack frame offset of the specified object.
@ SSPLK_SmallArray
Array or nested array < SSP-buffer-size.
@ SSPLK_LargeArray
Array or nested array >= SSP-buffer-size.
@ SSPLK_AddrOf
The address of this allocation is exposed and triggered protection.
@ SSPLK_None
Did not trigger a stack protector.
bool isCalleeSavedObjectIndex(int ObjectIdx) const
std::pair< int, int64_t > getLocalFrameObjectMap(int i) const
Get the local offset mapping for a for an object.
uint64_t getMaxCallFrameSize() const
Return the maximum size of a call frame that must be allocated for an outgoing function call.
void setSavePoints(SaveRestorePoints NewSavePoints)
bool getUseLocalStackAllocationBlock() const
Get whether the local allocation blob should be allocated together or let PEI allocate the locals in ...
int getStackProtectorIndex() const
Return the index for the stack protector object.
void setCalleeSavedInfoValid(bool v)
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
bool isSpillSlotObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a spill slot.
int64_t getObjectSize(int ObjectIdx) const
Return the size of the specified object.
bool isMaxCallFrameSizeComputed() const
int64_t getLocalFrameSize() const
Get the size of the local object blob.
const std::vector< CalleeSavedInfo > & getCalleeSavedInfo() const
Returns a reference to call saved info vector for the current function.
void setCalleeSavedInfo(std::vector< CalleeSavedInfo > CSI)
Used by prolog/epilog inserter to set the function's callee saved information.
bool isVariableSizedObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a variable sized object.
uint64_t getUnsafeStackSize() const
int getObjectIndexEnd() const
Return one past the maximum frame object index.
bool hasStackProtectorIndex() const
void setRestorePoints(SaveRestorePoints NewRestorePoints)
LLVM_ABI int CreateFixedSpillStackObject(uint64_t Size, int64_t SPOffset, bool IsImmutable=false)
Create a spill slot at a fixed location on the stack.
uint8_t getStackID(int ObjectIdx) const
const SaveRestorePoints & getRestorePoints() const
void setIsCalleeSavedObjectIndex(int ObjectIdx, bool IsCalleeSaved)
int64_t getObjectOffset(int ObjectIdx) const
Return the assigned stack offset of the specified object from the incoming stack pointer.
void setStackSize(uint64_t Size)
Set the size of the stack.
int getObjectIndexBegin() const
Return the minimum frame object index.
const SaveRestorePoints & getSavePoints() const
bool isDeadObjectIndex(int ObjectIdx) const
Returns true if the specified index corresponds to a dead object.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const WinEHFuncInfo * getWinEHFuncInfo() const
getWinEHFuncInfo - Return information about how the current function uses Windows exception handling.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
bool shouldSplitStack() const
Should we be emitting segmented stack stuff for the function.
const MachineFunctionProperties & getProperties() const
Get the function properties.
const MachineBasicBlock & front() const
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Emit an optimization remark.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
bool isReserved(MCRegister PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
LLVM_ABI PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI void enterBasicBlockEnd(MachineBasicBlock &MBB)
Start tracking liveness from the end of basic block MBB.
LLVM_ABI void backward()
Update internal register state and move MBB iterator backwards.
void getScavengingFrameIndices(SmallVectorImpl< int > &A) const
Get an array of scavenging frame indices.
bool isScavengingFrameIndex(int FI) const
Query whether a frame index is a scavenging frame index.
constexpr unsigned id() const
Definition Register.h:100
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:345
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
size_type count(const T &V) const
count - Return 1 if the element is in the set, 0 otherwise.
Definition SmallSet.h:176
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
static StackOffset getScalable(int64_t Scalable)
Definition TypeSize.h:40
static StackOffset getFixed(int64_t Fixed)
Definition TypeSize.h:39
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition StringRef.h:490
Information about stack frame layout on the target.
virtual void spillFPBP(MachineFunction &MF) const
If frame pointer or base pointer is clobbered by an instruction, we should spill/restore it around th...
virtual void emitEpilogue(MachineFunction &MF, MachineBasicBlock &MBB) const =0
virtual const SpillSlot * getCalleeSavedSpillSlots(unsigned &NumEntries) const
getCalleeSavedSpillSlots - This method returns a pointer to an array of pairs, that contains an entry...
virtual bool hasReservedCallFrame(const MachineFunction &MF) const
hasReservedCallFrame - Under normal circumstances, when a frame pointer is not required,...
virtual bool enableStackSlotScavenging(const MachineFunction &MF) const
Returns true if the stack slot holes in the fixed and callee-save stack area should be used when allo...
virtual bool allocateScavengingFrameIndexesNearIncomingSP(const MachineFunction &MF) const
Control the placement of special register scavenging spill slots when allocating a stack frame.
Align getTransientStackAlign() const
getTransientStackAlignment - This method returns the number of bytes to which the stack pointer must ...
virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs, RegScavenger *RS=nullptr) const
This method determines which of the registers reported by TargetRegisterInfo::getCalleeSavedRegs() sh...
virtual uint64_t getStackThreshold() const
getStackThreshold - Return the maximum stack size
virtual void processFunctionBeforeFrameFinalized(MachineFunction &MF, RegScavenger *RS=nullptr) const
processFunctionBeforeFrameFinalized - This method is called immediately before the specified function...
virtual void inlineStackProbe(MachineFunction &MF, MachineBasicBlock &PrologueMBB) const
Replace a StackProbe stub (if any) with the actual probe code inline.
void restoreCalleeSavedRegister(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, const CalleeSavedInfo &CS, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const
void spillCalleeSavedRegister(MachineBasicBlock &SaveBlock, MachineBasicBlock::iterator MI, const CalleeSavedInfo &CS, const TargetInstrInfo *TII, const TargetRegisterInfo *TRI) const
spillCalleeSavedRegister - Default implementation for spilling a single callee saved register.
virtual void orderFrameObjects(const MachineFunction &MF, SmallVectorImpl< int > &objectsToAllocate) const
Order the symbols in the local stack frame.
virtual void adjustForHiPEPrologue(MachineFunction &MF, MachineBasicBlock &PrologueMBB) const
Adjust the prologue to add Erlang Run-Time System (ERTS) specific code in the assembly prologue to ex...
virtual bool spillCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, ArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const
spillCalleeSavedRegisters - Issues instruction(s) to spill all callee saved registers and returns tru...
int getOffsetOfLocalArea() const
getOffsetOfLocalArea - This method returns the offset of the local area from the stack pointer on ent...
virtual bool needsFrameIndexResolution(const MachineFunction &MF) const
virtual MachineBasicBlock::iterator eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB, MachineBasicBlock::iterator MI) const
This method is called during prolog/epilog code insertion to eliminate call frame setup and destroy p...
virtual void emitZeroCallUsedRegs(BitVector RegsToZero, MachineBasicBlock &MBB, RegScavenger *RS) const
emitZeroCallUsedRegs - Zeros out call used registers.
Align getStackAlign() const
getStackAlignment - This method returns the number of bytes to which the stack pointer must be aligne...
virtual bool assignCalleeSavedSpillSlots(MachineFunction &MF, const TargetRegisterInfo *TRI, std::vector< CalleeSavedInfo > &CSI) const
assignCalleeSavedSpillSlots - Allows target to override spill slot assignment logic.
virtual void processFunctionBeforeFrameIndicesReplaced(MachineFunction &MF, RegScavenger *RS=nullptr) const
processFunctionBeforeFrameIndicesReplaced - This method is called immediately before MO_FrameIndex op...
virtual StackOffset getFrameIndexReferencePreferSP(const MachineFunction &MF, int FI, Register &FrameReg, bool IgnoreSPUpdates) const
Same as getFrameIndexReference, except that the stack pointer (as opposed to the frame pointer) will ...
StackDirection getStackGrowthDirection() const
getStackGrowthDirection - Return the direction the stack grows
virtual void adjustForSegmentedStacks(MachineFunction &MF, MachineBasicBlock &PrologueMBB) const
Adjust the prologue to have the function use segmented stacks.
int alignSPAdjust(int SPAdj) const
alignSPAdjust - This method aligns the stack adjustment to the correct alignment.
virtual bool canSimplifyCallFramePseudos(const MachineFunction &MF) const
canSimplifyCallFramePseudos - When possible, it's best to simplify the call frame pseudo ops before d...
virtual void emitRemarks(const MachineFunction &MF, MachineOptimizationRemarkEmitter *ORE) const
This method is called at the end of prolog/epilog code insertion, so targets can emit remarks based o...
virtual bool targetHandlesStackFrameRounding() const
targetHandlesStackFrameRounding - Returns true if the target is responsible for rounding up the stack...
virtual void emitPrologue(MachineFunction &MF, MachineBasicBlock &MBB) const =0
emitProlog/emitEpilog - These methods insert prolog and epilog code into the function.
virtual bool restoreCalleeSavedRegisters(MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, MutableArrayRef< CalleeSavedInfo > CSI, const TargetRegisterInfo *TRI) const
restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee saved registers and returns...
virtual StackOffset getFrameIndexReference(const MachineFunction &MF, int FI, Register &FrameReg) const
getFrameIndexReference - This method should return the base register and offset used to reference a f...
TargetInstrInfo - Interface to description of machine instruction set.
CodeGenOptLevel getOptLevel() const
Returns the optimization level: None, Less, Default, or Aggressive.
virtual bool usesPhysRegsForValues() const
True if the target uses physical regs (as nearly all targets do).
TargetOptions Options
unsigned StackSymbolOrdering
StackSymbolOrdering - When true, this will allow CodeGen to order the local stack symbols (for code s...
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
bool hasStackRealignment(const MachineFunction &MF) const
True if stack realignment is required and still possible.
virtual const TargetFrameLowering * getFrameLowering() const
virtual const TargetInstrInfo * getInstrInfo() const
virtual const TargetRegisterInfo * getRegisterInfo() const =0
Return the target's register information.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
@ Entry
Definition COFF.h:862
DXILDebugInfoMap run(Module &M)
DiagnosticInfoOptimizationBase::Argument NV
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:578
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
testing::Matcher< const detail::ErrorHolder & > Failed()
Definition Error.h:198
LLVM_ABI void scavengeFrameVirtualRegs(MachineFunction &MF, RegScavenger &RS)
Replaces all frame index virtual registers with physical registers.
LLVM_ABI MachineFunctionPass * createPrologEpilogInserterPass()
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI char & PrologEpilogCodeInserterID
PrologEpilogCodeInserter - This pass inserts prolog and epilog code, and eliminates abstract frame re...
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1746
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:407
DenseMap< MachineBasicBlock *, std::vector< CalleeSavedInfo > > SaveRestorePoints
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1753
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
auto reverse_conditionally(ContainerTy &&C, bool ShouldReverse)
Return a range that conditionally reverses C.
Definition STLExtras.h:1423
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition MCRegister.h:21
DWARFExpression::Operation Op
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39