Revert "X86: Align the stack on word boundaries in LowerFormalArguments()"
[oota-llvm.git] / include / llvm / CodeGen / CallingConvLower.h
1 //===-- llvm/CallingConvLower.h - Calling Conventions -----------*- 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 // This file declares the CCState and CCValAssign classes, used for lowering
11 // and implementing calling conventions.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CODEGEN_CALLINGCONVLOWER_H
16 #define LLVM_CODEGEN_CALLINGCONVLOWER_H
17
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/CodeGen/MachineFrameInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/IR/CallingConv.h"
22 #include "llvm/Target/TargetCallingConv.h"
23
24 namespace llvm {
25 class CCState;
26 class MVT;
27 class TargetMachine;
28 class TargetRegisterInfo;
29
30 /// CCValAssign - Represent assignment of one arg/retval to a location.
31 class CCValAssign {
32 public:
33   enum LocInfo {
34     Full,   // The value fills the full location.
35     SExt,   // The value is sign extended in the location.
36     ZExt,   // The value is zero extended in the location.
37     AExt,   // The value is extended with undefined upper bits.
38     BCvt,   // The value is bit-converted in the location.
39     VExt,   // The value is vector-widened in the location.
40             // FIXME: Not implemented yet. Code that uses AExt to mean
41             // vector-widen should be fixed to use VExt instead.
42     FPExt,  // The floating-point value is fp-extended in the location.
43     Indirect // The location contains pointer to the value.
44     // TODO: a subset of the value is in the location.
45   };
46 private:
47   /// ValNo - This is the value number begin assigned (e.g. an argument number).
48   unsigned ValNo;
49
50   /// Loc is either a stack offset or a register number.
51   unsigned Loc;
52
53   /// isMem - True if this is a memory loc, false if it is a register loc.
54   unsigned isMem : 1;
55
56   /// isCustom - True if this arg/retval requires special handling.
57   unsigned isCustom : 1;
58
59   /// Information about how the value is assigned.
60   LocInfo HTP : 6;
61
62   /// ValVT - The type of the value being assigned.
63   MVT ValVT;
64
65   /// LocVT - The type of the location being assigned to.
66   MVT LocVT;
67 public:
68
69   static CCValAssign getReg(unsigned ValNo, MVT ValVT,
70                             unsigned RegNo, MVT LocVT,
71                             LocInfo HTP) {
72     CCValAssign Ret;
73     Ret.ValNo = ValNo;
74     Ret.Loc = RegNo;
75     Ret.isMem = false;
76     Ret.isCustom = false;
77     Ret.HTP = HTP;
78     Ret.ValVT = ValVT;
79     Ret.LocVT = LocVT;
80     return Ret;
81   }
82
83   static CCValAssign getCustomReg(unsigned ValNo, MVT ValVT,
84                                   unsigned RegNo, MVT LocVT,
85                                   LocInfo HTP) {
86     CCValAssign Ret;
87     Ret = getReg(ValNo, ValVT, RegNo, LocVT, HTP);
88     Ret.isCustom = true;
89     return Ret;
90   }
91
92   static CCValAssign getMem(unsigned ValNo, MVT ValVT,
93                             unsigned Offset, MVT LocVT,
94                             LocInfo HTP) {
95     CCValAssign Ret;
96     Ret.ValNo = ValNo;
97     Ret.Loc = Offset;
98     Ret.isMem = true;
99     Ret.isCustom = false;
100     Ret.HTP = HTP;
101     Ret.ValVT = ValVT;
102     Ret.LocVT = LocVT;
103     return Ret;
104   }
105
106   static CCValAssign getCustomMem(unsigned ValNo, MVT ValVT,
107                                   unsigned Offset, MVT LocVT,
108                                   LocInfo HTP) {
109     CCValAssign Ret;
110     Ret = getMem(ValNo, ValVT, Offset, LocVT, HTP);
111     Ret.isCustom = true;
112     return Ret;
113   }
114
115   // There is no need to differentiate between a pending CCValAssign and other
116   // kinds, as they are stored in a different list.
117   static CCValAssign getPending(unsigned ValNo, MVT ValVT, MVT LocVT,
118                                 LocInfo HTP) {
119     return getReg(ValNo, ValVT, 0, LocVT, HTP);
120   }
121
122   void convertToReg(unsigned RegNo) {
123     Loc = RegNo;
124     isMem = false;
125   }
126
127   void convertToMem(unsigned Offset) {
128     Loc = Offset;
129     isMem = true;
130   }
131
132   unsigned getValNo() const { return ValNo; }
133   MVT getValVT() const { return ValVT; }
134
135   bool isRegLoc() const { return !isMem; }
136   bool isMemLoc() const { return isMem; }
137
138   bool needsCustom() const { return isCustom; }
139
140   unsigned getLocReg() const { assert(isRegLoc()); return Loc; }
141   unsigned getLocMemOffset() const { assert(isMemLoc()); return Loc; }
142   MVT getLocVT() const { return LocVT; }
143
144   LocInfo getLocInfo() const { return HTP; }
145   bool isExtInLoc() const {
146     return (HTP == AExt || HTP == SExt || HTP == ZExt);
147   }
148
149 };
150
151 /// CCAssignFn - This function assigns a location for Val, updating State to
152 /// reflect the change.  It returns 'true' if it failed to handle Val.
153 typedef bool CCAssignFn(unsigned ValNo, MVT ValVT,
154                         MVT LocVT, CCValAssign::LocInfo LocInfo,
155                         ISD::ArgFlagsTy ArgFlags, CCState &State);
156
157 /// CCCustomFn - This function assigns a location for Val, possibly updating
158 /// all args to reflect changes and indicates if it handled it. It must set
159 /// isCustom if it handles the arg and returns true.
160 typedef bool CCCustomFn(unsigned &ValNo, MVT &ValVT,
161                         MVT &LocVT, CCValAssign::LocInfo &LocInfo,
162                         ISD::ArgFlagsTy &ArgFlags, CCState &State);
163
164 /// ParmContext - This enum tracks whether calling convention lowering is in
165 /// the context of prologue or call generation. Not all backends make use of
166 /// this information.
167 typedef enum { Unknown, Prologue, Call } ParmContext;
168
169 /// CCState - This class holds information needed while lowering arguments and
170 /// return values.  It captures which registers are already assigned and which
171 /// stack slots are used.  It provides accessors to allocate these values.
172 class CCState {
173 private:
174   CallingConv::ID CallingConv;
175   bool IsVarArg;
176   MachineFunction &MF;
177   const TargetRegisterInfo &TRI;
178   SmallVectorImpl<CCValAssign> &Locs;
179   LLVMContext &Context;
180
181   unsigned StackOffset;
182   SmallVector<uint32_t, 16> UsedRegs;
183   SmallVector<CCValAssign, 4> PendingLocs;
184
185   // ByValInfo and SmallVector<ByValInfo, 4> ByValRegs:
186   //
187   // Vector of ByValInfo instances (ByValRegs) is introduced for byval registers
188   // tracking.
189   // Or, in another words it tracks byval parameters that are stored in
190   // general purpose registers.
191   //
192   // For 4 byte stack alignment,
193   // instance index means byval parameter number in formal
194   // arguments set. Assume, we have some "struct_type" with size = 4 bytes,
195   // then, for function "foo":
196   //
197   // i32 foo(i32 %p, %struct_type* %r, i32 %s, %struct_type* %t)
198   //
199   // ByValRegs[0] describes how "%r" is stored (Begin == r1, End == r2)
200   // ByValRegs[1] describes how "%t" is stored (Begin == r3, End == r4).
201   //
202   // In case of 8 bytes stack alignment,
203   // ByValRegs may also contain information about wasted registers.
204   // In function shown above, r3 would be wasted according to AAPCS rules.
205   // And in that case ByValRegs[1].Waste would be "true".
206   // ByValRegs vector size still would be 2,
207   // while "%t" goes to the stack: it wouldn't be described in ByValRegs.
208   //
209   // Supposed use-case for this collection:
210   // 1. Initially ByValRegs is empty, InRegsParamsProceed is 0.
211   // 2. HandleByVal fillups ByValRegs.
212   // 3. Argument analysis (LowerFormatArguments, for example). After
213   // some byval argument was analyzed, InRegsParamsProceed is increased.
214   struct ByValInfo {
215     ByValInfo(unsigned B, unsigned E, bool IsWaste = false) :
216       Begin(B), End(E), Waste(IsWaste) {}
217     // First register allocated for current parameter.
218     unsigned Begin;
219
220     // First after last register allocated for current parameter.
221     unsigned End;
222
223     // Means that current range of registers doesn't belong to any
224     // parameters. It was wasted due to stack alignment rules.
225     // For more information see:
226     // AAPCS, 5.5 Parameter Passing, Stage C, C.3.
227     bool Waste;
228   };
229   SmallVector<ByValInfo, 4 > ByValRegs;
230
231   // InRegsParamsProceed - shows how many instances of ByValRegs was proceed
232   // during argument analysis.
233   unsigned InRegsParamsProceed;
234
235 protected:
236   ParmContext CallOrPrologue;
237
238 public:
239   CCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
240           SmallVectorImpl<CCValAssign> &locs, LLVMContext &C);
241
242   void addLoc(const CCValAssign &V) {
243     Locs.push_back(V);
244   }
245
246   LLVMContext &getContext() const { return Context; }
247   MachineFunction &getMachineFunction() const { return MF; }
248   CallingConv::ID getCallingConv() const { return CallingConv; }
249   bool isVarArg() const { return IsVarArg; }
250
251   unsigned getNextStackOffset() const { return StackOffset; }
252
253   /// isAllocated - Return true if the specified register (or an alias) is
254   /// allocated.
255   bool isAllocated(unsigned Reg) const {
256     return UsedRegs[Reg/32] & (1 << (Reg&31));
257   }
258
259   /// AnalyzeFormalArguments - Analyze an array of argument values,
260   /// incorporating info about the formals into this state.
261   void AnalyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Ins,
262                               CCAssignFn Fn);
263
264   /// AnalyzeReturn - Analyze the returned values of a return,
265   /// incorporating info about the result values into this state.
266   void AnalyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs,
267                      CCAssignFn Fn);
268
269   /// CheckReturn - Analyze the return values of a function, returning
270   /// true if the return can be performed without sret-demotion, and
271   /// false otherwise.
272   bool CheckReturn(const SmallVectorImpl<ISD::OutputArg> &ArgsFlags,
273                    CCAssignFn Fn);
274
275   /// AnalyzeCallOperands - Analyze the outgoing arguments to a call,
276   /// incorporating info about the passed values into this state.
277   void AnalyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Outs,
278                            CCAssignFn Fn);
279
280   /// AnalyzeCallOperands - Same as above except it takes vectors of types
281   /// and argument flags.
282   void AnalyzeCallOperands(SmallVectorImpl<MVT> &ArgVTs,
283                            SmallVectorImpl<ISD::ArgFlagsTy> &Flags,
284                            CCAssignFn Fn);
285
286   /// AnalyzeCallResult - Analyze the return values of a call,
287   /// incorporating info about the passed values into this state.
288   void AnalyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins,
289                          CCAssignFn Fn);
290
291   /// AnalyzeCallResult - Same as above except it's specialized for calls which
292   /// produce a single value.
293   void AnalyzeCallResult(MVT VT, CCAssignFn Fn);
294
295   /// getFirstUnallocated - Return the first unallocated register in the set, or
296   /// NumRegs if they are all allocated.
297   unsigned getFirstUnallocated(const MCPhysReg *Regs, unsigned NumRegs) const {
298     for (unsigned i = 0; i != NumRegs; ++i)
299       if (!isAllocated(Regs[i]))
300         return i;
301     return NumRegs;
302   }
303
304   /// AllocateReg - Attempt to allocate one register.  If it is not available,
305   /// return zero.  Otherwise, return the register, marking it and any aliases
306   /// as allocated.
307   unsigned AllocateReg(unsigned Reg) {
308     if (isAllocated(Reg)) return 0;
309     MarkAllocated(Reg);
310     return Reg;
311   }
312
313   /// Version of AllocateReg with extra register to be shadowed.
314   unsigned AllocateReg(unsigned Reg, unsigned ShadowReg) {
315     if (isAllocated(Reg)) return 0;
316     MarkAllocated(Reg);
317     MarkAllocated(ShadowReg);
318     return Reg;
319   }
320
321   /// AllocateReg - Attempt to allocate one of the specified registers.  If none
322   /// are available, return zero.  Otherwise, return the first one available,
323   /// marking it and any aliases as allocated.
324   unsigned AllocateReg(const MCPhysReg *Regs, unsigned NumRegs) {
325     unsigned FirstUnalloc = getFirstUnallocated(Regs, NumRegs);
326     if (FirstUnalloc == NumRegs)
327       return 0;    // Didn't find the reg.
328
329     // Mark the register and any aliases as allocated.
330     unsigned Reg = Regs[FirstUnalloc];
331     MarkAllocated(Reg);
332     return Reg;
333   }
334
335   /// AllocateRegBlock - Attempt to allocate a block of RegsRequired consecutive
336   /// registers. If this is not possible, return zero. Otherwise, return the first
337   /// register of the block that were allocated, marking the entire block as allocated.
338   unsigned AllocateRegBlock(const uint16_t *Regs, unsigned NumRegs, unsigned RegsRequired) {
339     for (unsigned StartIdx = 0; StartIdx <= NumRegs - RegsRequired; ++StartIdx) {
340       bool BlockAvailable = true;
341       // Check for already-allocated regs in this block
342       for (unsigned BlockIdx = 0; BlockIdx < RegsRequired; ++BlockIdx) {
343         if (isAllocated(Regs[StartIdx + BlockIdx])) {
344           BlockAvailable = false;
345           break;
346         }
347       }
348       if (BlockAvailable) {
349         // Mark the entire block as allocated
350         for (unsigned BlockIdx = 0; BlockIdx < RegsRequired; ++BlockIdx) {
351           MarkAllocated(Regs[StartIdx + BlockIdx]);
352         }
353         return Regs[StartIdx];
354       }
355     }
356     // No block was available
357     return 0;
358   }
359
360   /// Version of AllocateReg with list of registers to be shadowed.
361   unsigned AllocateReg(const MCPhysReg *Regs, const MCPhysReg *ShadowRegs,
362                        unsigned NumRegs) {
363     unsigned FirstUnalloc = getFirstUnallocated(Regs, NumRegs);
364     if (FirstUnalloc == NumRegs)
365       return 0;    // Didn't find the reg.
366
367     // Mark the register and any aliases as allocated.
368     unsigned Reg = Regs[FirstUnalloc], ShadowReg = ShadowRegs[FirstUnalloc];
369     MarkAllocated(Reg);
370     MarkAllocated(ShadowReg);
371     return Reg;
372   }
373
374   /// AllocateStack - Allocate a chunk of stack space with the specified size
375   /// and alignment.
376   unsigned AllocateStack(unsigned Size, unsigned Align) {
377     assert(Align && ((Align - 1) & Align) == 0); // Align is power of 2.
378     StackOffset = ((StackOffset + Align - 1) & ~(Align - 1));
379     unsigned Result = StackOffset;
380     StackOffset += Size;
381     MF.getFrameInfo()->ensureMaxAlignment(Align);
382     return Result;
383   }
384
385   /// Version of AllocateStack with extra register to be shadowed.
386   unsigned AllocateStack(unsigned Size, unsigned Align, unsigned ShadowReg) {
387     MarkAllocated(ShadowReg);
388     return AllocateStack(Size, Align);
389   }
390
391   /// Version of AllocateStack with list of extra registers to be shadowed.
392   /// Note that, unlike AllocateReg, this shadows ALL of the shadow registers.
393   unsigned AllocateStack(unsigned Size, unsigned Align,
394                          const MCPhysReg *ShadowRegs, unsigned NumShadowRegs) {
395     for (unsigned i = 0; i < NumShadowRegs; ++i)
396       MarkAllocated(ShadowRegs[i]);
397     return AllocateStack(Size, Align);
398   }
399
400   // HandleByVal - Allocate a stack slot large enough to pass an argument by
401   // value. The size and alignment information of the argument is encoded in its
402   // parameter attribute.
403   void HandleByVal(unsigned ValNo, MVT ValVT,
404                    MVT LocVT, CCValAssign::LocInfo LocInfo,
405                    int MinSize, int MinAlign, ISD::ArgFlagsTy ArgFlags);
406
407   // Returns count of byval arguments that are to be stored (even partly)
408   // in registers.
409   unsigned getInRegsParamsCount() const { return ByValRegs.size(); }
410
411   // Returns count of byval in-regs arguments proceed.
412   unsigned getInRegsParamsProceed() const { return InRegsParamsProceed; }
413
414   // Get information about N-th byval parameter that is stored in registers.
415   // Here "ByValParamIndex" is N.
416   void getInRegsParamInfo(unsigned InRegsParamRecordIndex,
417                           unsigned& BeginReg, unsigned& EndReg) const {
418     assert(InRegsParamRecordIndex < ByValRegs.size() &&
419            "Wrong ByVal parameter index");
420
421     const ByValInfo& info = ByValRegs[InRegsParamRecordIndex];
422     BeginReg = info.Begin;
423     EndReg = info.End;
424   }
425
426   // Add information about parameter that is kept in registers.
427   void addInRegsParamInfo(unsigned RegBegin, unsigned RegEnd) {
428     ByValRegs.push_back(ByValInfo(RegBegin, RegEnd));
429   }
430
431   // Goes either to next byval parameter (excluding "waste" record), or
432   // to the end of collection.
433   // Returns false, if end is reached.
434   bool nextInRegsParam() {
435     unsigned e = ByValRegs.size();
436     if (InRegsParamsProceed < e)
437       ++InRegsParamsProceed;
438     return InRegsParamsProceed < e;
439   }
440
441   // Clear byval registers tracking info.
442   void clearByValRegsInfo() {
443     InRegsParamsProceed = 0;
444     ByValRegs.clear();
445   }
446
447   // Rewind byval registers tracking info.
448   void rewindByValRegsInfo() {
449     InRegsParamsProceed = 0;
450   }
451
452   ParmContext getCallOrPrologue() const { return CallOrPrologue; }
453
454   // Get list of pending assignments
455   SmallVectorImpl<llvm::CCValAssign> &getPendingLocs() {
456     return PendingLocs;
457   }
458
459 private:
460   /// MarkAllocated - Mark a register and all of its aliases as allocated.
461   void MarkAllocated(unsigned Reg);
462 };
463
464
465
466 } // end namespace llvm
467
468 #endif