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 /// Targets that set this to false don't have the ability to overalign
129 /// their stack frame, and thus, overaligned allocas are all treated
130 /// as dynamic allocations and the target must handle them as part
131 /// of DYNAMIC_STACKALLOC lowering.
132 /// FIXME: There is room for improvement in this case, in terms of
133 /// grouping overaligned allocas into a "secondary stack frame" and
134 /// then only use a single alloca to allocate this frame and only a
135 /// single virtual register to access it. Currently, without such an
136 /// optimization, each such alloca gets it's own dynamic
138 bool StackRealignable;
140 /// The list of stack objects allocated.
141 std::vector<StackObject> Objects;
143 /// This contains the number of fixed objects contained on
144 /// the stack. Because fixed objects are stored at a negative index in the
145 /// Objects list, this is also the index to the 0th object in the list.
146 unsigned NumFixedObjects;
148 /// This boolean keeps track of whether any variable
149 /// sized objects have been allocated yet.
150 bool HasVarSizedObjects;
152 /// This boolean keeps track of whether there is a call
153 /// to builtin \@llvm.frameaddress.
154 bool FrameAddressTaken;
156 /// This boolean keeps track of whether there is a call
157 /// to builtin \@llvm.returnaddress.
158 bool ReturnAddressTaken;
160 /// This boolean keeps track of whether there is a call
161 /// to builtin \@llvm.experimental.stackmap.
164 /// This boolean keeps track of whether there is a call
165 /// to builtin \@llvm.experimental.patchpoint.
168 /// The prolog/epilog code inserter calculates the final stack
169 /// offsets for all of the fixed size objects, updating the Objects list
170 /// above. It then updates StackSize to contain the number of bytes that need
171 /// to be allocated on entry to the function.
174 /// The amount that a frame offset needs to be adjusted to
175 /// have the actual offset from the stack/frame pointer. The exact usage of
176 /// this is target-dependent, but it is typically used to adjust between
177 /// SP-relative and FP-relative offsets. E.G., if objects are accessed via
178 /// SP then OffsetAdjustment is zero; if FP is used, OffsetAdjustment is set
179 /// to the distance between the initial SP and the value in FP. For many
180 /// targets, this value is only used when generating debug info (via
181 /// TargetRegisterInfo::getFrameIndexReference); when generating code, the
182 /// corresponding adjustments are performed directly.
183 int OffsetAdjustment;
185 /// The prolog/epilog code inserter may process objects that require greater
186 /// alignment than the default alignment the target provides.
187 /// To handle this, MaxAlignment is set to the maximum alignment
188 /// needed by the objects on the current frame. If this is greater than the
189 /// native alignment maintained by the compiler, dynamic alignment code will
192 unsigned MaxAlignment;
194 /// Set to true if this function adjusts the stack -- e.g.,
195 /// when calling another function. This is only valid during and after
196 /// prolog/epilog code insertion.
199 /// Set to true if this function has any function calls.
202 /// The frame index for the stack protector.
203 int StackProtectorIdx;
205 /// The frame index for the function context. Used for SjLj exceptions.
206 int FunctionContextIdx;
208 /// This contains the size of the largest call frame if the target uses frame
209 /// setup/destroy pseudo instructions (as defined in the TargetFrameInfo
210 /// class). This information is important for frame pointer elimination.
211 /// It is only valid during and after prolog/epilog code insertion.
212 unsigned MaxCallFrameSize;
214 /// The prolog/epilog code inserter fills in this vector with each
215 /// callee saved register saved in the frame. Beyond its use by the prolog/
216 /// epilog code inserter, this data used for debug info and exception
218 std::vector<CalleeSavedInfo> CSInfo;
220 /// Has CSInfo been set yet?
223 /// References to frame indices which are mapped
224 /// into the local frame allocation block. <FrameIdx, LocalOffset>
225 SmallVector<std::pair<int, int64_t>, 32> LocalFrameObjects;
227 /// Size of the pre-allocated local frame block.
228 int64_t LocalFrameSize;
230 /// Required alignment of the local object blob, which is the strictest
231 /// alignment of any object in it.
232 unsigned LocalFrameMaxAlign;
234 /// Whether the local object blob needs to be allocated together. If not,
235 /// PEI should ignore the isPreAllocated flags on the stack objects and
236 /// just allocate them normally.
237 bool UseLocalStackAllocationBlock;
239 /// Whether the "realign-stack" option is on.
242 /// True if the function dynamically adjusts the stack pointer through some
243 /// opaque mechanism like inline assembly or Win32 EH.
244 bool HasOpaqueSPAdjustment;
246 /// True if the function contains a call to the llvm.vastart intrinsic.
249 /// True if this is a varargs function that contains a musttail call.
250 bool HasMustTailInVarArgFunc;
252 /// True if this function contains a tail call. If so immutable objects like
253 /// function arguments are no longer so. A tail call *can* override fixed
254 /// stack objects like arguments so we can't treat them as immutable.
257 /// Not null, if shrink-wrapping found a better place for the prologue.
258 MachineBasicBlock *Save;
259 /// Not null, if shrink-wrapping found a better place for the epilogue.
260 MachineBasicBlock *Restore;
263 explicit MachineFrameInfo(unsigned StackAlign, bool isStackRealign,
265 : StackAlignment(StackAlign), StackRealignable(isStackRealign),
266 RealignOption(RealignOpt) {
267 StackSize = NumFixedObjects = OffsetAdjustment = MaxAlignment = 0;
268 HasVarSizedObjects = false;
269 FrameAddressTaken = false;
270 ReturnAddressTaken = false;
272 HasPatchPoint = false;
273 AdjustsStack = false;
275 StackProtectorIdx = -1;
276 FunctionContextIdx = -1;
277 MaxCallFrameSize = 0;
280 LocalFrameMaxAlign = 0;
281 UseLocalStackAllocationBlock = false;
282 HasOpaqueSPAdjustment = false;
284 HasMustTailInVarArgFunc = false;
290 /// Return true if there are any stack objects in this function.
291 bool hasStackObjects() const { return !Objects.empty(); }
293 /// This method may be called any time after instruction
294 /// selection is complete to determine if the stack frame for this function
295 /// contains any variable sized objects.
296 bool hasVarSizedObjects() const { return HasVarSizedObjects; }
298 /// Return the index for the stack protector object.
299 int getStackProtectorIndex() const { return StackProtectorIdx; }
300 void setStackProtectorIndex(int I) { StackProtectorIdx = I; }
301 bool hasStackProtectorIndex() const { return StackProtectorIdx != -1; }
303 /// Return the index for the function context object.
304 /// This object is used for SjLj exceptions.
305 int getFunctionContextIndex() const { return FunctionContextIdx; }
306 void setFunctionContextIndex(int I) { FunctionContextIdx = I; }
308 /// This method may be called any time after instruction
309 /// selection is complete to determine if there is a call to
310 /// \@llvm.frameaddress in this function.
311 bool isFrameAddressTaken() const { return FrameAddressTaken; }
312 void setFrameAddressIsTaken(bool T) { FrameAddressTaken = T; }
314 /// This method may be called any time after
315 /// instruction selection is complete to determine if there is a call to
316 /// \@llvm.returnaddress in this function.
317 bool isReturnAddressTaken() const { return ReturnAddressTaken; }
318 void setReturnAddressIsTaken(bool s) { ReturnAddressTaken = s; }
320 /// This method may be called any time after instruction
321 /// selection is complete to determine if there is a call to builtin
322 /// \@llvm.experimental.stackmap.
323 bool hasStackMap() const { return HasStackMap; }
324 void setHasStackMap(bool s = true) { HasStackMap = s; }
326 /// This method may be called any time after instruction
327 /// selection is complete to determine if there is a call to builtin
328 /// \@llvm.experimental.patchpoint.
329 bool hasPatchPoint() const { return HasPatchPoint; }
330 void setHasPatchPoint(bool s = true) { HasPatchPoint = s; }
332 /// Return the minimum frame object index.
333 int getObjectIndexBegin() const { return -NumFixedObjects; }
335 /// Return one past the maximum frame object index.
336 int getObjectIndexEnd() const { return (int)Objects.size()-NumFixedObjects; }
338 /// Return the number of fixed objects.
339 unsigned getNumFixedObjects() const { return NumFixedObjects; }
341 /// Return the number of objects.
342 unsigned getNumObjects() const { return Objects.size(); }
344 /// Map a frame index into the local object block
345 void mapLocalFrameObject(int ObjectIndex, int64_t Offset) {
346 LocalFrameObjects.push_back(std::pair<int, int64_t>(ObjectIndex, Offset));
347 Objects[ObjectIndex + NumFixedObjects].PreAllocated = true;
350 /// Get the local offset mapping for a for an object.
351 std::pair<int, int64_t> getLocalFrameObjectMap(int i) const {
352 assert (i >= 0 && (unsigned)i < LocalFrameObjects.size() &&
353 "Invalid local object reference!");
354 return LocalFrameObjects[i];
357 /// Return the number of objects allocated into the local object block.
358 int64_t getLocalFrameObjectCount() const { return LocalFrameObjects.size(); }
360 /// Set the size of the local object blob.
361 void setLocalFrameSize(int64_t sz) { LocalFrameSize = sz; }
363 /// Get the size of the local object blob.
364 int64_t getLocalFrameSize() const { return LocalFrameSize; }
366 /// Required alignment of the local object blob,
367 /// which is the strictest alignment of any object in it.
368 void setLocalFrameMaxAlign(unsigned Align) { LocalFrameMaxAlign = Align; }
370 /// Return the required alignment of the local object blob.
371 unsigned getLocalFrameMaxAlign() const { return LocalFrameMaxAlign; }
373 /// Get whether the local allocation blob should be allocated together or
374 /// let PEI allocate the locals in it directly.
375 bool getUseLocalStackAllocationBlock() const {
376 return UseLocalStackAllocationBlock;
379 /// setUseLocalStackAllocationBlock - Set whether the local allocation blob
380 /// should be allocated together or let PEI allocate the locals in it
382 void setUseLocalStackAllocationBlock(bool v) {
383 UseLocalStackAllocationBlock = v;
386 /// Return true if the object was pre-allocated into the local block.
387 bool isObjectPreAllocated(int ObjectIdx) const {
388 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
389 "Invalid Object Idx!");
390 return Objects[ObjectIdx+NumFixedObjects].PreAllocated;
393 /// Return the size of the specified object.
394 int64_t getObjectSize(int ObjectIdx) const {
395 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
396 "Invalid Object Idx!");
397 return Objects[ObjectIdx+NumFixedObjects].Size;
400 /// Change the size of the specified stack object.
401 void setObjectSize(int ObjectIdx, int64_t Size) {
402 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
403 "Invalid Object Idx!");
404 Objects[ObjectIdx+NumFixedObjects].Size = Size;
407 /// Return the alignment of the specified stack object.
408 unsigned getObjectAlignment(int ObjectIdx) const {
409 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
410 "Invalid Object Idx!");
411 return Objects[ObjectIdx+NumFixedObjects].Alignment;
414 /// setObjectAlignment - Change the alignment of the specified stack object.
415 void setObjectAlignment(int ObjectIdx, unsigned Align) {
416 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
417 "Invalid Object Idx!");
418 Objects[ObjectIdx+NumFixedObjects].Alignment = Align;
419 ensureMaxAlignment(Align);
422 /// Return the underlying Alloca of the specified
423 /// stack object if it exists. Returns 0 if none exists.
424 const AllocaInst* getObjectAllocation(int ObjectIdx) const {
425 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
426 "Invalid Object Idx!");
427 return Objects[ObjectIdx+NumFixedObjects].Alloca;
430 /// Return the assigned stack offset of the specified object
431 /// from the incoming stack pointer.
432 int64_t getObjectOffset(int ObjectIdx) const {
433 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
434 "Invalid Object Idx!");
435 assert(!isDeadObjectIndex(ObjectIdx) &&
436 "Getting frame offset for a dead object?");
437 return Objects[ObjectIdx+NumFixedObjects].SPOffset;
440 /// Set the stack frame offset of the specified object. The
441 /// offset is relative to the stack pointer on entry to the function.
442 void setObjectOffset(int ObjectIdx, int64_t SPOffset) {
443 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
444 "Invalid Object Idx!");
445 assert(!isDeadObjectIndex(ObjectIdx) &&
446 "Setting frame offset for a dead object?");
447 Objects[ObjectIdx+NumFixedObjects].SPOffset = SPOffset;
450 /// Return the number of bytes that must be allocated to hold
451 /// all of the fixed size frame objects. This is only valid after
452 /// Prolog/Epilog code insertion has finalized the stack frame layout.
453 uint64_t getStackSize() const { return StackSize; }
455 /// Set the size of the stack.
456 void setStackSize(uint64_t Size) { StackSize = Size; }
458 /// Estimate and return the size of the stack frame.
459 unsigned estimateStackSize(const MachineFunction &MF) const;
461 /// Return the correction for frame offsets.
462 int getOffsetAdjustment() const { return OffsetAdjustment; }
464 /// Set the correction for frame offsets.
465 void setOffsetAdjustment(int Adj) { OffsetAdjustment = Adj; }
467 /// Return the alignment in bytes that this function must be aligned to,
468 /// which is greater than the default stack alignment provided by the target.
469 unsigned getMaxAlignment() const { return MaxAlignment; }
471 /// Make sure the function is at least Align bytes aligned.
472 void ensureMaxAlignment(unsigned Align);
474 /// Return true if this function adjusts the stack -- e.g.,
475 /// when calling another function. This is only valid during and after
476 /// prolog/epilog code insertion.
477 bool adjustsStack() const { return AdjustsStack; }
478 void setAdjustsStack(bool V) { AdjustsStack = V; }
480 /// Return true if the current function has any function calls.
481 bool hasCalls() const { return HasCalls; }
482 void setHasCalls(bool V) { HasCalls = V; }
484 /// Returns true if the function contains opaque dynamic stack adjustments.
485 bool hasOpaqueSPAdjustment() const { return HasOpaqueSPAdjustment; }
486 void setHasOpaqueSPAdjustment(bool B) { HasOpaqueSPAdjustment = B; }
488 /// Returns true if the function calls the llvm.va_start intrinsic.
489 bool hasVAStart() const { return HasVAStart; }
490 void setHasVAStart(bool B) { HasVAStart = B; }
492 /// Returns true if the function is variadic and contains a musttail call.
493 bool hasMustTailInVarArgFunc() const { return HasMustTailInVarArgFunc; }
494 void setHasMustTailInVarArgFunc(bool B) { HasMustTailInVarArgFunc = B; }
496 /// Returns true if the function contains a tail call.
497 bool hasTailCall() const { return HasTailCall; }
498 void setHasTailCall() { HasTailCall = true; }
500 /// Return the maximum size of a call frame that must be
501 /// allocated for an outgoing function call. This is only available if
502 /// CallFrameSetup/Destroy pseudo instructions are used by the target, and
503 /// then only during or after prolog/epilog code insertion.
505 unsigned getMaxCallFrameSize() const { return MaxCallFrameSize; }
506 void setMaxCallFrameSize(unsigned S) { MaxCallFrameSize = S; }
508 /// Create a new object at a fixed location on the stack.
509 /// All fixed objects should be created before other objects are created for
510 /// efficiency. By default, fixed objects are not pointed to by LLVM IR
511 /// values. This returns an index with a negative value.
512 int CreateFixedObject(uint64_t Size, int64_t SPOffset, bool Immutable,
513 bool isAliased = false);
515 /// Create a spill slot at a fixed location on the stack.
516 /// Returns an index with a negative value.
517 int CreateFixedSpillStackObject(uint64_t Size, int64_t SPOffset);
519 /// Returns true if the specified index corresponds to a fixed stack object.
520 bool isFixedObjectIndex(int ObjectIdx) const {
521 return ObjectIdx < 0 && (ObjectIdx >= -(int)NumFixedObjects);
524 /// Returns true if the specified index corresponds
525 /// to an object that might be pointed to by an LLVM IR value.
526 bool isAliasedObjectIndex(int ObjectIdx) const {
527 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
528 "Invalid Object Idx!");
529 return Objects[ObjectIdx+NumFixedObjects].isAliased;
532 /// isImmutableObjectIndex - Returns true if the specified index corresponds
533 /// to an immutable object.
534 bool isImmutableObjectIndex(int ObjectIdx) const {
535 // Tail calling functions can clobber their function arguments.
538 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
539 "Invalid Object Idx!");
540 return Objects[ObjectIdx+NumFixedObjects].isImmutable;
543 /// Returns true if the specified index corresponds to a spill slot.
544 bool isSpillSlotObjectIndex(int ObjectIdx) const {
545 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
546 "Invalid Object Idx!");
547 return Objects[ObjectIdx+NumFixedObjects].isSpillSlot;
550 /// Returns true if the specified index corresponds to a dead object.
551 bool isDeadObjectIndex(int ObjectIdx) const {
552 assert(unsigned(ObjectIdx+NumFixedObjects) < Objects.size() &&
553 "Invalid Object Idx!");
554 return Objects[ObjectIdx+NumFixedObjects].Size == ~0ULL;
557 /// Returns true if the specified index corresponds to a variable sized
559 bool isVariableSizedObjectIndex(int ObjectIdx) const {
560 assert(unsigned(ObjectIdx + NumFixedObjects) < Objects.size() &&
561 "Invalid Object Idx!");
562 return Objects[ObjectIdx + NumFixedObjects].Size == 0;
565 /// Create a new statically sized stack object, returning
566 /// a nonnegative identifier to represent it.
567 int CreateStackObject(uint64_t Size, unsigned Alignment, bool isSS,
568 const AllocaInst *Alloca = nullptr);
570 /// Create a new statically sized stack object that represents a spill slot,
571 /// returning a nonnegative identifier to represent it.
572 int CreateSpillStackObject(uint64_t Size, unsigned Alignment);
574 /// Remove or mark dead a statically sized stack object.
575 void RemoveStackObject(int ObjectIdx) {
577 Objects[ObjectIdx+NumFixedObjects].Size = ~0ULL;
580 /// Notify the MachineFrameInfo object that a variable sized object has been
581 /// created. This must be created whenever a variable sized object is
582 /// created, whether or not the index returned is actually used.
583 int CreateVariableSizedObject(unsigned Alignment, const AllocaInst *Alloca);
585 /// Returns a reference to call saved info vector for the current function.
586 const std::vector<CalleeSavedInfo> &getCalleeSavedInfo() const {
590 /// Used by prolog/epilog inserter to set the function's callee saved
592 void setCalleeSavedInfo(const std::vector<CalleeSavedInfo> &CSI) {
596 /// Has the callee saved info been calculated yet?
597 bool isCalleeSavedInfoValid() const { return CSIValid; }
599 void setCalleeSavedInfoValid(bool v) { CSIValid = v; }
601 MachineBasicBlock *getSavePoint() const { return Save; }
602 void setSavePoint(MachineBasicBlock *NewSave) { Save = NewSave; }
603 MachineBasicBlock *getRestorePoint() const { return Restore; }
604 void setRestorePoint(MachineBasicBlock *NewRestore) { Restore = NewRestore; }
606 /// Return a set of physical registers that are pristine.
608 /// Pristine registers hold a value that is useless to the current function,
609 /// but that must be preserved - they are callee saved registers that are not
612 /// Before the PrologueEpilogueInserter has placed the CSR spill code, this
613 /// method always returns an empty set.
614 BitVector getPristineRegs(const MachineFunction &MF) const;
616 /// Used by the MachineFunction printer to print information about
617 /// stack objects. Implemented in MachineFunction.cpp.
618 void print(const MachineFunction &MF, raw_ostream &OS) const;
620 /// dump - Print the function to stderr.
621 void dump(const MachineFunction &MF) const;
624 } // End llvm namespace