1 //=- AArch64MachineFunctionInfo.h - AArch64 machine function info -*- 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 // This file declares AArch64-specific per-machine-function information.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_LIB_TARGET_AARCH64_AARCH64MACHINEFUNCTIONINFO_H
14 #define LLVM_LIB_TARGET_AARCH64_AARCH64MACHINEFUNCTIONINFO_H
15 
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/CodeGen/CallingConvLower.h"
21 #include "llvm/CodeGen/MIRYamlMapping.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/MC/MCLinkerOptimizationHint.h"
26 #include <cassert>
27 
28 namespace llvm {
29 
30 namespace yaml {
31 struct AArch64FunctionInfo;
32 } // end namespace yaml
33 
34 class MachineInstr;
35 
36 /// AArch64FunctionInfo - This class is derived from MachineFunctionInfo and
37 /// contains private AArch64-specific information for each MachineFunction.
38 class AArch64FunctionInfo final : public MachineFunctionInfo {
39   /// Backreference to the machine function.
40   MachineFunction &MF;
41 
42   /// Number of bytes of arguments this function has on the stack. If the callee
43   /// is expected to restore the argument stack this should be a multiple of 16,
44   /// all usable during a tail call.
45   ///
46   /// The alternative would forbid tail call optimisation in some cases: if we
47   /// want to transfer control from a function with 8-bytes of stack-argument
48   /// space to a function with 16-bytes then misalignment of this value would
49   /// make a stack adjustment necessary, which could not be undone by the
50   /// callee.
51   unsigned BytesInStackArgArea = 0;
52 
53   /// The number of bytes to restore to deallocate space for incoming
54   /// arguments. Canonically 0 in the C calling convention, but non-zero when
55   /// callee is expected to pop the args.
56   unsigned ArgumentStackToRestore = 0;
57 
58   /// Space just below incoming stack pointer reserved for arguments being
59   /// passed on the stack during a tail call. This will be the difference
60   /// between the largest tail call argument space needed in this function and
61   /// what's already available by reusing space of incoming arguments.
62   unsigned TailCallReservedStack = 0;
63 
64   /// HasStackFrame - True if this function has a stack frame. Set by
65   /// determineCalleeSaves().
66   bool HasStackFrame = false;
67 
68   /// Amount of stack frame size, not including callee-saved registers.
69   uint64_t LocalStackSize = 0;
70 
71   /// The start and end frame indices for the SVE callee saves.
72   int MinSVECSFrameIndex = 0;
73   int MaxSVECSFrameIndex = 0;
74 
75   /// Amount of stack frame size used for saving callee-saved registers.
76   unsigned CalleeSavedStackSize = 0;
77   unsigned SVECalleeSavedStackSize = 0;
78   bool HasCalleeSavedStackSize = false;
79 
80   /// Number of TLS accesses using the special (combinable)
81   /// _TLS_MODULE_BASE_ symbol.
82   unsigned NumLocalDynamicTLSAccesses = 0;
83 
84   /// FrameIndex for start of varargs area for arguments passed on the
85   /// stack.
86   int VarArgsStackIndex = 0;
87 
88   /// FrameIndex for start of varargs area for arguments passed in
89   /// general purpose registers.
90   int VarArgsGPRIndex = 0;
91 
92   /// Size of the varargs area for arguments passed in general purpose
93   /// registers.
94   unsigned VarArgsGPRSize = 0;
95 
96   /// FrameIndex for start of varargs area for arguments passed in
97   /// floating-point registers.
98   int VarArgsFPRIndex = 0;
99 
100   /// Size of the varargs area for arguments passed in floating-point
101   /// registers.
102   unsigned VarArgsFPRSize = 0;
103 
104   /// True if this function has a subset of CSRs that is handled explicitly via
105   /// copies.
106   bool IsSplitCSR = false;
107 
108   /// True when the stack gets realigned dynamically because the size of stack
109   /// frame is unknown at compile time. e.g., in case of VLAs.
110   bool StackRealigned = false;
111 
112   /// True when the callee-save stack area has unused gaps that may be used for
113   /// other stack allocations.
114   bool CalleeSaveStackHasFreeSpace = false;
115 
116   /// SRetReturnReg - sret lowering includes returning the value of the
117   /// returned struct in a register. This field holds the virtual register into
118   /// which the sret argument is passed.
119   unsigned SRetReturnReg = 0;
120   /// SVE stack size (for predicates and data vectors) are maintained here
121   /// rather than in FrameInfo, as the placement and Stack IDs are target
122   /// specific.
123   uint64_t StackSizeSVE = 0;
124 
125   /// HasCalculatedStackSizeSVE indicates whether StackSizeSVE is valid.
126   bool HasCalculatedStackSizeSVE = false;
127 
128   /// Has a value when it is known whether or not the function uses a
129   /// redzone, and no value otherwise.
130   /// Initialized during frame lowering, unless the function has the noredzone
131   /// attribute, in which case it is set to false at construction.
132   Optional<bool> HasRedZone;
133 
134   /// ForwardedMustTailRegParms - A list of virtual and physical registers
135   /// that must be forwarded to every musttail call.
136   SmallVector<ForwardedRegister, 1> ForwardedMustTailRegParms;
137 
138   /// FrameIndex for the tagged base pointer.
139   Optional<int> TaggedBasePointerIndex;
140 
141   /// Offset from SP-at-entry to the tagged base pointer.
142   /// Tagged base pointer is set up to point to the first (lowest address)
143   /// tagged stack slot.
144   unsigned TaggedBasePointerOffset;
145 
146   /// OutliningStyle denotes, if a function was outined, how it was outlined,
147   /// e.g. Tail Call, Thunk, or Function if none apply.
148   Optional<std::string> OutliningStyle;
149 
150   // Offset from SP-after-callee-saved-spills (i.e. SP-at-entry minus
151   // CalleeSavedStackSize) to the address of the frame record.
152   int CalleeSaveBaseToFrameRecordOffset = 0;
153 
154   /// SignReturnAddress is true if PAC-RET is enabled for the function with
155   /// defaults being sign non-leaf functions only, with the B key.
156   bool SignReturnAddress = false;
157 
158   /// SignReturnAddressAll modifies the default PAC-RET mode to signing leaf
159   /// functions as well.
160   bool SignReturnAddressAll = false;
161 
162   /// SignWithBKey modifies the default PAC-RET mode to signing with the B key.
163   bool SignWithBKey = false;
164 
165   /// BranchTargetEnforcement enables placing BTI instructions at potential
166   /// indirect branch destinations.
167   bool BranchTargetEnforcement = false;
168 
169   /// Whether this function has an extended frame record [Ctx, FP, LR]. If so,
170   /// bit 60 of the in-memory FP will be 1 to enable other tools to detect the
171   /// extended record.
172   bool HasSwiftAsyncContext = false;
173 
174   /// The stack slot where the Swift asynchronous context is stored.
175   int SwiftAsyncContextFrameIdx = std::numeric_limits<int>::max();
176 
177   /// True if the function need unwind information.
178   mutable Optional<bool> NeedsDwarfUnwindInfo;
179 
180   /// True if the function need asynchronous unwind information.
181   mutable Optional<bool> NeedsDwarfAsyncUnwindInfo;
182 
183 public:
184   explicit AArch64FunctionInfo(MachineFunction &MF);
185 
186   void initializeBaseYamlFields(const yaml::AArch64FunctionInfo &YamlMFI);
187 
188   unsigned getBytesInStackArgArea() const { return BytesInStackArgArea; }
189   void setBytesInStackArgArea(unsigned bytes) { BytesInStackArgArea = bytes; }
190 
191   unsigned getArgumentStackToRestore() const { return ArgumentStackToRestore; }
192   void setArgumentStackToRestore(unsigned bytes) {
193     ArgumentStackToRestore = bytes;
194   }
195 
196   unsigned getTailCallReservedStack() const { return TailCallReservedStack; }
197   void setTailCallReservedStack(unsigned bytes) {
198     TailCallReservedStack = bytes;
199   }
200 
201   bool hasCalculatedStackSizeSVE() const { return HasCalculatedStackSizeSVE; }
202 
203   void setStackSizeSVE(uint64_t S) {
204     HasCalculatedStackSizeSVE = true;
205     StackSizeSVE = S;
206   }
207 
208   uint64_t getStackSizeSVE() const { return StackSizeSVE; }
209 
210   bool hasStackFrame() const { return HasStackFrame; }
211   void setHasStackFrame(bool s) { HasStackFrame = s; }
212 
213   bool isStackRealigned() const { return StackRealigned; }
214   void setStackRealigned(bool s) { StackRealigned = s; }
215 
216   bool hasCalleeSaveStackFreeSpace() const {
217     return CalleeSaveStackHasFreeSpace;
218   }
219   void setCalleeSaveStackHasFreeSpace(bool s) {
220     CalleeSaveStackHasFreeSpace = s;
221   }
222   bool isSplitCSR() const { return IsSplitCSR; }
223   void setIsSplitCSR(bool s) { IsSplitCSR = s; }
224 
225   void setLocalStackSize(uint64_t Size) { LocalStackSize = Size; }
226   uint64_t getLocalStackSize() const { return LocalStackSize; }
227 
228   void setOutliningStyle(std::string Style) { OutliningStyle = Style; }
229   Optional<std::string> getOutliningStyle() const { return OutliningStyle; }
230 
231   void setCalleeSavedStackSize(unsigned Size) {
232     CalleeSavedStackSize = Size;
233     HasCalleeSavedStackSize = true;
234   }
235 
236   // When CalleeSavedStackSize has not been set (for example when
237   // some MachineIR pass is run in isolation), then recalculate
238   // the CalleeSavedStackSize directly from the CalleeSavedInfo.
239   // Note: This information can only be recalculated after PEI
240   // has assigned offsets to the callee save objects.
241   unsigned getCalleeSavedStackSize(const MachineFrameInfo &MFI) const {
242     bool ValidateCalleeSavedStackSize = false;
243 
244 #ifndef NDEBUG
245     // Make sure the calculated size derived from the CalleeSavedInfo
246     // equals the cached size that was calculated elsewhere (e.g. in
247     // determineCalleeSaves).
248     ValidateCalleeSavedStackSize = HasCalleeSavedStackSize;
249 #endif
250 
251     if (!HasCalleeSavedStackSize || ValidateCalleeSavedStackSize) {
252       assert(MFI.isCalleeSavedInfoValid() && "CalleeSavedInfo not calculated");
253       if (MFI.getCalleeSavedInfo().empty())
254         return 0;
255 
256       int64_t MinOffset = std::numeric_limits<int64_t>::max();
257       int64_t MaxOffset = std::numeric_limits<int64_t>::min();
258       for (const auto &Info : MFI.getCalleeSavedInfo()) {
259         int FrameIdx = Info.getFrameIdx();
260         if (MFI.getStackID(FrameIdx) != TargetStackID::Default)
261           continue;
262         int64_t Offset = MFI.getObjectOffset(FrameIdx);
263         int64_t ObjSize = MFI.getObjectSize(FrameIdx);
264         MinOffset = std::min<int64_t>(Offset, MinOffset);
265         MaxOffset = std::max<int64_t>(Offset + ObjSize, MaxOffset);
266       }
267 
268       if (SwiftAsyncContextFrameIdx != std::numeric_limits<int>::max()) {
269         int64_t Offset = MFI.getObjectOffset(getSwiftAsyncContextFrameIdx());
270         int64_t ObjSize = MFI.getObjectSize(getSwiftAsyncContextFrameIdx());
271         MinOffset = std::min<int64_t>(Offset, MinOffset);
272         MaxOffset = std::max<int64_t>(Offset + ObjSize, MaxOffset);
273       }
274 
275       unsigned Size = alignTo(MaxOffset - MinOffset, 16);
276       assert((!HasCalleeSavedStackSize || getCalleeSavedStackSize() == Size) &&
277              "Invalid size calculated for callee saves");
278       return Size;
279     }
280 
281     return getCalleeSavedStackSize();
282   }
283 
284   unsigned getCalleeSavedStackSize() const {
285     assert(HasCalleeSavedStackSize &&
286            "CalleeSavedStackSize has not been calculated");
287     return CalleeSavedStackSize;
288   }
289 
290   // Saves the CalleeSavedStackSize for SVE vectors in 'scalable bytes'
291   void setSVECalleeSavedStackSize(unsigned Size) {
292     SVECalleeSavedStackSize = Size;
293   }
294   unsigned getSVECalleeSavedStackSize() const {
295     return SVECalleeSavedStackSize;
296   }
297 
298   void setMinMaxSVECSFrameIndex(int Min, int Max) {
299     MinSVECSFrameIndex = Min;
300     MaxSVECSFrameIndex = Max;
301   }
302 
303   int getMinSVECSFrameIndex() const { return MinSVECSFrameIndex; }
304   int getMaxSVECSFrameIndex() const { return MaxSVECSFrameIndex; }
305 
306   void incNumLocalDynamicTLSAccesses() { ++NumLocalDynamicTLSAccesses; }
307   unsigned getNumLocalDynamicTLSAccesses() const {
308     return NumLocalDynamicTLSAccesses;
309   }
310 
311   Optional<bool> hasRedZone() const { return HasRedZone; }
312   void setHasRedZone(bool s) { HasRedZone = s; }
313 
314   int getVarArgsStackIndex() const { return VarArgsStackIndex; }
315   void setVarArgsStackIndex(int Index) { VarArgsStackIndex = Index; }
316 
317   int getVarArgsGPRIndex() const { return VarArgsGPRIndex; }
318   void setVarArgsGPRIndex(int Index) { VarArgsGPRIndex = Index; }
319 
320   unsigned getVarArgsGPRSize() const { return VarArgsGPRSize; }
321   void setVarArgsGPRSize(unsigned Size) { VarArgsGPRSize = Size; }
322 
323   int getVarArgsFPRIndex() const { return VarArgsFPRIndex; }
324   void setVarArgsFPRIndex(int Index) { VarArgsFPRIndex = Index; }
325 
326   unsigned getVarArgsFPRSize() const { return VarArgsFPRSize; }
327   void setVarArgsFPRSize(unsigned Size) { VarArgsFPRSize = Size; }
328 
329   unsigned getSRetReturnReg() const { return SRetReturnReg; }
330   void setSRetReturnReg(unsigned Reg) { SRetReturnReg = Reg; }
331 
332   unsigned getJumpTableEntrySize(int Idx) const {
333     return JumpTableEntryInfo[Idx].first;
334   }
335   MCSymbol *getJumpTableEntryPCRelSymbol(int Idx) const {
336     return JumpTableEntryInfo[Idx].second;
337   }
338   void setJumpTableEntryInfo(int Idx, unsigned Size, MCSymbol *PCRelSym) {
339     if ((unsigned)Idx >= JumpTableEntryInfo.size())
340       JumpTableEntryInfo.resize(Idx+1);
341     JumpTableEntryInfo[Idx] = std::make_pair(Size, PCRelSym);
342   }
343 
344   using SetOfInstructions = SmallPtrSet<const MachineInstr *, 16>;
345 
346   const SetOfInstructions &getLOHRelated() const { return LOHRelated; }
347 
348   // Shortcuts for LOH related types.
349   class MILOHDirective {
350     MCLOHType Kind;
351 
352     /// Arguments of this directive. Order matters.
353     SmallVector<const MachineInstr *, 3> Args;
354 
355   public:
356     using LOHArgs = ArrayRef<const MachineInstr *>;
357 
358     MILOHDirective(MCLOHType Kind, LOHArgs Args)
359         : Kind(Kind), Args(Args.begin(), Args.end()) {
360       assert(isValidMCLOHType(Kind) && "Invalid LOH directive type!");
361     }
362 
363     MCLOHType getKind() const { return Kind; }
364     LOHArgs getArgs() const { return Args; }
365   };
366 
367   using MILOHArgs = MILOHDirective::LOHArgs;
368   using MILOHContainer = SmallVector<MILOHDirective, 32>;
369 
370   const MILOHContainer &getLOHContainer() const { return LOHContainerSet; }
371 
372   /// Add a LOH directive of this @p Kind and this @p Args.
373   void addLOHDirective(MCLOHType Kind, MILOHArgs Args) {
374     LOHContainerSet.push_back(MILOHDirective(Kind, Args));
375     LOHRelated.insert(Args.begin(), Args.end());
376   }
377 
378   SmallVectorImpl<ForwardedRegister> &getForwardedMustTailRegParms() {
379     return ForwardedMustTailRegParms;
380   }
381 
382   Optional<int> getTaggedBasePointerIndex() const {
383     return TaggedBasePointerIndex;
384   }
385   void setTaggedBasePointerIndex(int Index) { TaggedBasePointerIndex = Index; }
386 
387   unsigned getTaggedBasePointerOffset() const {
388     return TaggedBasePointerOffset;
389   }
390   void setTaggedBasePointerOffset(unsigned Offset) {
391     TaggedBasePointerOffset = Offset;
392   }
393 
394   int getCalleeSaveBaseToFrameRecordOffset() const {
395     return CalleeSaveBaseToFrameRecordOffset;
396   }
397   void setCalleeSaveBaseToFrameRecordOffset(int Offset) {
398     CalleeSaveBaseToFrameRecordOffset = Offset;
399   }
400 
401   bool shouldSignReturnAddress() const;
402   bool shouldSignReturnAddress(bool SpillsLR) const;
403 
404   bool shouldSignWithBKey() const { return SignWithBKey; }
405 
406   bool branchTargetEnforcement() const { return BranchTargetEnforcement; }
407 
408   void setHasSwiftAsyncContext(bool HasContext) {
409     HasSwiftAsyncContext = HasContext;
410   }
411   bool hasSwiftAsyncContext() const { return HasSwiftAsyncContext; }
412 
413   void setSwiftAsyncContextFrameIdx(int FI) {
414     SwiftAsyncContextFrameIdx = FI;
415   }
416   int getSwiftAsyncContextFrameIdx() const { return SwiftAsyncContextFrameIdx; }
417 
418   bool needsDwarfUnwindInfo() const;
419   bool needsAsyncDwarfUnwindInfo() const;
420 
421 private:
422   // Hold the lists of LOHs.
423   MILOHContainer LOHContainerSet;
424   SetOfInstructions LOHRelated;
425 
426   SmallVector<std::pair<unsigned, MCSymbol *>, 2> JumpTableEntryInfo;
427 };
428 
429 namespace yaml {
430 struct AArch64FunctionInfo final : public yaml::MachineFunctionInfo {
431   Optional<bool> HasRedZone;
432 
433   AArch64FunctionInfo() = default;
434   AArch64FunctionInfo(const llvm::AArch64FunctionInfo &MFI);
435 
436   void mappingImpl(yaml::IO &YamlIO) override;
437   ~AArch64FunctionInfo() = default;
438 };
439 
440 template <> struct MappingTraits<AArch64FunctionInfo> {
441   static void mapping(IO &YamlIO, AArch64FunctionInfo &MFI) {
442     YamlIO.mapOptional("hasRedZone", MFI.HasRedZone);
443   }
444 };
445 
446 } // end namespace yaml
447 
448 } // end namespace llvm
449 
450 #endif // LLVM_LIB_TARGET_AARCH64_AARCH64MACHINEFUNCTIONINFO_H
451