1 //===-- CodeGen/MachineFrameInfo.h - Abstract Stack Frame Rep. --*- 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 // The file defines the MachineFrameInfo class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CODEGEN_MACHINEFRAMEINFO_H
14 #define LLVM_CODEGEN_MACHINEFRAMEINFO_H
15 
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/CodeGen/Register.h"
18 #include "llvm/Support/Alignment.h"
19 #include <cassert>
20 #include <vector>
21 
22 namespace llvm {
23 class raw_ostream;
24 class MachineFunction;
25 class MachineBasicBlock;
26 class BitVector;
27 class AllocaInst;
28 
29 /// The CalleeSavedInfo class tracks the information need to locate where a
30 /// callee saved register is in the current frame.
31 /// Callee saved reg can also be saved to a different register rather than
32 /// on the stack by setting DstReg instead of FrameIdx.
33 class CalleeSavedInfo {
34   Register Reg;
35   union {
36     int FrameIdx;
37     unsigned DstReg;
38   };
39   /// Flag indicating whether the register is actually restored in the epilog.
40   /// In most cases, if a register is saved, it is also restored. There are
41   /// some situations, though, when this is not the case. For example, the
42   /// LR register on ARM is usually saved, but on exit from the function its
43   /// saved value may be loaded directly into PC. Since liveness tracking of
44   /// physical registers treats callee-saved registers are live outside of
45   /// the function, LR would be treated as live-on-exit, even though in these
46   /// scenarios it is not. This flag is added to indicate that the saved
47   /// register described by this object is not restored in the epilog.
48   /// The long-term solution is to model the liveness of callee-saved registers
49   /// by implicit uses on the return instructions, however, the required
50   /// changes in the ARM backend would be quite extensive.
51   bool Restored = true;
52   /// Flag indicating whether the register is spilled to stack or another
53   /// register.
54   bool SpilledToReg = false;
55 
56 public:
57   explicit CalleeSavedInfo(unsigned R, int FI = 0) : Reg(R), FrameIdx(FI) {}
58 
59   // Accessors.
60   Register getReg()                        const { return Reg; }
61   int getFrameIdx()                        const { return FrameIdx; }
62   unsigned getDstReg()                     const { return DstReg; }
63   void setFrameIdx(int FI) {
64     FrameIdx = FI;
65     SpilledToReg = false;
66   }
67   void setDstReg(Register SpillReg) {
68     DstReg = SpillReg;
69     SpilledToReg = true;
70   }
71   bool isRestored()                        const { return Restored; }
72   void setRestored(bool R)                       { Restored = R; }
73   bool isSpilledToReg()                    const { return SpilledToReg; }
74 };
75 
76 /// The MachineFrameInfo class represents an abstract stack frame until
77 /// prolog/epilog code is inserted.  This class is key to allowing stack frame
78 /// representation optimizations, such as frame pointer elimination.  It also
79 /// allows more mundane (but still important) optimizations, such as reordering
80 /// of abstract objects on the stack frame.
81 ///
82 /// To support this, the class assigns unique integer identifiers to stack
83 /// objects requested clients.  These identifiers are negative integers for
84 /// fixed stack objects (such as arguments passed on the stack) or nonnegative
85 /// for objects that may be reordered.  Instructions which refer to stack
86 /// objects use a special MO_FrameIndex operand to represent these frame
87 /// indexes.
88 ///
89 /// Because this class keeps track of all references to the stack frame, it
90 /// knows when a variable sized object is allocated on the stack.  This is the
91 /// sole condition which prevents frame pointer elimination, which is an
92 /// important optimization on register-poor architectures.  Because original
93 /// variable sized alloca's in the source program are the only source of
94 /// variable sized stack objects, it is safe to decide whether there will be
95 /// any variable sized objects before all stack objects are known (for
96 /// example, register allocator spill code never needs variable sized
97 /// objects).
98 ///
99 /// When prolog/epilog code emission is performed, the final stack frame is
100 /// built and the machine instructions are modified to refer to the actual
101 /// stack offsets of the object, eliminating all MO_FrameIndex operands from
102 /// the program.
103 ///
104 /// Abstract Stack Frame Information
105 class MachineFrameInfo {
106 public:
107   /// Stack Smashing Protection (SSP) rules require that vulnerable stack
108   /// allocations are located close the stack protector.
109   enum SSPLayoutKind {
110     SSPLK_None,       ///< Did not trigger a stack protector.  No effect on data
111                       ///< layout.
112     SSPLK_LargeArray, ///< Array or nested array >= SSP-buffer-size.  Closest
113                       ///< to the stack protector.
114     SSPLK_SmallArray, ///< Array or nested array < SSP-buffer-size. 2nd closest
115                       ///< to the stack protector.
116     SSPLK_AddrOf      ///< The address of this allocation is exposed and
117                       ///< triggered protection.  3rd closest to the protector.
118   };
119 
120 private:
121   // Represent a single object allocated on the stack.
122   struct StackObject {
123     // The offset of this object from the stack pointer on entry to
124     // the function.  This field has no meaning for a variable sized element.
125     int64_t SPOffset;
126 
127     // The size of this object on the stack. 0 means a variable sized object,
128     // ~0ULL means a dead object.
129     uint64_t Size;
130 
131     // The required alignment of this stack slot.
132     Align Alignment;
133 
134     // If true, the value of the stack object is set before
135     // entering the function and is not modified inside the function. By
136     // default, fixed objects are immutable unless marked otherwise.
137     bool isImmutable;
138 
139     // If true the stack object is used as spill slot. It
140     // cannot alias any other memory objects.
141     bool isSpillSlot;
142 
143     /// If true, this stack slot is used to spill a value (could be deopt
144     /// and/or GC related) over a statepoint. We know that the address of the
145     /// slot can't alias any LLVM IR value.  This is very similar to a Spill
146     /// Slot, but is created by statepoint lowering is SelectionDAG, not the
147     /// register allocator.
148     bool isStatepointSpillSlot = false;
149 
150     /// Identifier for stack memory type analagous to address space. If this is
151     /// non-0, the meaning is target defined. Offsets cannot be directly
152     /// compared between objects with different stack IDs. The object may not
153     /// necessarily reside in the same contiguous memory block as other stack
154     /// objects. Objects with differing stack IDs should not be merged or
155     /// replaced substituted for each other.
156     //
157     /// It is assumed a target uses consecutive, increasing stack IDs starting
158     /// from 1.
159     uint8_t StackID;
160 
161     /// If this stack object is originated from an Alloca instruction
162     /// this value saves the original IR allocation. Can be NULL.
163     const AllocaInst *Alloca;
164 
165     // If true, the object was mapped into the local frame
166     // block and doesn't need additional handling for allocation beyond that.
167     bool PreAllocated = false;
168 
169     // If true, an LLVM IR value might point to this object.
170     // Normally, spill slots and fixed-offset objects don't alias IR-accessible
171     // objects, but there are exceptions (on PowerPC, for example, some byval
172     // arguments have ABI-prescribed offsets).
173     bool isAliased;
174 
175     /// If true, the object has been zero-extended.
176     bool isZExt = false;
177 
178     /// If true, the object has been sign-extended.
179     bool isSExt = false;
180 
181     uint8_t SSPLayout = SSPLK_None;
182 
183     StackObject(uint64_t Size, Align Alignment, int64_t SPOffset,
184                 bool IsImmutable, bool IsSpillSlot, const AllocaInst *Alloca,
185                 bool IsAliased, uint8_t StackID = 0)
186         : SPOffset(SPOffset), Size(Size), Alignment(Alignment),
187           isImmutable(IsImmutable), isSpillSlot(IsSpillSlot), StackID(StackID),
188           Alloca(Alloca), isAliased(IsAliased) {}
189   };
190 
191   /// The alignment of the stack.
192   Align StackAlignment;
193 
194   /// Can the stack be realigned. This can be false if the target does not
195   /// support stack realignment, or if the user asks us not to realign the
196   /// stack. In this situation, overaligned allocas are all treated as dynamic
197   /// allocations and the target must handle them as part of DYNAMIC_STACKALLOC
198   /// lowering. All non-alloca stack objects have their alignment clamped to the
199   /// base ABI stack alignment.
200   /// FIXME: There is room for improvement in this case, in terms of
201   /// grouping overaligned allocas into a "secondary stack frame" and
202   /// then only use a single alloca to allocate this frame and only a
203   /// single virtual register to access it. Currently, without such an
204   /// optimization, each such alloca gets its own dynamic realignment.
205   bool StackRealignable;
206 
207   /// Whether the function has the \c alignstack attribute.
208   bool ForcedRealign;
209 
210   /// The list of stack objects allocated.
211   std::vector<StackObject> Objects;
212 
213   /// This contains the number of fixed objects contained on
214   /// the stack.  Because fixed objects are stored at a negative index in the
215   /// Objects list, this is also the index to the 0th object in the list.
216   unsigned NumFixedObjects = 0;
217 
218   /// This boolean keeps track of whether any variable
219   /// sized objects have been allocated yet.
220   bool HasVarSizedObjects = false;
221 
222   /// This boolean keeps track of whether there is a call
223   /// to builtin \@llvm.frameaddress.
224   bool FrameAddressTaken = false;
225 
226   /// This boolean keeps track of whether there is a call
227   /// to builtin \@llvm.returnaddress.
228   bool ReturnAddressTaken = false;
229 
230   /// This boolean keeps track of whether there is a call
231   /// to builtin \@llvm.experimental.stackmap.
232   bool HasStackMap = false;
233 
234   /// This boolean keeps track of whether there is a call
235   /// to builtin \@llvm.experimental.patchpoint.
236   bool HasPatchPoint = false;
237 
238   /// The prolog/epilog code inserter calculates the final stack
239   /// offsets for all of the fixed size objects, updating the Objects list
240   /// above.  It then updates StackSize to contain the number of bytes that need
241   /// to be allocated on entry to the function.
242   uint64_t StackSize = 0;
243 
244   /// The amount that a frame offset needs to be adjusted to
245   /// have the actual offset from the stack/frame pointer.  The exact usage of
246   /// this is target-dependent, but it is typically used to adjust between
247   /// SP-relative and FP-relative offsets.  E.G., if objects are accessed via
248   /// SP then OffsetAdjustment is zero; if FP is used, OffsetAdjustment is set
249   /// to the distance between the initial SP and the value in FP.  For many
250   /// targets, this value is only used when generating debug info (via
251   /// TargetRegisterInfo::getFrameIndexReference); when generating code, the
252   /// corresponding adjustments are performed directly.
253   int OffsetAdjustment = 0;
254 
255   /// The prolog/epilog code inserter may process objects that require greater
256   /// alignment than the default alignment the target provides.
257   /// To handle this, MaxAlignment is set to the maximum alignment
258   /// needed by the objects on the current frame.  If this is greater than the
259   /// native alignment maintained by the compiler, dynamic alignment code will
260   /// be needed.
261   ///
262   Align MaxAlignment;
263 
264   /// Set to true if this function adjusts the stack -- e.g.,
265   /// when calling another function. This is only valid during and after
266   /// prolog/epilog code insertion.
267   bool AdjustsStack = false;
268 
269   /// Set to true if this function has any function calls.
270   bool HasCalls = false;
271 
272   /// The frame index for the stack protector.
273   int StackProtectorIdx = -1;
274 
275   /// The frame index for the function context. Used for SjLj exceptions.
276   int FunctionContextIdx = -1;
277 
278   /// This contains the size of the largest call frame if the target uses frame
279   /// setup/destroy pseudo instructions (as defined in the TargetFrameInfo
280   /// class).  This information is important for frame pointer elimination.
281   /// It is only valid during and after prolog/epilog code insertion.
282   unsigned MaxCallFrameSize = ~0u;
283 
284   /// The number of bytes of callee saved registers that the target wants to
285   /// report for the current function in the CodeView S_FRAMEPROC record.
286   unsigned CVBytesOfCalleeSavedRegisters = 0;
287 
288   /// The prolog/epilog code inserter fills in this vector with each
289   /// callee saved register saved in either the frame or a different
290   /// register.  Beyond its use by the prolog/ epilog code inserter,
291   /// this data is used for debug info and exception handling.
292   std::vector<CalleeSavedInfo> CSInfo;
293 
294   /// Has CSInfo been set yet?
295   bool CSIValid = false;
296 
297   /// References to frame indices which are mapped
298   /// into the local frame allocation block. <FrameIdx, LocalOffset>
299   SmallVector<std::pair<int, int64_t>, 32> LocalFrameObjects;
300 
301   /// Size of the pre-allocated local frame block.
302   int64_t LocalFrameSize = 0;
303 
304   /// Required alignment of the local object blob, which is the strictest
305   /// alignment of any object in it.
306   Align LocalFrameMaxAlign;
307 
308   /// Whether the local object blob needs to be allocated together. If not,
309   /// PEI should ignore the isPreAllocated flags on the stack objects and
310   /// just allocate them normally.
311   bool UseLocalStackAllocationBlock = false;
312 
313   /// True if the function dynamically adjusts the stack pointer through some
314   /// opaque mechanism like inline assembly or Win32 EH.
315   bool HasOpaqueSPAdjustment = false;
316 
317   /// True if the function contains operations which will lower down to
318   /// instructions which manipulate the stack pointer.
319   bool HasCopyImplyingStackAdjustment = false;
320 
321   /// True if the function contains a call to the llvm.vastart intrinsic.
322   bool HasVAStart = false;
323 
324   /// True if this is a varargs function that contains a musttail call.
325   bool HasMustTailInVarArgFunc = false;
326 
327   /// True if this function contains a tail call. If so immutable objects like
328   /// function arguments are no longer so. A tail call *can* override fixed
329   /// stack objects like arguments so we can't treat them as immutable.
330   bool HasTailCall = false;
331 
332   /// Not null, if shrink-wrapping found a better place for the prologue.
333   MachineBasicBlock *Save = nullptr;
334   /// Not null, if shrink-wrapping found a better place for the epilogue.
335   MachineBasicBlock *Restore = nullptr;
336 
337   /// Size of the UnsafeStack Frame
338   uint64_t UnsafeStackSize = 0;
339 
340 public:
341   explicit MachineFrameInfo(Align StackAlignment, bool StackRealignable,
342                             bool ForcedRealign)
343       : StackAlignment(StackAlignment),
344         StackRealignable(StackRealignable), ForcedRealign(ForcedRealign) {}
345 
346   MachineFrameInfo(const MachineFrameInfo &) = delete;
347 
348   /// Return true if there are any stack objects in this function.
349   bool hasStackObjects() const { return !Objects.empty(); }
350 
351   /// This method may be called any time after instruction
352   /// selection is complete to determine if the stack frame for this function
353   /// contains any variable sized objects.
354   bool hasVarSizedObjects() const { return HasVarSizedObjects; }
355 
356   /// Return the index for the stack protector object.
357   int getStackProtectorIndex() const { return StackProtectorIdx; }
358   void setStackProtectorIndex(int I) { StackProtectorIdx = I; }
359   bool hasStackProtectorIndex() const { return StackProtectorIdx != -1; }
360 
361   /// Return the index for the function context object.
362   /// This object is used for SjLj exceptions.
363   int getFunctionContextIndex() const { return FunctionContextIdx; }
364   void setFunctionContextIndex(int I) { FunctionContextIdx = I; }
365   bool hasFunctionContextIndex() const { return FunctionContextIdx != -1; }
366 
367   /// This method may be called any time after instruction
368   /// selection is complete to determine if there is a call to
369   /// \@llvm.frameaddress in this function.
370   bool isFrameAddressTaken() const { return FrameAddressTaken; }
371   void setFrameAddressIsTaken(bool T) { FrameAddressTaken = T; }
372 
373   /// This method may be called any time after
374   /// instruction selection is complete to determine if there is a call to
375   /// \@llvm.returnaddress in this function.
376   bool isReturnAddressTaken() const { return ReturnAddressTaken; }
377   void setReturnAddressIsTaken(bool s) { ReturnAddressTaken = s; }
378 
379   /// This method may be called any time after instruction
380   /// selection is complete to determine if there is a call to builtin
381   /// \@llvm.experimental.stackmap.
382   bool hasStackMap() const { return HasStackMap; }
383   void setHasStackMap(bool s = true) { HasStackMap = s; }
384 
385   /// This method may be called any time after instruction
386   /// selection is complete to determine if there is a call to builtin
387   /// \@llvm.experimental.patchpoint.
388   bool hasPatchPoint() const { return HasPatchPoint; }
389   void setHasPatchPoint(bool s = true) { HasPatchPoint = s; }
390 
391   /// Return true if this function requires a split stack prolog, even if it
392   /// uses no stack space. This is only meaningful for functions where
393   /// MachineFunction::shouldSplitStack() returns true.
394   //
395   // For non-leaf functions we have to allow for the possibility that the call
396   // is to a non-split function, as in PR37807. This function could also take
397   // the address of a non-split function. When the linker tries to adjust its
398   // non-existent prologue, it would fail with an error. Mark the object file so
399   // that such failures are not errors. See this Go language bug-report
400   // https://go-review.googlesource.com/c/go/+/148819/
401   bool needsSplitStackProlog() const {
402     return getStackSize() != 0 || hasTailCall();
403   }
404 
405   /// Return the minimum frame object index.
406   int getObjectIndexBegin() const { return -NumFixedObjects; }
407 
408   /// Return one past the maximum frame object index.
409   int getObjectIndexEnd() const { return (int)Objects.size()-NumFixedObjects; }
410 
411   /// Return the number of fixed objects.
412   unsigned getNumFixedObjects() const { return NumFixedObjects; }
413 
414   /// Return the number of objects.
415   unsigned getNumObjects() const { return Objects.size(); }
416 
417   /// Map a frame index into the local object block
418   void mapLocalFrameObject(int ObjectIndex, int64_t Offset) {
419     LocalFrameObjects.push_back(std::pair<int, int64_t>(ObjectIndex, Offset));
420     Objects[ObjectIndex + NumFixedObjects].PreAllocated = true;
421   }
422 
423   /// Get the local offset mapping for a for an object.
424   std::pair<int, int64_t> getLocalFrameObjectMap(int i) const {
425     assert (i >= 0 && (unsigned)i < LocalFrameObjects.size() &&
426             "Invalid local object reference!");
427     return LocalFrameObjects[i];
428   }
429 
430   /// Return the number of objects allocated into the local object block.
431   int64_t getLocalFrameObjectCount() const { return LocalFrameObjects.size(); }
432 
433   /// Set the size of the local object blob.
434   void setLocalFrameSize(int64_t sz) { LocalFrameSize = sz; }
435 
436   /// Get the size of the local object blob.
437   int64_t getLocalFrameSize() const { return LocalFrameSize; }
438 
439   /// Required alignment of the local object blob,
440   /// which is the strictest alignment of any object in it.
441   void setLocalFrameMaxAlign(Align Alignment) {
442     LocalFrameMaxAlign = Alignment;
443   }
444 
445   /// Return the required alignment of the local object blob.
446   Align getLocalFrameMaxAlign() const { return LocalFrameMaxAlign; }
447 
448   /// Get whether the local allocation blob should be allocated together or
449   /// let PEI allocate the locals in it directly.
450   bool getUseLocalStackAllocationBlock() const {
451     return UseLocalStackAllocationBlock;
452   }
453 
454   /// setUseLocalStackAllocationBlock - Set whether the local allocation blob
455   /// should be allocated together or let PEI allocate the locals in it
456   /// directly.
457   void setUseLocalStackAllocationBlock(bool v) {
458     UseLocalStackAllocationBlock = v;
459   }
460 
461   /// Return true if the object was pre-allocated into the local block.
462   bool isObjectPreAllocated(int ObjectIdx) const {
463     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
464            "Invalid Object Idx!");
465     return Objects[ObjectIdx+NumFixedObjects].PreAllocated;
466   }
467 
468   /// Return the size of the specified object.
469   int64_t getObjectSize(int ObjectIdx) const {
470     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
471            "Invalid Object Idx!");
472     return Objects[ObjectIdx+NumFixedObjects].Size;
473   }
474 
475   /// Change the size of the specified stack object.
476   void setObjectSize(int ObjectIdx, int64_t Size) {
477     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
478            "Invalid Object Idx!");
479     Objects[ObjectIdx+NumFixedObjects].Size = Size;
480   }
481 
482   /// Return the alignment of the specified stack object.
483   Align getObjectAlign(int ObjectIdx) const {
484     assert(unsigned(ObjectIdx + NumFixedObjects) < Objects.size() &&
485            "Invalid Object Idx!");
486     return Objects[ObjectIdx + NumFixedObjects].Alignment;
487   }
488 
489   /// setObjectAlignment - Change the alignment of the specified stack object.
490   void setObjectAlignment(int ObjectIdx, Align Alignment) {
491     assert(unsigned(ObjectIdx + NumFixedObjects) < Objects.size() &&
492            "Invalid Object Idx!");
493     Objects[ObjectIdx + NumFixedObjects].Alignment = Alignment;
494 
495     // Only ensure max alignment for the default stack.
496     if (getStackID(ObjectIdx) == 0)
497       ensureMaxAlignment(Alignment);
498   }
499 
500   /// Return the underlying Alloca of the specified
501   /// stack object if it exists. Returns 0 if none exists.
502   const AllocaInst* getObjectAllocation(int ObjectIdx) const {
503     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
504            "Invalid Object Idx!");
505     return Objects[ObjectIdx+NumFixedObjects].Alloca;
506   }
507 
508   /// Remove the underlying Alloca of the specified stack object if it
509   /// exists. This generally should not be used and is for reduction tooling.
510   void clearObjectAllocation(int ObjectIdx) {
511     assert(unsigned(ObjectIdx + NumFixedObjects) < Objects.size() &&
512            "Invalid Object Idx!");
513     Objects[ObjectIdx + NumFixedObjects].Alloca = nullptr;
514   }
515 
516   /// Return the assigned stack offset of the specified object
517   /// from the incoming stack pointer.
518   int64_t getObjectOffset(int ObjectIdx) const {
519     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
520            "Invalid Object Idx!");
521     assert(!isDeadObjectIndex(ObjectIdx) &&
522            "Getting frame offset for a dead object?");
523     return Objects[ObjectIdx+NumFixedObjects].SPOffset;
524   }
525 
526   bool isObjectZExt(int ObjectIdx) const {
527     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
528            "Invalid Object Idx!");
529     return Objects[ObjectIdx+NumFixedObjects].isZExt;
530   }
531 
532   void setObjectZExt(int ObjectIdx, bool IsZExt) {
533     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
534            "Invalid Object Idx!");
535     Objects[ObjectIdx+NumFixedObjects].isZExt = IsZExt;
536   }
537 
538   bool isObjectSExt(int ObjectIdx) const {
539     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
540            "Invalid Object Idx!");
541     return Objects[ObjectIdx+NumFixedObjects].isSExt;
542   }
543 
544   void setObjectSExt(int ObjectIdx, bool IsSExt) {
545     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
546            "Invalid Object Idx!");
547     Objects[ObjectIdx+NumFixedObjects].isSExt = IsSExt;
548   }
549 
550   /// Set the stack frame offset of the specified object. The
551   /// offset is relative to the stack pointer on entry to the function.
552   void setObjectOffset(int ObjectIdx, int64_t SPOffset) {
553     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
554            "Invalid Object Idx!");
555     assert(!isDeadObjectIndex(ObjectIdx) &&
556            "Setting frame offset for a dead object?");
557     Objects[ObjectIdx+NumFixedObjects].SPOffset = SPOffset;
558   }
559 
560   SSPLayoutKind getObjectSSPLayout(int ObjectIdx) const {
561     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
562            "Invalid Object Idx!");
563     return (SSPLayoutKind)Objects[ObjectIdx+NumFixedObjects].SSPLayout;
564   }
565 
566   void setObjectSSPLayout(int ObjectIdx, SSPLayoutKind Kind) {
567     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
568            "Invalid Object Idx!");
569     assert(!isDeadObjectIndex(ObjectIdx) &&
570            "Setting SSP layout for a dead object?");
571     Objects[ObjectIdx+NumFixedObjects].SSPLayout = Kind;
572   }
573 
574   /// Return the number of bytes that must be allocated to hold
575   /// all of the fixed size frame objects.  This is only valid after
576   /// Prolog/Epilog code insertion has finalized the stack frame layout.
577   uint64_t getStackSize() const { return StackSize; }
578 
579   /// Set the size of the stack.
580   void setStackSize(uint64_t Size) { StackSize = Size; }
581 
582   /// Estimate and return the size of the stack frame.
583   uint64_t estimateStackSize(const MachineFunction &MF) const;
584 
585   /// Return the correction for frame offsets.
586   int getOffsetAdjustment() const { return OffsetAdjustment; }
587 
588   /// Set the correction for frame offsets.
589   void setOffsetAdjustment(int Adj) { OffsetAdjustment = Adj; }
590 
591   /// Return the alignment in bytes that this function must be aligned to,
592   /// which is greater than the default stack alignment provided by the target.
593   Align getMaxAlign() const { return MaxAlignment; }
594 
595   /// Make sure the function is at least Align bytes aligned.
596   void ensureMaxAlignment(Align Alignment);
597 
598   /// Return true if this function adjusts the stack -- e.g.,
599   /// when calling another function. This is only valid during and after
600   /// prolog/epilog code insertion.
601   bool adjustsStack() const { return AdjustsStack; }
602   void setAdjustsStack(bool V) { AdjustsStack = V; }
603 
604   /// Return true if the current function has any function calls.
605   bool hasCalls() const { return HasCalls; }
606   void setHasCalls(bool V) { HasCalls = V; }
607 
608   /// Returns true if the function contains opaque dynamic stack adjustments.
609   bool hasOpaqueSPAdjustment() const { return HasOpaqueSPAdjustment; }
610   void setHasOpaqueSPAdjustment(bool B) { HasOpaqueSPAdjustment = B; }
611 
612   /// Returns true if the function contains operations which will lower down to
613   /// instructions which manipulate the stack pointer.
614   bool hasCopyImplyingStackAdjustment() const {
615     return HasCopyImplyingStackAdjustment;
616   }
617   void setHasCopyImplyingStackAdjustment(bool B) {
618     HasCopyImplyingStackAdjustment = B;
619   }
620 
621   /// Returns true if the function calls the llvm.va_start intrinsic.
622   bool hasVAStart() const { return HasVAStart; }
623   void setHasVAStart(bool B) { HasVAStart = B; }
624 
625   /// Returns true if the function is variadic and contains a musttail call.
626   bool hasMustTailInVarArgFunc() const { return HasMustTailInVarArgFunc; }
627   void setHasMustTailInVarArgFunc(bool B) { HasMustTailInVarArgFunc = B; }
628 
629   /// Returns true if the function contains a tail call.
630   bool hasTailCall() const { return HasTailCall; }
631   void setHasTailCall(bool V = true) { HasTailCall = V; }
632 
633   /// Computes the maximum size of a callframe and the AdjustsStack property.
634   /// This only works for targets defining
635   /// TargetInstrInfo::getCallFrameSetupOpcode(), getCallFrameDestroyOpcode(),
636   /// and getFrameSize().
637   /// This is usually computed by the prologue epilogue inserter but some
638   /// targets may call this to compute it earlier.
639   void computeMaxCallFrameSize(const MachineFunction &MF);
640 
641   /// Return the maximum size of a call frame that must be
642   /// allocated for an outgoing function call.  This is only available if
643   /// CallFrameSetup/Destroy pseudo instructions are used by the target, and
644   /// then only during or after prolog/epilog code insertion.
645   ///
646   unsigned getMaxCallFrameSize() const {
647     // TODO: Enable this assert when targets are fixed.
648     //assert(isMaxCallFrameSizeComputed() && "MaxCallFrameSize not computed yet");
649     if (!isMaxCallFrameSizeComputed())
650       return 0;
651     return MaxCallFrameSize;
652   }
653   bool isMaxCallFrameSizeComputed() const {
654     return MaxCallFrameSize != ~0u;
655   }
656   void setMaxCallFrameSize(unsigned S) { MaxCallFrameSize = S; }
657 
658   /// Returns how many bytes of callee-saved registers the target pushed in the
659   /// prologue. Only used for debug info.
660   unsigned getCVBytesOfCalleeSavedRegisters() const {
661     return CVBytesOfCalleeSavedRegisters;
662   }
663   void setCVBytesOfCalleeSavedRegisters(unsigned S) {
664     CVBytesOfCalleeSavedRegisters = S;
665   }
666 
667   /// Create a new object at a fixed location on the stack.
668   /// All fixed objects should be created before other objects are created for
669   /// efficiency. By default, fixed objects are not pointed to by LLVM IR
670   /// values. This returns an index with a negative value.
671   int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool IsImmutable,
672                         bool isAliased = false);
673 
674   /// Create a spill slot at a fixed location on the stack.
675   /// Returns an index with a negative value.
676   int CreateFixedSpillStackObject(uint64_t Size, int64_t SPOffset,
677                                   bool IsImmutable = false);
678 
679   /// Returns true if the specified index corresponds to a fixed stack object.
680   bool isFixedObjectIndex(int ObjectIdx) const {
681     return ObjectIdx < 0 && (ObjectIdx >= -(int)NumFixedObjects);
682   }
683 
684   /// Returns true if the specified index corresponds
685   /// to an object that might be pointed to by an LLVM IR value.
686   bool isAliasedObjectIndex(int ObjectIdx) const {
687     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
688            "Invalid Object Idx!");
689     return Objects[ObjectIdx+NumFixedObjects].isAliased;
690   }
691 
692   /// Returns true if the specified index corresponds to an immutable object.
693   bool isImmutableObjectIndex(int ObjectIdx) const {
694     // Tail calling functions can clobber their function arguments.
695     if (HasTailCall)
696       return false;
697     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
698            "Invalid Object Idx!");
699     return Objects[ObjectIdx+NumFixedObjects].isImmutable;
700   }
701 
702   /// Marks the immutability of an object.
703   void setIsImmutableObjectIndex(int ObjectIdx, bool IsImmutable) {
704     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
705            "Invalid Object Idx!");
706     Objects[ObjectIdx+NumFixedObjects].isImmutable = IsImmutable;
707   }
708 
709   /// Returns true if the specified index corresponds to a spill slot.
710   bool isSpillSlotObjectIndex(int ObjectIdx) const {
711     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
712            "Invalid Object Idx!");
713     return Objects[ObjectIdx+NumFixedObjects].isSpillSlot;
714   }
715 
716   bool isStatepointSpillSlotObjectIndex(int ObjectIdx) const {
717     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
718            "Invalid Object Idx!");
719     return Objects[ObjectIdx+NumFixedObjects].isStatepointSpillSlot;
720   }
721 
722   /// \see StackID
723   uint8_t getStackID(int ObjectIdx) const {
724     return Objects[ObjectIdx+NumFixedObjects].StackID;
725   }
726 
727   /// \see StackID
728   void setStackID(int ObjectIdx, uint8_t ID) {
729     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
730            "Invalid Object Idx!");
731     Objects[ObjectIdx+NumFixedObjects].StackID = ID;
732     // If ID > 0, MaxAlignment may now be overly conservative.
733     // If ID == 0, MaxAlignment will need to be updated separately.
734   }
735 
736   /// Returns true if the specified index corresponds to a dead object.
737   bool isDeadObjectIndex(int ObjectIdx) const {
738     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
739            "Invalid Object Idx!");
740     return Objects[ObjectIdx+NumFixedObjects].Size == ~0ULL;
741   }
742 
743   /// Returns true if the specified index corresponds to a variable sized
744   /// object.
745   bool isVariableSizedObjectIndex(int ObjectIdx) const {
746     assert(unsigned(ObjectIdx + NumFixedObjects) < Objects.size() &&
747            "Invalid Object Idx!");
748     return Objects[ObjectIdx + NumFixedObjects].Size == 0;
749   }
750 
751   void markAsStatepointSpillSlotObjectIndex(int ObjectIdx) {
752     assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
753            "Invalid Object Idx!");
754     Objects[ObjectIdx+NumFixedObjects].isStatepointSpillSlot = true;
755     assert(isStatepointSpillSlotObjectIndex(ObjectIdx) && "inconsistent");
756   }
757 
758   /// Create a new statically sized stack object, returning
759   /// a nonnegative identifier to represent it.
760   int CreateStackObject(uint64_t Size, Align Alignment, bool isSpillSlot,
761                         const AllocaInst *Alloca = nullptr, uint8_t ID = 0);
762 
763   /// Create a new statically sized stack object that represents a spill slot,
764   /// returning a nonnegative identifier to represent it.
765   int CreateSpillStackObject(uint64_t Size, Align Alignment);
766 
767   /// Remove or mark dead a statically sized stack object.
768   void RemoveStackObject(int ObjectIdx) {
769     // Mark it dead.
770     Objects[ObjectIdx+NumFixedObjects].Size = ~0ULL;
771   }
772 
773   /// Notify the MachineFrameInfo object that a variable sized object has been
774   /// created.  This must be created whenever a variable sized object is
775   /// created, whether or not the index returned is actually used.
776   int CreateVariableSizedObject(Align Alignment, const AllocaInst *Alloca);
777 
778   /// Returns a reference to call saved info vector for the current function.
779   const std::vector<CalleeSavedInfo> &getCalleeSavedInfo() const {
780     return CSInfo;
781   }
782   /// \copydoc getCalleeSavedInfo()
783   std::vector<CalleeSavedInfo> &getCalleeSavedInfo() { return CSInfo; }
784 
785   /// Used by prolog/epilog inserter to set the function's callee saved
786   /// information.
787   void setCalleeSavedInfo(std::vector<CalleeSavedInfo> CSI) {
788     CSInfo = std::move(CSI);
789   }
790 
791   /// Has the callee saved info been calculated yet?
792   bool isCalleeSavedInfoValid() const { return CSIValid; }
793 
794   void setCalleeSavedInfoValid(bool v) { CSIValid = v; }
795 
796   MachineBasicBlock *getSavePoint() const { return Save; }
797   void setSavePoint(MachineBasicBlock *NewSave) { Save = NewSave; }
798   MachineBasicBlock *getRestorePoint() const { return Restore; }
799   void setRestorePoint(MachineBasicBlock *NewRestore) { Restore = NewRestore; }
800 
801   uint64_t getUnsafeStackSize() const { return UnsafeStackSize; }
802   void setUnsafeStackSize(uint64_t Size) { UnsafeStackSize = Size; }
803 
804   /// Return a set of physical registers that are pristine.
805   ///
806   /// Pristine registers hold a value that is useless to the current function,
807   /// but that must be preserved - they are callee saved registers that are not
808   /// saved.
809   ///
810   /// Before the PrologueEpilogueInserter has placed the CSR spill code, this
811   /// method always returns an empty set.
812   BitVector getPristineRegs(const MachineFunction &MF) const;
813 
814   /// Used by the MachineFunction printer to print information about
815   /// stack objects. Implemented in MachineFunction.cpp.
816   void print(const MachineFunction &MF, raw_ostream &OS) const;
817 
818   /// dump - Print the function to stderr.
819   void dump(const MachineFunction &MF) const;
820 };
821 
822 } // End llvm namespace
823 
824 #endif
825