1 //===-- CodeGen/MachineFrameInfo.h - Abstract Stack Frame Rep. --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // The file defines the MachineFrameInfo class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CODEGEN_MACHINEFRAMEINFO_H
15 #define LLVM_CODEGEN_MACHINEFRAMEINFO_H
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/Support/DataTypes.h"
25 class TargetRegisterClass;
27 class MachineFunction;
28 class MachineBasicBlock;
29 class TargetFrameLowering;
35 /// The CalleeSavedInfo class tracks the information need to locate where a
36 /// callee saved register is in the current frame.
37 class CalleeSavedInfo {
42 explicit CalleeSavedInfo(unsigned R, int FI = 0)
43 : Reg(R), FrameIdx(FI) {}
46 unsigned getReg() const { return Reg; }
47 int getFrameIdx() const { return FrameIdx; }
48 void setFrameIdx(int FI) { FrameIdx = FI; }
51 /// The MachineFrameInfo class represents an abstract stack frame until
52 /// prolog/epilog code is inserted. This class is key to allowing stack frame
53 /// representation optimizations, such as frame pointer elimination. It also
54 /// allows more mundane (but still important) optimizations, such as reordering
55 /// of abstract objects on the stack frame.
57 /// To support this, the class assigns unique integer identifiers to stack
58 /// objects requested clients. These identifiers are negative integers for
59 /// fixed stack objects (such as arguments passed on the stack) or nonnegative
60 /// for objects that may be reordered. Instructions which refer to stack
61 /// objects use a special MO_FrameIndex operand to represent these frame
64 /// Because this class keeps track of all references to the stack frame, it
65 /// knows when a variable sized object is allocated on the stack. This is the
66 /// sole condition which prevents frame pointer elimination, which is an
67 /// important optimization on register-poor architectures. Because original
68 /// variable sized alloca's in the source program are the only source of
69 /// variable sized stack objects, it is safe to decide whether there will be
70 /// any variable sized objects before all stack objects are known (for
71 /// example, register allocator spill code never needs variable sized
74 /// When prolog/epilog code emission is performed, the final stack frame is
75 /// built and the machine instructions are modified to refer to the actual
76 /// stack offsets of the object, eliminating all MO_FrameIndex operands from
79 /// @brief Abstract Stack Frame Information
80 class MachineFrameInfo {
82 // Represent a single object allocated on the stack.
84 // The offset of this object from the stack pointer on entry to
85 // the function. This field has no meaning for a variable sized element.
88 // The size of this object on the stack. 0 means a variable sized object,
89 // ~0ULL means a dead object.
92 // The required alignment of this stack slot.
95 // If true, the value of the stack object is set before
96 // entering the function and is not modified inside the function. By
97 // default, fixed objects are immutable unless marked otherwise.
100 // If true the stack object is used as spill slot. It
101 // cannot alias any other memory objects.
104 /// If this stack object is originated from an Alloca instruction
105 /// this value saves the original IR allocation. Can be NULL.
106 const AllocaInst *Alloca;
108 // If true, the object was mapped into the local frame
109 // block and doesn't need additional handling for allocation beyond that.
112 // If true, an LLVM IR value might point to this object.
113 // Normally, spill slots and fixed-offset objects don't alias IR-accessible
114 // objects, but there are exceptions (on PowerPC, for example, some byval
115 // arguments have ABI-prescribed offsets).
118 StackObject(uint64_t Sz, unsigned Al, int64_t SP, bool IM,
119 bool isSS, const AllocaInst *Val, bool A)
120 : SPOffset(SP), Size(Sz), Alignment(Al), isImmutable(IM),
121 isSpillSlot(isSS), Alloca(Val), PreAllocated(false), isAliased(A) {}
124 /// The alignment of the stack.
125 unsigned StackAlignment;
127 /// Can the stack be realigned.
128 bool StackRealignable;
130 /// The list of stack objects allocated.
131 std::vector<StackObject> Objects;
133 /// This contains the number of fixed objects contained on
134 /// the stack. Because fixed objects are stored at a negative index in the
135 /// Objects list, this is also the index to the 0th object in the list.
136 unsigned NumFixedObjects;
138 /// This boolean keeps track of whether any variable
139 /// sized objects have been allocated yet.
140 bool HasVarSizedObjects;
142 /// This boolean keeps track of whether there is a call
143 /// to builtin \@llvm.frameaddress.
144 bool FrameAddressTaken;
146 /// This boolean keeps track of whether there is a call
147 /// to builtin \@llvm.returnaddress.
148 bool ReturnAddressTaken;
150 /// This boolean keeps track of whether there is a call
151 /// to builtin \@llvm.experimental.stackmap.
154 /// This boolean keeps track of whether there is a call
155 /// to builtin \@llvm.experimental.patchpoint.
158 /// The prolog/epilog code inserter calculates the final stack
159 /// offsets for all of the fixed size objects, updating the Objects list
160 /// above. It then updates StackSize to contain the number of bytes that need
161 /// to be allocated on entry to the function.
164 /// The amount that a frame offset needs to be adjusted to
165 /// have the actual offset from the stack/frame pointer. The exact usage of
166 /// this is target-dependent, but it is typically used to adjust between
167 /// SP-relative and FP-relative offsets. E.G., if objects are accessed via
168 /// SP then OffsetAdjustment is zero; if FP is used, OffsetAdjustment is set
169 /// to the distance between the initial SP and the value in FP. For many
170 /// targets, this value is only used when generating debug info (via
171 /// TargetRegisterInfo::getFrameIndexOffset); when generating code, the
172 /// corresponding adjustments are performed directly.
173 int OffsetAdjustment;
175 /// The prolog/epilog code inserter may process objects that require greater
176 /// alignment than the default alignment the target provides.
177 /// To handle this, MaxAlignment is set to the maximum alignment
178 /// needed by the objects on the current frame. If this is greater than the
179 /// native alignment maintained by the compiler, dynamic alignment code will
182 unsigned MaxAlignment;
184 /// Set to true if this function adjusts the stack -- e.g.,
185 /// when calling another function. This is only valid during and after
186 /// prolog/epilog code insertion.
189 /// Set to true if this function has any function calls.
192 /// The frame index for the stack protector.
193 int StackProtectorIdx;
195 /// The frame index for the function context. Used for SjLj exceptions.
196 int FunctionContextIdx;
198 /// This contains the size of the largest call frame if the target uses frame
199 /// setup/destroy pseudo instructions (as defined in the TargetFrameInfo
200 /// class). This information is important for frame pointer elimination.
201 /// If is only valid during and after prolog/epilog code insertion.
202 unsigned MaxCallFrameSize;
204 /// The prolog/epilog code inserter fills in this vector with each
205 /// callee saved register saved in the frame. Beyond its use by the prolog/
206 /// epilog code inserter, this data used for debug info and exception
208 std::vector<CalleeSavedInfo> CSInfo;
210 /// Has CSInfo been set yet?
213 /// References to frame indices which are mapped
214 /// into the local frame allocation block. <FrameIdx, LocalOffset>
215 SmallVector<std::pair<int, int64_t>, 32> LocalFrameObjects;
217 /// Size of the pre-allocated local frame block.
218 int64_t LocalFrameSize;
220 /// Required alignment of the local object blob, which is the strictest
221 /// alignment of any object in it.
222 unsigned LocalFrameMaxAlign;
224 /// Whether the local object blob needs to be allocated together. If not,
225 /// PEI should ignore the isPreAllocated flags on the stack objects and
226 /// just allocate them normally.
227 bool UseLocalStackAllocationBlock;
229 /// Whether the "realign-stack" option is on.
232 /// True if the function dynamically adjusts the stack pointer through some
233 /// opaque mechanism like inline assembly or Win32 EH.
234 bool HasOpaqueSPAdjustment;
236 /// True if the function contains a call to the llvm.vastart intrinsic.
239 /// True if this is a varargs function that contains a musttail call.
240 bool HasMustTailInVarArgFunc;
242 /// True if this function contains a tail call. If so immutable objects like
243 /// function arguments are no longer so. A tail call *can* override fixed
244 /// stack objects like arguments so we can't treat them as immutable.
247 /// Not null, if shrink-wrapping found a better place for the prologue.
248 MachineBasicBlock *Save;
249 /// Not null, if shrink-wrapping found a better place for the epilogue.
250 MachineBasicBlock *Restore;
253 explicit MachineFrameInfo(unsigned StackAlign, bool isStackRealign,
255 : StackAlignment(StackAlign), StackRealignable(isStackRealign),
256 RealignOption(RealignOpt) {
257 StackSize = NumFixedObjects = OffsetAdjustment = MaxAlignment = 0;
258 HasVarSizedObjects = false;
259 FrameAddressTaken = false;
260 ReturnAddressTaken = false;
262 HasPatchPoint = false;
263 AdjustsStack = false;
265 StackProtectorIdx = -1;
266 FunctionContextIdx = -1;
267 MaxCallFrameSize = 0;
270 LocalFrameMaxAlign = 0;
271 UseLocalStackAllocationBlock = false;
272 HasOpaqueSPAdjustment = false;
274 HasMustTailInVarArgFunc = false;
280 /// Return true if there are any stack objects in this function.
281 bool hasStackObjects() const { return !Objects.empty(); }
283 /// This method may be called any time after instruction
284 /// selection is complete to determine if the stack frame for this function
285 /// contains any variable sized objects.
286 bool hasVarSizedObjects() const { return HasVarSizedObjects; }
288 /// Return the index for the stack protector object.
289 int getStackProtectorIndex() const { return StackProtectorIdx; }
290 void setStackProtectorIndex(int I) { StackProtectorIdx = I; }
292 /// Return the index for the function context object.
293 /// This object is used for SjLj exceptions.
294 int getFunctionContextIndex() const { return FunctionContextIdx; }
295 void setFunctionContextIndex(int I) { FunctionContextIdx = I; }
297 /// This method may be called any time after instruction
298 /// selection is complete to determine if there is a call to
299 /// \@llvm.frameaddress in this function.
300 bool isFrameAddressTaken() const { return FrameAddressTaken; }
301 void setFrameAddressIsTaken(bool T) { FrameAddressTaken = T; }
303 /// This method may be called any time after
304 /// instruction selection is complete to determine if there is a call to
305 /// \@llvm.returnaddress in this function.
306 bool isReturnAddressTaken() const { return ReturnAddressTaken; }
307 void setReturnAddressIsTaken(bool s) { ReturnAddressTaken = s; }
309 /// This method may be called any time after instruction
310 /// selection is complete to determine if there is a call to builtin
311 /// \@llvm.experimental.stackmap.
312 bool hasStackMap() const { return HasStackMap; }
313 void setHasStackMap(bool s = true) { HasStackMap = s; }
315 /// This method may be called any time after instruction
316 /// selection is complete to determine if there is a call to builtin
317 /// \@llvm.experimental.patchpoint.
318 bool hasPatchPoint() const { return HasPatchPoint; }
319 void setHasPatchPoint(bool s = true) { HasPatchPoint = s; }
321 /// Return the minimum frame object index.
322 int getObjectIndexBegin() const { return -NumFixedObjects; }
324 /// Return one past the maximum frame object index.
325 int getObjectIndexEnd() const { return (int)Objects.size()-NumFixedObjects; }
327 /// Return the number of fixed objects.
328 unsigned getNumFixedObjects() const { return NumFixedObjects; }
330 /// Return the number of objects.
331 unsigned getNumObjects() const { return Objects.size(); }
333 /// Map a frame index into the local object block
334 void mapLocalFrameObject(int ObjectIndex, int64_t Offset) {
335 LocalFrameObjects.push_back(std::pair<int, int64_t>(ObjectIndex, Offset));
336 Objects[ObjectIndex + NumFixedObjects].PreAllocated = true;
339 /// Get the local offset mapping for a for an object.
340 std::pair<int, int64_t> getLocalFrameObjectMap(int i) {
341 assert (i >= 0 && (unsigned)i < LocalFrameObjects.size() &&
342 "Invalid local object reference!");
343 return LocalFrameObjects[i];
346 /// Return the number of objects allocated into the local object block.
347 int64_t getLocalFrameObjectCount() { return LocalFrameObjects.size(); }
349 /// Set the size of the local object blob.
350 void setLocalFrameSize(int64_t sz) { LocalFrameSize = sz; }
352 /// Get the size of the local object blob.
353 int64_t getLocalFrameSize() const { return LocalFrameSize; }
355 /// Required alignment of the local object blob,
356 /// which is the strictest alignment of any object in it.
357 void setLocalFrameMaxAlign(unsigned Align) { LocalFrameMaxAlign = Align; }
359 /// Return the required alignment of the local object blob.
360 unsigned getLocalFrameMaxAlign() const { return LocalFrameMaxAlign; }
362 /// Get whether the local allocation blob should be allocated together or
363 /// let PEI allocate the locals in it directly.
364 bool getUseLocalStackAllocationBlock() {return UseLocalStackAllocationBlock;}
366 /// setUseLocalStackAllocationBlock - Set whether the local allocation blob
367 /// should be allocated together or let PEI allocate the locals in it
369 void setUseLocalStackAllocationBlock(bool v) {
370 UseLocalStackAllocationBlock = v;
373 /// Return true if the object was pre-allocated into the local block.
374 bool isObjectPreAllocated(int ObjectIdx) const {
375 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
376 "Invalid Object Idx!");
377 return Objects[ObjectIdx+NumFixedObjects].PreAllocated;
380 /// Return the size of the specified object.
381 int64_t getObjectSize(int ObjectIdx) const {
382 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
383 "Invalid Object Idx!");
384 return Objects[ObjectIdx+NumFixedObjects].Size;
387 /// Change the size of the specified stack object.
388 void setObjectSize(int ObjectIdx, int64_t Size) {
389 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
390 "Invalid Object Idx!");
391 Objects[ObjectIdx+NumFixedObjects].Size = Size;
394 /// Return the alignment of the specified stack object.
395 unsigned getObjectAlignment(int ObjectIdx) const {
396 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
397 "Invalid Object Idx!");
398 return Objects[ObjectIdx+NumFixedObjects].Alignment;
401 /// setObjectAlignment - Change the alignment of the specified stack object.
402 void setObjectAlignment(int ObjectIdx, unsigned Align) {
403 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
404 "Invalid Object Idx!");
405 Objects[ObjectIdx+NumFixedObjects].Alignment = Align;
406 ensureMaxAlignment(Align);
409 /// Return the underlying Alloca of the specified
410 /// stack object if it exists. Returns 0 if none exists.
411 const AllocaInst* getObjectAllocation(int ObjectIdx) const {
412 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
413 "Invalid Object Idx!");
414 return Objects[ObjectIdx+NumFixedObjects].Alloca;
417 /// Return the assigned stack offset of the specified object
418 /// from the incoming stack pointer.
419 int64_t getObjectOffset(int ObjectIdx) const {
420 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
421 "Invalid Object Idx!");
422 assert(!isDeadObjectIndex(ObjectIdx) &&
423 "Getting frame offset for a dead object?");
424 return Objects[ObjectIdx+NumFixedObjects].SPOffset;
427 /// Set the stack frame offset of the specified object. The
428 /// offset is relative to the stack pointer on entry to the function.
429 void setObjectOffset(int ObjectIdx, int64_t SPOffset) {
430 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
431 "Invalid Object Idx!");
432 assert(!isDeadObjectIndex(ObjectIdx) &&
433 "Setting frame offset for a dead object?");
434 Objects[ObjectIdx+NumFixedObjects].SPOffset = SPOffset;
437 /// Return the number of bytes that must be allocated to hold
438 /// all of the fixed size frame objects. This is only valid after
439 /// Prolog/Epilog code insertion has finalized the stack frame layout.
440 uint64_t getStackSize() const { return StackSize; }
442 /// Set the size of the stack.
443 void setStackSize(uint64_t Size) { StackSize = Size; }
445 /// Estimate and return the size of the stack frame.
446 unsigned estimateStackSize(const MachineFunction &MF) const;
448 /// Return the correction for frame offsets.
449 int getOffsetAdjustment() const { return OffsetAdjustment; }
451 /// Set the correction for frame offsets.
452 void setOffsetAdjustment(int Adj) { OffsetAdjustment = Adj; }
454 /// Return the alignment in bytes that this function must be aligned to,
455 /// which is greater than the default stack alignment provided by the target.
456 unsigned getMaxAlignment() const { return MaxAlignment; }
458 /// Make sure the function is at least Align bytes aligned.
459 void ensureMaxAlignment(unsigned Align);
461 /// Return true if this function adjusts the stack -- e.g.,
462 /// when calling another function. This is only valid during and after
463 /// prolog/epilog code insertion.
464 bool adjustsStack() const { return AdjustsStack; }
465 void setAdjustsStack(bool V) { AdjustsStack = V; }
467 /// Return true if the current function has any function calls.
468 bool hasCalls() const { return HasCalls; }
469 void setHasCalls(bool V) { HasCalls = V; }
471 /// Returns true if the function contains opaque dynamic stack adjustments.
472 bool hasOpaqueSPAdjustment() const { return HasOpaqueSPAdjustment; }
473 void setHasOpaqueSPAdjustment(bool B) { HasOpaqueSPAdjustment = B; }
475 /// Returns true if the function calls the llvm.va_start intrinsic.
476 bool hasVAStart() const { return HasVAStart; }
477 void setHasVAStart(bool B) { HasVAStart = B; }
479 /// Returns true if the function is variadic and contains a musttail call.
480 bool hasMustTailInVarArgFunc() const { return HasMustTailInVarArgFunc; }
481 void setHasMustTailInVarArgFunc(bool B) { HasMustTailInVarArgFunc = B; }
483 /// Returns true if the function contains a tail call.
484 bool hasTailCall() const { return HasTailCall; }
485 void setHasTailCall() { HasTailCall = true; }
487 /// Return the maximum size of a call frame that must be
488 /// allocated for an outgoing function call. This is only available if
489 /// CallFrameSetup/Destroy pseudo instructions are used by the target, and
490 /// then only during or after prolog/epilog code insertion.
492 unsigned getMaxCallFrameSize() const { return MaxCallFrameSize; }
493 void setMaxCallFrameSize(unsigned S) { MaxCallFrameSize = S; }
495 /// Create a new object at a fixed location on the stack.
496 /// All fixed objects should be created before other objects are created for
497 /// efficiency. By default, fixed objects are not pointed to by LLVM IR
498 /// values. This returns an index with a negative value.
499 int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool Immutable,
500 bool isAliased = false);
502 /// Create a spill slot at a fixed location on the stack.
503 /// Returns an index with a negative value.
504 int CreateFixedSpillStackObject(uint64_t Size, int64_t SPOffset);
506 /// Returns true if the specified index corresponds to a fixed stack object.
507 bool isFixedObjectIndex(int ObjectIdx) const {
508 return ObjectIdx < 0 && (ObjectIdx >= -(int)NumFixedObjects);
511 /// Returns true if the specified index corresponds
512 /// to an object that might be pointed to by an LLVM IR value.
513 bool isAliasedObjectIndex(int ObjectIdx) const {
514 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
515 "Invalid Object Idx!");
516 return Objects[ObjectIdx+NumFixedObjects].isAliased;
519 /// isImmutableObjectIndex - Returns true if the specified index corresponds
520 /// to an immutable object.
521 bool isImmutableObjectIndex(int ObjectIdx) const {
522 // Tail calling functions can clobber their function arguments.
525 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
526 "Invalid Object Idx!");
527 return Objects[ObjectIdx+NumFixedObjects].isImmutable;
530 /// Returns true if the specified index corresponds to a spill slot.
531 bool isSpillSlotObjectIndex(int ObjectIdx) const {
532 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
533 "Invalid Object Idx!");
534 return Objects[ObjectIdx+NumFixedObjects].isSpillSlot;
537 /// Returns true if the specified index corresponds to a dead object.
538 bool isDeadObjectIndex(int ObjectIdx) const {
539 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
540 "Invalid Object Idx!");
541 return Objects[ObjectIdx+NumFixedObjects].Size == ~0ULL;
544 /// Create a new statically sized stack object, returning
545 /// a nonnegative identifier to represent it.
546 int CreateStackObject(uint64_t Size, unsigned Alignment, bool isSS,
547 const AllocaInst *Alloca = nullptr);
549 /// Create a new statically sized stack object that represents a spill slot,
550 /// returning a nonnegative identifier to represent it.
551 int CreateSpillStackObject(uint64_t Size, unsigned Alignment);
553 /// Remove or mark dead a statically sized stack object.
554 void RemoveStackObject(int ObjectIdx) {
556 Objects[ObjectIdx+NumFixedObjects].Size = ~0ULL;
559 /// Notify the MachineFrameInfo object that a variable sized object has been
560 /// created. This must be created whenever a variable sized object is
561 /// created, whether or not the index returned is actually used.
562 int CreateVariableSizedObject(unsigned Alignment, const AllocaInst *Alloca);
564 /// Returns a reference to call saved info vector for the current function.
565 const std::vector<CalleeSavedInfo> &getCalleeSavedInfo() const {
569 /// Used by prolog/epilog inserter to set the function's callee saved
571 void setCalleeSavedInfo(const std::vector<CalleeSavedInfo> &CSI) {
575 /// Has the callee saved info been calculated yet?
576 bool isCalleeSavedInfoValid() const { return CSIValid; }
578 void setCalleeSavedInfoValid(bool v) { CSIValid = v; }
580 MachineBasicBlock *getSavePoint() const { return Save; }
581 void setSavePoint(MachineBasicBlock *NewSave) { Save = NewSave; }
582 MachineBasicBlock *getRestorePoint() const { return Restore; }
583 void setRestorePoint(MachineBasicBlock *NewRestore) { Restore = NewRestore; }
585 /// Return a set of physical registers that are pristine.
587 /// Pristine registers hold a value that is useless to the current function,
588 /// but that must be preserved - they are callee saved registers that are not
591 /// Before the PrologueEpilogueInserter has placed the CSR spill code, this
592 /// method always returns an empty set.
593 BitVector getPristineRegs(const MachineFunction &MF) const;
595 /// Used by the MachineFunction printer to print information about
596 /// stack objects. Implemented in MachineFunction.cpp.
597 void print(const MachineFunction &MF, raw_ostream &OS) const;
599 /// dump - Print the function to stderr.
600 void dump(const MachineFunction &MF) const;
603 } // End llvm namespace