1//===-- CodeGen/MachineFrameInfo.h - Abstract Stack Frame Rep. --*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// The file defines the MachineFrameInfo class.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CODEGEN_MACHINEFRAMEINFO_H
15#define LLVM_CODEGEN_MACHINEFRAMEINFO_H
16
17#include "llvm/ADT/SmallVector.h"
18#include "llvm/Support/DataTypes.h"
19#include <cassert>
20#include <vector>
21
22namespace llvm {
23class raw_ostream;
24class DataLayout;
25class TargetRegisterClass;
26class Type;
27class MachineFunction;
28class MachineBasicBlock;
29class TargetFrameLowering;
30class BitVector;
31class Value;
32class AllocaInst;
33
34/// The CalleeSavedInfo class tracks the information need to locate where a
35/// callee saved register is in the current frame.
36class CalleeSavedInfo {
37  unsigned Reg;
38  int FrameIdx;
39
40public:
41  explicit CalleeSavedInfo(unsigned R, int FI = 0)
42  : Reg(R), FrameIdx(FI) {}
43
44  // Accessors.
45  unsigned getReg()                        const { return Reg; }
46  int getFrameIdx()                        const { return FrameIdx; }
47  void setFrameIdx(int FI)                       { FrameIdx = FI; }
48};
49
50/// The MachineFrameInfo class represents an abstract stack frame until
51/// prolog/epilog code is inserted.  This class is key to allowing stack frame
52/// representation optimizations, such as frame pointer elimination.  It also
53/// allows more mundane (but still important) optimizations, such as reordering
54/// of abstract objects on the stack frame.
55///
56/// To support this, the class assigns unique integer identifiers to stack
57/// objects requested clients.  These identifiers are negative integers for
58/// fixed stack objects (such as arguments passed on the stack) or nonnegative
59/// for objects that may be reordered.  Instructions which refer to stack
60/// objects use a special MO_FrameIndex operand to represent these frame
61/// indexes.
62///
63/// Because this class keeps track of all references to the stack frame, it
64/// knows when a variable sized object is allocated on the stack.  This is the
65/// sole condition which prevents frame pointer elimination, which is an
66/// important optimization on register-poor architectures.  Because original
67/// variable sized alloca's in the source program are the only source of
68/// variable sized stack objects, it is safe to decide whether there will be
69/// any variable sized objects before all stack objects are known (for
70/// example, register allocator spill code never needs variable sized
71/// objects).
72///
73/// When prolog/epilog code emission is performed, the final stack frame is
74/// built and the machine instructions are modified to refer to the actual
75/// stack offsets of the object, eliminating all MO_FrameIndex operands from
76/// the program.
77///
78/// @brief Abstract Stack Frame Information
79class MachineFrameInfo {
80
81  // StackObject - Represent a single object allocated on the stack.
82  struct StackObject {
83    // SPOffset - The offset of this object from the stack pointer on entry to
84    // the function.  This field has no meaning for a variable sized element.
85    int64_t SPOffset;
86
87    // The size of this object on the stack. 0 means a variable sized object,
88    // ~0ULL means a dead object.
89    uint64_t Size;
90
91    // Alignment - The required alignment of this stack slot.
92    unsigned Alignment;
93
94    // isImmutable - If true, the value of the stack object is set before
95    // entering the function and is not modified inside the function. By
96    // default, fixed objects are immutable unless marked otherwise.
97    bool isImmutable;
98
99    // isSpillSlot - If true the stack object is used as spill slot. It
100    // cannot alias any other memory objects.
101    bool isSpillSlot;
102
103    // MayNeedSP - If true the stack object triggered the creation of the stack
104    // protector. We should allocate this object right after the stack
105    // protector.
106    bool MayNeedSP;
107
108    /// Alloca - If this stack object is originated from an Alloca instruction
109    /// this value saves the original IR allocation. Can be NULL.
110    const AllocaInst *Alloca;
111
112    // PreAllocated - If true, the object was mapped into the local frame
113    // block and doesn't need additional handling for allocation beyond that.
114    bool PreAllocated;
115
116    StackObject(uint64_t Sz, unsigned Al, int64_t SP, bool IM,
117                bool isSS, bool NSP, const AllocaInst *Val)
118      : SPOffset(SP), Size(Sz), Alignment(Al), isImmutable(IM),
119        isSpillSlot(isSS), MayNeedSP(NSP), Alloca(Val), PreAllocated(false) {}
120  };
121
122  /// Objects - The list of stack objects allocated...
123  ///
124  std::vector<StackObject> Objects;
125
126  /// NumFixedObjects - This contains the number of fixed objects contained on
127  /// the stack.  Because fixed objects are stored at a negative index in the
128  /// Objects list, this is also the index to the 0th object in the list.
129  ///
130  unsigned NumFixedObjects;
131
132  /// HasVarSizedObjects - This boolean keeps track of whether any variable
133  /// sized objects have been allocated yet.
134  ///
135  bool HasVarSizedObjects;
136
137  /// FrameAddressTaken - This boolean keeps track of whether there is a call
138  /// to builtin \@llvm.frameaddress.
139  bool FrameAddressTaken;
140
141  /// ReturnAddressTaken - This boolean keeps track of whether there is a call
142  /// to builtin \@llvm.returnaddress.
143  bool ReturnAddressTaken;
144
145  /// StackSize - The prolog/epilog code inserter calculates the final stack
146  /// offsets for all of the fixed size objects, updating the Objects list
147  /// above.  It then updates StackSize to contain the number of bytes that need
148  /// to be allocated on entry to the function.
149  ///
150  uint64_t StackSize;
151
152  /// OffsetAdjustment - The amount that a frame offset needs to be adjusted to
153  /// have the actual offset from the stack/frame pointer.  The exact usage of
154  /// this is target-dependent, but it is typically used to adjust between
155  /// SP-relative and FP-relative offsets.  E.G., if objects are accessed via
156  /// SP then OffsetAdjustment is zero; if FP is used, OffsetAdjustment is set
157  /// to the distance between the initial SP and the value in FP.  For many
158  /// targets, this value is only used when generating debug info (via
159  /// TargetRegisterInfo::getFrameIndexOffset); when generating code, the
160  /// corresponding adjustments are performed directly.
161  int OffsetAdjustment;
162
163  /// MaxAlignment - The prolog/epilog code inserter may process objects
164  /// that require greater alignment than the default alignment the target
165  /// provides. To handle this, MaxAlignment is set to the maximum alignment
166  /// needed by the objects on the current frame.  If this is greater than the
167  /// native alignment maintained by the compiler, dynamic alignment code will
168  /// be needed.
169  ///
170  unsigned MaxAlignment;
171
172  /// AdjustsStack - Set to true if this function adjusts the stack -- e.g.,
173  /// when calling another function. This is only valid during and after
174  /// prolog/epilog code insertion.
175  bool AdjustsStack;
176
177  /// HasCalls - Set to true if this function has any function calls.
178  bool HasCalls;
179
180  /// StackProtectorIdx - The frame index for the stack protector.
181  int StackProtectorIdx;
182
183  /// FunctionContextIdx - The frame index for the function context. Used for
184  /// SjLj exceptions.
185  int FunctionContextIdx;
186
187  /// MaxCallFrameSize - This contains the size of the largest call frame if the
188  /// target uses frame setup/destroy pseudo instructions (as defined in the
189  /// TargetFrameInfo class).  This information is important for frame pointer
190  /// elimination.  If is only valid during and after prolog/epilog code
191  /// insertion.
192  ///
193  unsigned MaxCallFrameSize;
194
195  /// CSInfo - The prolog/epilog code inserter fills in this vector with each
196  /// callee saved register saved in the frame.  Beyond its use by the prolog/
197  /// epilog code inserter, this data used for debug info and exception
198  /// handling.
199  std::vector<CalleeSavedInfo> CSInfo;
200
201  /// CSIValid - Has CSInfo been set yet?
202  bool CSIValid;
203
204  /// TargetFrameLowering - Target information about frame layout.
205  ///
206  const TargetFrameLowering &TFI;
207
208  /// LocalFrameObjects - References to frame indices which are mapped
209  /// into the local frame allocation block. <FrameIdx, LocalOffset>
210  SmallVector<std::pair<int, int64_t>, 32> LocalFrameObjects;
211
212  /// LocalFrameSize - Size of the pre-allocated local frame block.
213  int64_t LocalFrameSize;
214
215  /// Required alignment of the local object blob, which is the strictest
216  /// alignment of any object in it.
217  unsigned LocalFrameMaxAlign;
218
219  /// Whether the local object blob needs to be allocated together. If not,
220  /// PEI should ignore the isPreAllocated flags on the stack objects and
221  /// just allocate them normally.
222  bool UseLocalStackAllocationBlock;
223
224  /// Whether the "realign-stack" option is on.
225  bool RealignOption;
226public:
227    explicit MachineFrameInfo(const TargetFrameLowering &tfi, bool RealignOpt)
228    : TFI(tfi), RealignOption(RealignOpt) {
229    StackSize = NumFixedObjects = OffsetAdjustment = MaxAlignment = 0;
230    HasVarSizedObjects = false;
231    FrameAddressTaken = false;
232    ReturnAddressTaken = false;
233    AdjustsStack = false;
234    HasCalls = false;
235    StackProtectorIdx = -1;
236    FunctionContextIdx = -1;
237    MaxCallFrameSize = 0;
238    CSIValid = false;
239    LocalFrameSize = 0;
240    LocalFrameMaxAlign = 0;
241    UseLocalStackAllocationBlock = false;
242  }
243
244  /// hasStackObjects - Return true if there are any stack objects in this
245  /// function.
246  ///
247  bool hasStackObjects() const { return !Objects.empty(); }
248
249  /// hasVarSizedObjects - This method may be called any time after instruction
250  /// selection is complete to determine if the stack frame for this function
251  /// contains any variable sized objects.
252  ///
253  bool hasVarSizedObjects() const { return HasVarSizedObjects; }
254
255  /// getStackProtectorIndex/setStackProtectorIndex - Return the index for the
256  /// stack protector object.
257  ///
258  int getStackProtectorIndex() const { return StackProtectorIdx; }
259  void setStackProtectorIndex(int I) { StackProtectorIdx = I; }
260
261  /// getFunctionContextIndex/setFunctionContextIndex - Return the index for the
262  /// function context object. This object is used for SjLj exceptions.
263  int getFunctionContextIndex() const { return FunctionContextIdx; }
264  void setFunctionContextIndex(int I) { FunctionContextIdx = I; }
265
266  /// isFrameAddressTaken - This method may be called any time after instruction
267  /// selection is complete to determine if there is a call to
268  /// \@llvm.frameaddress in this function.
269  bool isFrameAddressTaken() const { return FrameAddressTaken; }
270  void setFrameAddressIsTaken(bool T) { FrameAddressTaken = T; }
271
272  /// isReturnAddressTaken - This method may be called any time after
273  /// instruction selection is complete to determine if there is a call to
274  /// \@llvm.returnaddress in this function.
275  bool isReturnAddressTaken() const { return ReturnAddressTaken; }
276  void setReturnAddressIsTaken(bool s) { ReturnAddressTaken = s; }
277
278  /// getObjectIndexBegin - Return the minimum frame object index.
279  ///
280  int getObjectIndexBegin() const { return -NumFixedObjects; }
281
282  /// getObjectIndexEnd - Return one past the maximum frame object index.
283  ///
284  int getObjectIndexEnd() const { return (int)Objects.size()-NumFixedObjects; }
285
286  /// getNumFixedObjects - Return the number of fixed objects.
287  unsigned getNumFixedObjects() const { return NumFixedObjects; }
288
289  /// getNumObjects - Return the number of objects.
290  ///
291  unsigned getNumObjects() const { return Objects.size(); }
292
293  /// mapLocalFrameObject - Map a frame index into the local object block
294  void mapLocalFrameObject(int ObjectIndex, int64_t Offset) {
295    LocalFrameObjects.push_back(std::pair<int, int64_t>(ObjectIndex, Offset));
296    Objects[ObjectIndex + NumFixedObjects].PreAllocated = true;
297  }
298
299  /// getLocalFrameObjectMap - Get the local offset mapping for a for an object
300  std::pair<int, int64_t> getLocalFrameObjectMap(int i) {
301    assert (i >= 0 && (unsigned)i < LocalFrameObjects.size() &&
302            "Invalid local object reference!");
303    return LocalFrameObjects[i];
304  }
305
306  /// getLocalFrameObjectCount - Return the number of objects allocated into
307  /// the local object block.
308  int64_t getLocalFrameObjectCount() { return LocalFrameObjects.size(); }
309
310  /// setLocalFrameSize - Set the size of the local object blob.
311  void setLocalFrameSize(int64_t sz) { LocalFrameSize = sz; }
312
313  /// getLocalFrameSize - Get the size of the local object blob.
314  int64_t getLocalFrameSize() const { return LocalFrameSize; }
315
316  /// setLocalFrameMaxAlign - Required alignment of the local object blob,
317  /// which is the strictest alignment of any object in it.
318  void setLocalFrameMaxAlign(unsigned Align) { LocalFrameMaxAlign = Align; }
319
320  /// getLocalFrameMaxAlign - Return the required alignment of the local
321  /// object blob.
322  unsigned getLocalFrameMaxAlign() const { return LocalFrameMaxAlign; }
323
324  /// getUseLocalStackAllocationBlock - Get whether the local allocation blob
325  /// should be allocated together or let PEI allocate the locals in it
326  /// directly.
327  bool getUseLocalStackAllocationBlock() {return UseLocalStackAllocationBlock;}
328
329  /// setUseLocalStackAllocationBlock - Set whether the local allocation blob
330  /// should be allocated together or let PEI allocate the locals in it
331  /// directly.
332  void setUseLocalStackAllocationBlock(bool v) {
333    UseLocalStackAllocationBlock = v;
334  }
335
336  /// isObjectPreAllocated - Return true if the object was pre-allocated into
337  /// the local block.
338  bool isObjectPreAllocated(int ObjectIdx) const {
339    assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
340           "Invalid Object Idx!");
341    return Objects[ObjectIdx+NumFixedObjects].PreAllocated;
342  }
343
344  /// getObjectSize - Return the size of the specified object.
345  ///
346  int64_t getObjectSize(int ObjectIdx) const {
347    assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
348           "Invalid Object Idx!");
349    return Objects[ObjectIdx+NumFixedObjects].Size;
350  }
351
352  /// setObjectSize - Change the size of the specified stack object.
353  void setObjectSize(int ObjectIdx, int64_t Size) {
354    assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
355           "Invalid Object Idx!");
356    Objects[ObjectIdx+NumFixedObjects].Size = Size;
357  }
358
359  /// getObjectAlignment - Return the alignment of the specified stack object.
360  unsigned getObjectAlignment(int ObjectIdx) const {
361    assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
362           "Invalid Object Idx!");
363    return Objects[ObjectIdx+NumFixedObjects].Alignment;
364  }
365
366  /// setObjectAlignment - Change the alignment of the specified stack object.
367  void setObjectAlignment(int ObjectIdx, unsigned Align) {
368    assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
369           "Invalid Object Idx!");
370    Objects[ObjectIdx+NumFixedObjects].Alignment = Align;
371    ensureMaxAlignment(Align);
372  }
373
374  /// getObjectAllocation - Return the underlying Alloca of the specified
375  /// stack object if it exists. Returns 0 if none exists.
376  const AllocaInst* getObjectAllocation(int ObjectIdx) const {
377    assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
378           "Invalid Object Idx!");
379    return Objects[ObjectIdx+NumFixedObjects].Alloca;
380  }
381
382  /// NeedsStackProtector - Returns true if the object may need stack
383  /// protectors.
384  bool MayNeedStackProtector(int ObjectIdx) const {
385    assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
386           "Invalid Object Idx!");
387    return Objects[ObjectIdx+NumFixedObjects].MayNeedSP;
388  }
389
390  /// getObjectOffset - Return the assigned stack offset of the specified object
391  /// from the incoming stack pointer.
392  ///
393  int64_t getObjectOffset(int ObjectIdx) const {
394    assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
395           "Invalid Object Idx!");
396    assert(!isDeadObjectIndex(ObjectIdx) &&
397           "Getting frame offset for a dead object?");
398    return Objects[ObjectIdx+NumFixedObjects].SPOffset;
399  }
400
401  /// setObjectOffset - Set the stack frame offset of the specified object.  The
402  /// offset is relative to the stack pointer on entry to the function.
403  ///
404  void setObjectOffset(int ObjectIdx, int64_t SPOffset) {
405    assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
406           "Invalid Object Idx!");
407    assert(!isDeadObjectIndex(ObjectIdx) &&
408           "Setting frame offset for a dead object?");
409    Objects[ObjectIdx+NumFixedObjects].SPOffset = SPOffset;
410  }
411
412  /// getStackSize - Return the number of bytes that must be allocated to hold
413  /// all of the fixed size frame objects.  This is only valid after
414  /// Prolog/Epilog code insertion has finalized the stack frame layout.
415  ///
416  uint64_t getStackSize() const { return StackSize; }
417
418  /// setStackSize - Set the size of the stack...
419  ///
420  void setStackSize(uint64_t Size) { StackSize = Size; }
421
422  /// Estimate and return the size of the stack frame.
423  unsigned estimateStackSize(const MachineFunction &MF) const;
424
425  /// getOffsetAdjustment - Return the correction for frame offsets.
426  ///
427  int getOffsetAdjustment() const { return OffsetAdjustment; }
428
429  /// setOffsetAdjustment - Set the correction for frame offsets.
430  ///
431  void setOffsetAdjustment(int Adj) { OffsetAdjustment = Adj; }
432
433  /// getMaxAlignment - Return the alignment in bytes that this function must be
434  /// aligned to, which is greater than the default stack alignment provided by
435  /// the target.
436  ///
437  unsigned getMaxAlignment() const { return MaxAlignment; }
438
439  /// ensureMaxAlignment - Make sure the function is at least Align bytes
440  /// aligned.
441  void ensureMaxAlignment(unsigned Align);
442
443  /// AdjustsStack - Return true if this function adjusts the stack -- e.g.,
444  /// when calling another function. This is only valid during and after
445  /// prolog/epilog code insertion.
446  bool adjustsStack() const { return AdjustsStack; }
447  void setAdjustsStack(bool V) { AdjustsStack = V; }
448
449  /// hasCalls - Return true if the current function has any function calls.
450  bool hasCalls() const { return HasCalls; }
451  void setHasCalls(bool V) { HasCalls = V; }
452
453  /// getMaxCallFrameSize - Return the maximum size of a call frame that must be
454  /// allocated for an outgoing function call.  This is only available if
455  /// CallFrameSetup/Destroy pseudo instructions are used by the target, and
456  /// then only during or after prolog/epilog code insertion.
457  ///
458  unsigned getMaxCallFrameSize() const { return MaxCallFrameSize; }
459  void setMaxCallFrameSize(unsigned S) { MaxCallFrameSize = S; }
460
461  /// CreateFixedObject - Create a new object at a fixed location on the stack.
462  /// All fixed objects should be created before other objects are created for
463  /// efficiency. By default, fixed objects are immutable. This returns an
464  /// index with a negative value.
465  ///
466  int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool Immutable);
467
468
469  /// isFixedObjectIndex - Returns true if the specified index corresponds to a
470  /// fixed stack object.
471  bool isFixedObjectIndex(int ObjectIdx) const {
472    return ObjectIdx < 0 && (ObjectIdx >= -(int)NumFixedObjects);
473  }
474
475  /// isImmutableObjectIndex - Returns true if the specified index corresponds
476  /// to an immutable object.
477  bool isImmutableObjectIndex(int ObjectIdx) const {
478    assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
479           "Invalid Object Idx!");
480    return Objects[ObjectIdx+NumFixedObjects].isImmutable;
481  }
482
483  /// isSpillSlotObjectIndex - Returns true if the specified index corresponds
484  /// to a spill slot..
485  bool isSpillSlotObjectIndex(int ObjectIdx) const {
486    assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
487           "Invalid Object Idx!");
488    return Objects[ObjectIdx+NumFixedObjects].isSpillSlot;
489  }
490
491  /// isDeadObjectIndex - Returns true if the specified index corresponds to
492  /// a dead object.
493  bool isDeadObjectIndex(int ObjectIdx) const {
494    assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
495           "Invalid Object Idx!");
496    return Objects[ObjectIdx+NumFixedObjects].Size == ~0ULL;
497  }
498
499  /// CreateStackObject - Create a new statically sized stack object, returning
500  /// a nonnegative identifier to represent it.
501  ///
502  int CreateStackObject(uint64_t Size, unsigned Alignment, bool isSS,
503                        bool MayNeedSP = false, const AllocaInst *Alloca = 0);
504
505  /// CreateSpillStackObject - Create a new statically sized stack object that
506  /// represents a spill slot, returning a nonnegative identifier to represent
507  /// it.
508  ///
509  int CreateSpillStackObject(uint64_t Size, unsigned Alignment);
510
511  /// RemoveStackObject - Remove or mark dead a statically sized stack object.
512  ///
513  void RemoveStackObject(int ObjectIdx) {
514    // Mark it dead.
515    Objects[ObjectIdx+NumFixedObjects].Size = ~0ULL;
516  }
517
518  /// CreateVariableSizedObject - Notify the MachineFrameInfo object that a
519  /// variable sized object has been created.  This must be created whenever a
520  /// variable sized object is created, whether or not the index returned is
521  /// actually used.
522  ///
523  int CreateVariableSizedObject(unsigned Alignment);
524
525  /// getCalleeSavedInfo - Returns a reference to call saved info vector for the
526  /// current function.
527  const std::vector<CalleeSavedInfo> &getCalleeSavedInfo() const {
528    return CSInfo;
529  }
530
531  /// setCalleeSavedInfo - Used by prolog/epilog inserter to set the function's
532  /// callee saved information.
533  void setCalleeSavedInfo(const std::vector<CalleeSavedInfo> &CSI) {
534    CSInfo = CSI;
535  }
536
537  /// isCalleeSavedInfoValid - Has the callee saved info been calculated yet?
538  bool isCalleeSavedInfoValid() const { return CSIValid; }
539
540  void setCalleeSavedInfoValid(bool v) { CSIValid = v; }
541
542  /// getPristineRegs - Return a set of physical registers that are pristine on
543  /// entry to the MBB.
544  ///
545  /// Pristine registers hold a value that is useless to the current function,
546  /// but that must be preserved - they are callee saved registers that have not
547  /// been saved yet.
548  ///
549  /// Before the PrologueEpilogueInserter has placed the CSR spill code, this
550  /// method always returns an empty set.
551  BitVector getPristineRegs(const MachineBasicBlock *MBB) const;
552
553  /// print - Used by the MachineFunction printer to print information about
554  /// stack objects. Implemented in MachineFunction.cpp
555  ///
556  void print(const MachineFunction &MF, raw_ostream &OS) const;
557
558  /// dump - Print the function to stderr.
559  void dump(const MachineFunction &MF) const;
560};
561
562} // End llvm namespace
563
564#endif
565