xref: /llvm-project/llvm/include/llvm/CodeGen/TargetFrameLowering.h (revision ad4a582fd938c933e784f0052bd773676b37b690)
1 //===-- llvm/CodeGen/TargetFrameLowering.h ----------------------*- C++ -*-===//
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 // Interface to describe the layout of a stack frame on the target machine.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CODEGEN_TARGETFRAMELOWERING_H
14 #define LLVM_CODEGEN_TARGETFRAMELOWERING_H
15 
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/CodeGen/MachineBasicBlock.h"
18 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h"
19 #include "llvm/Support/TypeSize.h"
20 #include <vector>
21 
22 namespace llvm {
23   class BitVector;
24   class CalleeSavedInfo;
25   class MachineFunction;
26   class RegScavenger;
27 
28 namespace TargetStackID {
29 enum Value {
30   Default = 0,
31   SGPRSpill = 1,
32   ScalableVector = 2,
33   WasmLocal = 3,
34   NoAlloc = 255
35 };
36 }
37 
38 /// Information about stack frame layout on the target.  It holds the direction
39 /// of stack growth, the known stack alignment on entry to each function, and
40 /// the offset to the locals area.
41 ///
42 /// The offset to the local area is the offset from the stack pointer on
43 /// function entry to the first location where function data (local variables,
44 /// spill locations) can be stored.
45 class TargetFrameLowering {
46 public:
47   enum StackDirection {
48     StackGrowsUp,        // Adding to the stack increases the stack address
49     StackGrowsDown       // Adding to the stack decreases the stack address
50   };
51 
52   // Maps a callee saved register to a stack slot with a fixed offset.
53   struct SpillSlot {
54     unsigned Reg;
55     int64_t Offset; // Offset relative to stack pointer on function entry.
56   };
57 
58   struct DwarfFrameBase {
59     // The frame base may be either a register (the default), the CFA with an
60     // offset, or a WebAssembly-specific location description.
61     enum FrameBaseKind { Register, CFA, WasmFrameBase } Kind;
62     struct WasmFrameBase {
63       unsigned Kind; // Wasm local, global, or value stack
64       unsigned Index;
65     };
66     union {
67       // Used with FrameBaseKind::Register.
68       unsigned Reg;
69       // Used with FrameBaseKind::CFA.
70       int64_t Offset;
71       struct WasmFrameBase WasmLoc;
72     } Location;
73   };
74 
75 private:
76   StackDirection StackDir;
77   Align StackAlignment;
78   Align TransientStackAlignment;
79   int LocalAreaOffset;
80   bool StackRealignable;
81 public:
82   TargetFrameLowering(StackDirection D, Align StackAl, int LAO,
83                       Align TransAl = Align(1), bool StackReal = true)
84       : StackDir(D), StackAlignment(StackAl), TransientStackAlignment(TransAl),
85         LocalAreaOffset(LAO), StackRealignable(StackReal) {}
86 
87   virtual ~TargetFrameLowering();
88 
89   // These methods return information that describes the abstract stack layout
90   // of the target machine.
91 
92   /// getStackGrowthDirection - Return the direction the stack grows
93   ///
94   StackDirection getStackGrowthDirection() const { return StackDir; }
95 
96   /// getStackAlignment - This method returns the number of bytes to which the
97   /// stack pointer must be aligned on entry to a function.  Typically, this
98   /// is the largest alignment for any data object in the target.
99   ///
100   unsigned getStackAlignment() const { return StackAlignment.value(); }
101   /// getStackAlignment - This method returns the number of bytes to which the
102   /// stack pointer must be aligned on entry to a function.  Typically, this
103   /// is the largest alignment for any data object in the target.
104   ///
105   Align getStackAlign() const { return StackAlignment; }
106 
107   /// getStackThreshold - Return the maximum stack size
108   ///
109   virtual uint64_t getStackThreshold() const { return UINT_MAX; }
110 
111   /// alignSPAdjust - This method aligns the stack adjustment to the correct
112   /// alignment.
113   ///
114   int alignSPAdjust(int SPAdj) const {
115     if (SPAdj < 0) {
116       SPAdj = -alignTo(-SPAdj, StackAlignment);
117     } else {
118       SPAdj = alignTo(SPAdj, StackAlignment);
119     }
120     return SPAdj;
121   }
122 
123   /// getTransientStackAlignment - This method returns the number of bytes to
124   /// which the stack pointer must be aligned at all times, even between
125   /// calls.
126   ///
127   Align getTransientStackAlign() const { return TransientStackAlignment; }
128 
129   /// isStackRealignable - This method returns whether the stack can be
130   /// realigned.
131   bool isStackRealignable() const {
132     return StackRealignable;
133   }
134 
135   /// This method returns whether or not it is safe for an object with the
136   /// given stack id to be bundled into the local area.
137   virtual bool isStackIdSafeForLocalArea(unsigned StackId) const {
138     return true;
139   }
140 
141   /// getOffsetOfLocalArea - This method returns the offset of the local area
142   /// from the stack pointer on entrance to a function.
143   ///
144   int getOffsetOfLocalArea() const { return LocalAreaOffset; }
145 
146   /// Control the placement of special register scavenging spill slots when
147   /// allocating a stack frame.
148   ///
149   /// If this returns true, the frame indexes used by the RegScavenger will be
150   /// allocated closest to the incoming stack pointer.
151   virtual bool allocateScavengingFrameIndexesNearIncomingSP(
152     const MachineFunction &MF) const;
153 
154   /// assignCalleeSavedSpillSlots - Allows target to override spill slot
155   /// assignment logic.  If implemented, assignCalleeSavedSpillSlots() should
156   /// assign frame slots to all CSI entries and return true.  If this method
157   /// returns false, spill slots will be assigned using generic implementation.
158   /// assignCalleeSavedSpillSlots() may add, delete or rearrange elements of
159   /// CSI.
160   virtual bool assignCalleeSavedSpillSlots(MachineFunction &MF,
161                                            const TargetRegisterInfo *TRI,
162                                            std::vector<CalleeSavedInfo> &CSI,
163                                            unsigned &MinCSFrameIndex,
164                                            unsigned &MaxCSFrameIndex) const {
165     return assignCalleeSavedSpillSlots(MF, TRI, CSI);
166   }
167 
168   virtual bool
169   assignCalleeSavedSpillSlots(MachineFunction &MF,
170                               const TargetRegisterInfo *TRI,
171                               std::vector<CalleeSavedInfo> &CSI) const {
172     return false;
173   }
174 
175   /// getCalleeSavedSpillSlots - This method returns a pointer to an array of
176   /// pairs, that contains an entry for each callee saved register that must be
177   /// spilled to a particular stack location if it is spilled.
178   ///
179   /// Each entry in this array contains a <register,offset> pair, indicating the
180   /// fixed offset from the incoming stack pointer that each register should be
181   /// spilled at. If a register is not listed here, the code generator is
182   /// allowed to spill it anywhere it chooses.
183   ///
184   virtual const SpillSlot *
185   getCalleeSavedSpillSlots(unsigned &NumEntries) const {
186     NumEntries = 0;
187     return nullptr;
188   }
189 
190   /// targetHandlesStackFrameRounding - Returns true if the target is
191   /// responsible for rounding up the stack frame (probably at emitPrologue
192   /// time).
193   virtual bool targetHandlesStackFrameRounding() const {
194     return false;
195   }
196 
197   /// Returns true if the target will correctly handle shrink wrapping.
198   virtual bool enableShrinkWrapping(const MachineFunction &MF) const {
199     return false;
200   }
201 
202   /// Returns true if the stack slot holes in the fixed and callee-save stack
203   /// area should be used when allocating other stack locations to reduce stack
204   /// size.
205   virtual bool enableStackSlotScavenging(const MachineFunction &MF) const {
206     return false;
207   }
208 
209   /// Returns true if the target can safely skip saving callee-saved registers
210   /// for noreturn nounwind functions.
211   virtual bool enableCalleeSaveSkip(const MachineFunction &MF) const;
212 
213   /// emitProlog/emitEpilog - These methods insert prolog and epilog code into
214   /// the function.
215   virtual void emitPrologue(MachineFunction &MF,
216                             MachineBasicBlock &MBB) const = 0;
217   virtual void emitEpilogue(MachineFunction &MF,
218                             MachineBasicBlock &MBB) const = 0;
219 
220   /// emitZeroCallUsedRegs - Zeros out call used registers.
221   virtual void emitZeroCallUsedRegs(BitVector RegsToZero,
222                                     MachineBasicBlock &MBB) const {}
223 
224   /// With basic block sections, emit callee saved frame moves for basic blocks
225   /// that are in a different section.
226   virtual void
227   emitCalleeSavedFrameMovesFullCFA(MachineBasicBlock &MBB,
228                                    MachineBasicBlock::iterator MBBI) const {}
229 
230   /// Returns true if we may need to fix the unwind information for the
231   /// function.
232   virtual bool enableCFIFixup(MachineFunction &MF) const;
233 
234   /// Emit CFI instructions that recreate the state of the unwind information
235   /// upon fucntion entry.
236   virtual void resetCFIToInitialState(MachineBasicBlock &MBB) const {}
237 
238   /// Replace a StackProbe stub (if any) with the actual probe code inline
239   virtual void inlineStackProbe(MachineFunction &MF,
240                                 MachineBasicBlock &PrologueMBB) const {}
241 
242   /// Does the stack probe function call return with a modified stack pointer?
243   virtual bool stackProbeFunctionModifiesSP() const { return false; }
244 
245   /// Adjust the prologue to have the function use segmented stacks. This works
246   /// by adding a check even before the "normal" function prologue.
247   virtual void adjustForSegmentedStacks(MachineFunction &MF,
248                                         MachineBasicBlock &PrologueMBB) const {}
249 
250   /// Adjust the prologue to add Erlang Run-Time System (ERTS) specific code in
251   /// the assembly prologue to explicitly handle the stack.
252   virtual void adjustForHiPEPrologue(MachineFunction &MF,
253                                      MachineBasicBlock &PrologueMBB) const {}
254 
255   /// spillCalleeSavedRegisters - Issues instruction(s) to spill all callee
256   /// saved registers and returns true if it isn't possible / profitable to do
257   /// so by issuing a series of store instructions via
258   /// storeRegToStackSlot(). Returns false otherwise.
259   virtual bool spillCalleeSavedRegisters(MachineBasicBlock &MBB,
260                                          MachineBasicBlock::iterator MI,
261                                          ArrayRef<CalleeSavedInfo> CSI,
262                                          const TargetRegisterInfo *TRI) const {
263     return false;
264   }
265 
266   /// restoreCalleeSavedRegisters - Issues instruction(s) to restore all callee
267   /// saved registers and returns true if it isn't possible / profitable to do
268   /// so by issuing a series of load instructions via loadRegToStackSlot().
269   /// If it returns true, and any of the registers in CSI is not restored,
270   /// it sets the corresponding Restored flag in CSI to false.
271   /// Returns false otherwise.
272   virtual bool
273   restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
274                               MachineBasicBlock::iterator MI,
275                               MutableArrayRef<CalleeSavedInfo> CSI,
276                               const TargetRegisterInfo *TRI) const {
277     return false;
278   }
279 
280   /// hasFP - Return true if the specified function should have a dedicated
281   /// frame pointer register. For most targets this is true only if the function
282   /// has variable sized allocas or if frame pointer elimination is disabled.
283   /// For all targets, this is false if the function has the naked attribute
284   /// since there is no prologue to set up the frame pointer.
285   bool hasFP(const MachineFunction &MF) const {
286     return !MF.getFunction().hasFnAttribute(Attribute::Naked) && hasFPImpl(MF);
287   }
288 
289   /// hasReservedCallFrame - Under normal circumstances, when a frame pointer is
290   /// not required, we reserve argument space for call sites in the function
291   /// immediately on entry to the current function. This eliminates the need for
292   /// add/sub sp brackets around call sites. Returns true if the call frame is
293   /// included as part of the stack frame.
294   virtual bool hasReservedCallFrame(const MachineFunction &MF) const {
295     return !hasFP(MF);
296   }
297 
298   /// canSimplifyCallFramePseudos - When possible, it's best to simplify the
299   /// call frame pseudo ops before doing frame index elimination. This is
300   /// possible only when frame index references between the pseudos won't
301   /// need adjusting for the call frame adjustments. Normally, that's true
302   /// if the function has a reserved call frame or a frame pointer. Some
303   /// targets (Thumb2, for example) may have more complicated criteria,
304   /// however, and can override this behavior.
305   virtual bool canSimplifyCallFramePseudos(const MachineFunction &MF) const {
306     return hasReservedCallFrame(MF) || hasFP(MF);
307   }
308 
309   // needsFrameIndexResolution - Do we need to perform FI resolution for
310   // this function. Normally, this is required only when the function
311   // has any stack objects. However, targets may want to override this.
312   virtual bool needsFrameIndexResolution(const MachineFunction &MF) const;
313 
314   /// getFrameIndexReference - This method should return the base register
315   /// and offset used to reference a frame index location. The offset is
316   /// returned directly, and the base register is returned via FrameReg.
317   virtual StackOffset getFrameIndexReference(const MachineFunction &MF, int FI,
318                                              Register &FrameReg) const;
319 
320   /// Same as \c getFrameIndexReference, except that the stack pointer (as
321   /// opposed to the frame pointer) will be the preferred value for \p
322   /// FrameReg. This is generally used for emitting statepoint or EH tables that
323   /// use offsets from RSP.  If \p IgnoreSPUpdates is true, the returned
324   /// offset is only guaranteed to be valid with respect to the value of SP at
325   /// the end of the prologue.
326   virtual StackOffset
327   getFrameIndexReferencePreferSP(const MachineFunction &MF, int FI,
328                                  Register &FrameReg,
329                                  bool IgnoreSPUpdates) const {
330     // Always safe to dispatch to getFrameIndexReference.
331     return getFrameIndexReference(MF, FI, FrameReg);
332   }
333 
334   /// getNonLocalFrameIndexReference - This method returns the offset used to
335   /// reference a frame index location. The offset can be from either FP/BP/SP
336   /// based on which base register is returned by llvm.localaddress.
337   virtual StackOffset getNonLocalFrameIndexReference(const MachineFunction &MF,
338                                                      int FI) const {
339     // By default, dispatch to getFrameIndexReference. Interested targets can
340     // override this.
341     Register FrameReg;
342     return getFrameIndexReference(MF, FI, FrameReg);
343   }
344 
345   /// getFrameIndexReferenceFromSP - This method returns the offset from the
346   /// stack pointer to the slot of the specified index. This function serves to
347   /// provide a comparable offset from a single reference point (the value of
348   /// the stack-pointer at function entry) that can be used for analysis.
349   virtual StackOffset getFrameIndexReferenceFromSP(const MachineFunction &MF,
350                                                    int FI) const;
351 
352   /// Returns the callee-saved registers as computed by determineCalleeSaves
353   /// in the BitVector \p SavedRegs.
354   virtual void getCalleeSaves(const MachineFunction &MF,
355                                   BitVector &SavedRegs) const;
356 
357   /// This method determines which of the registers reported by
358   /// TargetRegisterInfo::getCalleeSavedRegs() should actually get saved.
359   /// The default implementation checks populates the \p SavedRegs bitset with
360   /// all registers which are modified in the function, targets may override
361   /// this function to save additional registers.
362   /// This method also sets up the register scavenger ensuring there is a free
363   /// register or a frameindex available.
364   /// This method should not be called by any passes outside of PEI, because
365   /// it may change state passed in by \p MF and \p RS. The preferred
366   /// interface outside PEI is getCalleeSaves.
367   virtual void determineCalleeSaves(MachineFunction &MF, BitVector &SavedRegs,
368                                     RegScavenger *RS = nullptr) const;
369 
370   /// processFunctionBeforeFrameFinalized - This method is called immediately
371   /// before the specified function's frame layout (MF.getFrameInfo()) is
372   /// finalized.  Once the frame is finalized, MO_FrameIndex operands are
373   /// replaced with direct constants.  This method is optional.
374   ///
375   virtual void processFunctionBeforeFrameFinalized(MachineFunction &MF,
376                                              RegScavenger *RS = nullptr) const {
377   }
378 
379   /// processFunctionBeforeFrameIndicesReplaced - This method is called
380   /// immediately before MO_FrameIndex operands are eliminated, but after the
381   /// frame is finalized. This method is optional.
382   virtual void
383   processFunctionBeforeFrameIndicesReplaced(MachineFunction &MF,
384                                             RegScavenger *RS = nullptr) const {}
385 
386   virtual unsigned getWinEHParentFrameOffset(const MachineFunction &MF) const {
387     report_fatal_error("WinEH not implemented for this target");
388   }
389 
390   /// This method is called during prolog/epilog code insertion to eliminate
391   /// call frame setup and destroy pseudo instructions (but only if the Target
392   /// is using them).  It is responsible for eliminating these instructions,
393   /// replacing them with concrete instructions.  This method need only be
394   /// implemented if using call frame setup/destroy pseudo instructions.
395   /// Returns an iterator pointing to the instruction after the replaced one.
396   virtual MachineBasicBlock::iterator
397   eliminateCallFramePseudoInstr(MachineFunction &MF,
398                                 MachineBasicBlock &MBB,
399                                 MachineBasicBlock::iterator MI) const {
400     llvm_unreachable("Call Frame Pseudo Instructions do not exist on this "
401                      "target!");
402   }
403 
404 
405   /// Order the symbols in the local stack frame.
406   /// The list of objects that we want to order is in \p objectsToAllocate as
407   /// indices into the MachineFrameInfo. The array can be reordered in any way
408   /// upon return. The contents of the array, however, may not be modified (i.e.
409   /// only their order may be changed).
410   /// By default, just maintain the original order.
411   virtual void
412   orderFrameObjects(const MachineFunction &MF,
413                     SmallVectorImpl<int> &objectsToAllocate) const {
414   }
415 
416   /// Check whether or not the given \p MBB can be used as a prologue
417   /// for the target.
418   /// The prologue will be inserted first in this basic block.
419   /// This method is used by the shrink-wrapping pass to decide if
420   /// \p MBB will be correctly handled by the target.
421   /// As soon as the target enable shrink-wrapping without overriding
422   /// this method, we assume that each basic block is a valid
423   /// prologue.
424   virtual bool canUseAsPrologue(const MachineBasicBlock &MBB) const {
425     return true;
426   }
427 
428   /// Check whether or not the given \p MBB can be used as a epilogue
429   /// for the target.
430   /// The epilogue will be inserted before the first terminator of that block.
431   /// This method is used by the shrink-wrapping pass to decide if
432   /// \p MBB will be correctly handled by the target.
433   /// As soon as the target enable shrink-wrapping without overriding
434   /// this method, we assume that each basic block is a valid
435   /// epilogue.
436   virtual bool canUseAsEpilogue(const MachineBasicBlock &MBB) const {
437     return true;
438   }
439 
440   /// Returns the StackID that scalable vectors should be associated with.
441   virtual TargetStackID::Value getStackIDForScalableVectors() const {
442     return TargetStackID::Default;
443   }
444 
445   virtual bool isSupportedStackID(TargetStackID::Value ID) const {
446     switch (ID) {
447     default:
448       return false;
449     case TargetStackID::Default:
450     case TargetStackID::NoAlloc:
451       return true;
452     }
453   }
454 
455   /// Check if given function is safe for not having callee saved registers.
456   /// This is used when interprocedural register allocation is enabled.
457   static bool isSafeForNoCSROpt(const Function &F);
458 
459   /// Check if the no-CSR optimisation is profitable for the given function.
460   virtual bool isProfitableForNoCSROpt(const Function &F) const {
461     return true;
462   }
463 
464   /// Return initial CFA offset value i.e. the one valid at the beginning of the
465   /// function (before any stack operations).
466   virtual int getInitialCFAOffset(const MachineFunction &MF) const;
467 
468   /// Return initial CFA register value i.e. the one valid at the beginning of
469   /// the function (before any stack operations).
470   virtual Register getInitialCFARegister(const MachineFunction &MF) const;
471 
472   /// Return the frame base information to be encoded in the DWARF subprogram
473   /// debug info.
474   virtual DwarfFrameBase getDwarfFrameBase(const MachineFunction &MF) const;
475 
476   /// If frame pointer or base pointer is clobbered by an instruction, we should
477   /// spill/restore it around that instruction.
478   virtual void spillFPBP(MachineFunction &MF) const {}
479 
480   /// This method is called at the end of prolog/epilog code insertion, so
481   /// targets can emit remarks based on the final frame layout.
482   virtual void emitRemarks(const MachineFunction &MF,
483                            MachineOptimizationRemarkEmitter *ORE) const {};
484 
485 protected:
486   virtual bool hasFPImpl(const MachineFunction &MF) const = 0;
487 };
488 
489 } // End llvm namespace
490 
491 #endif
492