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