blob: 248619fc2d594203897c327ccf00d5767b655e49 [file] [log] [blame]
Daniel Dunbar0dbe2272008-09-08 21:33:45 +00001//===----- CGCall.h - Encapsulate calling convention details ----*- 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// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
15#include "CGCall.h"
16#include "CodeGenFunction.h"
Daniel Dunbarb7688072008-09-10 00:41:16 +000017#include "CodeGenModule.h"
Daniel Dunbar6b1da0e2008-10-13 17:02:26 +000018#include "clang/Basic/TargetInfo.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000019#include "clang/AST/ASTContext.h"
20#include "clang/AST/Decl.h"
Anders Carlssonf6f8ae52009-04-03 22:48:58 +000021#include "clang/AST/DeclCXX.h"
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000022#include "clang/AST/DeclObjC.h"
Daniel Dunbar99037e52009-01-29 08:13:58 +000023#include "clang/AST/RecordLayout.h"
Devang Patel24095da2009-06-04 23:32:02 +000024#include "clang/Frontend/CompileOptions.h"
Daniel Dunbar56273772008-09-17 00:51:38 +000025#include "llvm/ADT/StringExtras.h"
Devang Pateld0646bd2008-09-24 01:01:36 +000026#include "llvm/Attributes.h"
Daniel Dunbard14151d2009-03-02 04:32:35 +000027#include "llvm/Support/CallSite.h"
Daniel Dunbarbe9eb092009-02-12 09:04:14 +000028#include "llvm/Support/MathExtras.h"
Daniel Dunbar54d1ccb2009-01-27 01:36:03 +000029#include "llvm/Target/TargetData.h"
Daniel Dunbar9eb5c6d2009-02-03 01:05:53 +000030
31#include "ABIInfo.h"
32
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000033using namespace clang;
34using namespace CodeGen;
35
36/***/
37
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000038// FIXME: Use iterator and sidestep silly type array creation.
39
Daniel Dunbar541b63b2009-02-02 23:23:47 +000040const
Douglas Gregor72564e72009-02-26 23:50:07 +000041CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionNoProtoType *FTNP) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +000042 return getFunctionInfo(FTNP->getResultType(),
43 llvm::SmallVector<QualType, 16>());
Daniel Dunbar45c25ba2008-09-10 04:01:49 +000044}
45
Daniel Dunbar541b63b2009-02-02 23:23:47 +000046const
Douglas Gregor72564e72009-02-26 23:50:07 +000047CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionProtoType *FTP) {
Daniel Dunbar541b63b2009-02-02 23:23:47 +000048 llvm::SmallVector<QualType, 16> ArgTys;
49 // FIXME: Kill copy.
Daniel Dunbar45c25ba2008-09-10 04:01:49 +000050 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
Daniel Dunbar541b63b2009-02-02 23:23:47 +000051 ArgTys.push_back(FTP->getArgType(i));
52 return getFunctionInfo(FTP->getResultType(), ArgTys);
Daniel Dunbar45c25ba2008-09-10 04:01:49 +000053}
54
Anders Carlssonf6f8ae52009-04-03 22:48:58 +000055const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXMethodDecl *MD) {
56 llvm::SmallVector<QualType, 16> ArgTys;
Chris Lattner3eb67ca2009-05-12 20:27:19 +000057 // Add the 'this' pointer unless this is a static method.
58 if (MD->isInstance())
59 ArgTys.push_back(MD->getThisType(Context));
Anders Carlssonf6f8ae52009-04-03 22:48:58 +000060
61 const FunctionProtoType *FTP = MD->getType()->getAsFunctionProtoType();
62 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
63 ArgTys.push_back(FTP->getArgType(i));
64 return getFunctionInfo(FTP->getResultType(), ArgTys);
65}
66
Daniel Dunbar541b63b2009-02-02 23:23:47 +000067const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionDecl *FD) {
Chris Lattner3eb67ca2009-05-12 20:27:19 +000068 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
Anders Carlssonf6f8ae52009-04-03 22:48:58 +000069 if (MD->isInstance())
70 return getFunctionInfo(MD);
Anders Carlssonf6f8ae52009-04-03 22:48:58 +000071
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000072 const FunctionType *FTy = FD->getType()->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +000073 if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FTy))
Daniel Dunbar541b63b2009-02-02 23:23:47 +000074 return getFunctionInfo(FTP);
Douglas Gregor72564e72009-02-26 23:50:07 +000075 return getFunctionInfo(cast<FunctionNoProtoType>(FTy));
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000076}
77
Daniel Dunbar541b63b2009-02-02 23:23:47 +000078const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const ObjCMethodDecl *MD) {
79 llvm::SmallVector<QualType, 16> ArgTys;
80 ArgTys.push_back(MD->getSelfDecl()->getType());
81 ArgTys.push_back(Context.getObjCSelType());
82 // FIXME: Kill copy?
Chris Lattner20732162009-02-20 06:23:21 +000083 for (ObjCMethodDecl::param_iterator i = MD->param_begin(),
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000084 e = MD->param_end(); i != e; ++i)
Daniel Dunbar541b63b2009-02-02 23:23:47 +000085 ArgTys.push_back((*i)->getType());
86 return getFunctionInfo(MD->getResultType(), ArgTys);
Daniel Dunbar0dbe2272008-09-08 21:33:45 +000087}
88
Daniel Dunbar541b63b2009-02-02 23:23:47 +000089const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
90 const CallArgList &Args) {
91 // FIXME: Kill copy.
92 llvm::SmallVector<QualType, 16> ArgTys;
Daniel Dunbar725ad312009-01-31 02:19:00 +000093 for (CallArgList::const_iterator i = Args.begin(), e = Args.end();
94 i != e; ++i)
Daniel Dunbar541b63b2009-02-02 23:23:47 +000095 ArgTys.push_back(i->second);
96 return getFunctionInfo(ResTy, ArgTys);
Daniel Dunbar725ad312009-01-31 02:19:00 +000097}
98
Daniel Dunbar541b63b2009-02-02 23:23:47 +000099const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
100 const FunctionArgList &Args) {
101 // FIXME: Kill copy.
102 llvm::SmallVector<QualType, 16> ArgTys;
Daniel Dunbarbb36d332009-02-02 21:43:58 +0000103 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
104 i != e; ++i)
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000105 ArgTys.push_back(i->second);
106 return getFunctionInfo(ResTy, ArgTys);
107}
108
109const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
110 const llvm::SmallVector<QualType, 16> &ArgTys) {
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000111 // Lookup or create unique function info.
112 llvm::FoldingSetNodeID ID;
113 CGFunctionInfo::Profile(ID, ResTy, ArgTys.begin(), ArgTys.end());
114
115 void *InsertPos = 0;
116 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, InsertPos);
117 if (FI)
118 return *FI;
119
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000120 // Construct the function info.
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000121 FI = new CGFunctionInfo(ResTy, ArgTys);
Daniel Dunbar35e67d42009-02-05 00:00:23 +0000122 FunctionInfos.InsertNode(FI, InsertPos);
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000123
124 // Compute ABI information.
Daniel Dunbar6bad2652009-02-03 06:51:18 +0000125 getABIInfo().computeInfo(*FI, getContext());
Daniel Dunbar88c2fa92009-02-03 05:31:23 +0000126
Daniel Dunbar40a6be62009-02-03 00:07:12 +0000127 return *FI;
Daniel Dunbar541b63b2009-02-02 23:23:47 +0000128}
129
130/***/
131
Daniel Dunbar6b1da0e2008-10-13 17:02:26 +0000132ABIInfo::~ABIInfo() {}
133
Daniel Dunbar6f7279b2009-02-04 23:24:38 +0000134void ABIArgInfo::dump() const {
135 fprintf(stderr, "(ABIArgInfo Kind=");
136 switch (TheKind) {
137 case Direct:
138 fprintf(stderr, "Direct");
139 break;
Daniel Dunbar6f7279b2009-02-04 23:24:38 +0000140 case Ignore:
141 fprintf(stderr, "Ignore");
142 break;
143 case Coerce:
144 fprintf(stderr, "Coerce Type=");
145 getCoerceToType()->print(llvm::errs());
Daniel Dunbar6f7279b2009-02-04 23:24:38 +0000146 break;
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000147 case Indirect:
148 fprintf(stderr, "Indirect Align=%d", getIndirectAlign());
Daniel Dunbar6f7279b2009-02-04 23:24:38 +0000149 break;
150 case Expand:
151 fprintf(stderr, "Expand");
152 break;
153 }
154 fprintf(stderr, ")\n");
155}
156
157/***/
158
Daniel Dunbar573b9072009-05-11 18:58:49 +0000159static bool isEmptyRecord(ASTContext &Context, QualType T);
160
161/// isEmptyField - Return true iff a the field is "empty", that is it
162/// is an unnamed bit-field or an (array of) empty record(s).
163static bool isEmptyField(ASTContext &Context, const FieldDecl *FD) {
164 if (FD->isUnnamedBitfield())
165 return true;
166
167 QualType FT = FD->getType();
Daniel Dunbarcc401dc2009-05-11 23:01:34 +0000168 // Constant arrays of empty records count as empty, strip them off.
169 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT))
170 FT = AT->getElementType();
Daniel Dunbar573b9072009-05-11 18:58:49 +0000171
172 return isEmptyRecord(Context, FT);
173}
174
175/// isEmptyRecord - Return true iff a structure contains only empty
176/// fields. Note that a structure with a flexible array member is not
Daniel Dunbar834af452008-09-17 21:22:33 +0000177/// considered empty.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000178static bool isEmptyRecord(ASTContext &Context, QualType T) {
Daniel Dunbar5bde6f42009-03-31 19:01:39 +0000179 const RecordType *RT = T->getAsRecordType();
Daniel Dunbar834af452008-09-17 21:22:33 +0000180 if (!RT)
181 return 0;
182 const RecordDecl *RD = RT->getDecl();
183 if (RD->hasFlexibleArrayMember())
184 return false;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000185 for (RecordDecl::field_iterator i = RD->field_begin(Context),
Daniel Dunbar573b9072009-05-11 18:58:49 +0000186 e = RD->field_end(Context); i != e; ++i)
187 if (!isEmptyField(Context, *i))
Daniel Dunbar834af452008-09-17 21:22:33 +0000188 return false;
Daniel Dunbar834af452008-09-17 21:22:33 +0000189 return true;
190}
191
192/// isSingleElementStruct - Determine if a structure is a "single
193/// element struct", i.e. it has exactly one non-empty field or
194/// exactly one field which is itself a single element
195/// struct. Structures with flexible array members are never
196/// considered single element structs.
197///
198/// \return The field declaration for the single non-empty field, if
199/// it exists.
Daniel Dunbardfc6b802009-04-01 07:08:38 +0000200static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Daniel Dunbar834af452008-09-17 21:22:33 +0000201 const RecordType *RT = T->getAsStructureType();
202 if (!RT)
203 return 0;
204
205 const RecordDecl *RD = RT->getDecl();
206 if (RD->hasFlexibleArrayMember())
207 return 0;
208
Daniel Dunbardfc6b802009-04-01 07:08:38 +0000209 const Type *Found = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000210 for (RecordDecl::field_iterator i = RD->field_begin(Context),
211 e = RD->field_end(Context); i != e; ++i) {
Daniel Dunbar834af452008-09-17 21:22:33 +0000212 const FieldDecl *FD = *i;
213 QualType FT = FD->getType();
214
Daniel Dunbar573b9072009-05-11 18:58:49 +0000215 // Ignore empty fields.
216 if (isEmptyField(Context, FD))
217 continue;
218
Daniel Dunbarcc401dc2009-05-11 23:01:34 +0000219 // If we already found an element then this isn't a single-element
220 // struct.
Daniel Dunbarfcab2ca2009-05-08 21:04:47 +0000221 if (Found)
Daniel Dunbar834af452008-09-17 21:22:33 +0000222 return 0;
Daniel Dunbarfcab2ca2009-05-08 21:04:47 +0000223
Daniel Dunbarcc401dc2009-05-11 23:01:34 +0000224 // Treat single element arrays as the element.
225 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
226 if (AT->getSize().getZExtValue() != 1)
227 break;
228 FT = AT->getElementType();
229 }
230
Daniel Dunbarfcab2ca2009-05-08 21:04:47 +0000231 if (!CodeGenFunction::hasAggregateLLVMType(FT)) {
Daniel Dunbardfc6b802009-04-01 07:08:38 +0000232 Found = FT.getTypePtr();
Daniel Dunbar834af452008-09-17 21:22:33 +0000233 } else {
Daniel Dunbardfc6b802009-04-01 07:08:38 +0000234 Found = isSingleElementStruct(FT, Context);
Daniel Dunbar834af452008-09-17 21:22:33 +0000235 if (!Found)
236 return 0;
237 }
238 }
239
240 return Found;
241}
242
243static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
244 if (!Ty->getAsBuiltinType() && !Ty->isPointerType())
245 return false;
246
247 uint64_t Size = Context.getTypeSize(Ty);
248 return Size == 32 || Size == 64;
249}
250
251static bool areAllFields32Or64BitBasicType(const RecordDecl *RD,
252 ASTContext &Context) {
Douglas Gregor6ab35242009-04-09 21:40:53 +0000253 for (RecordDecl::field_iterator i = RD->field_begin(Context),
254 e = RD->field_end(Context); i != e; ++i) {
Daniel Dunbar834af452008-09-17 21:22:33 +0000255 const FieldDecl *FD = *i;
256
257 if (!is32Or64BitBasicType(FD->getType(), Context))
258 return false;
259
Mike Stumpf5408fe2009-05-16 07:57:57 +0000260 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
261 // how to expand them yet, and the predicate for telling if a bitfield still
262 // counts as "basic" is more complicated than what we were doing previously.
Daniel Dunbare06a75f2009-03-11 22:05:26 +0000263 if (FD->isBitField())
264 return false;
Daniel Dunbar834af452008-09-17 21:22:33 +0000265 }
Daniel Dunbare06a75f2009-03-11 22:05:26 +0000266
Daniel Dunbar834af452008-09-17 21:22:33 +0000267 return true;
268}
269
Daniel Dunbar6b1da0e2008-10-13 17:02:26 +0000270namespace {
271/// DefaultABIInfo - The default implementation for ABI specific
272/// details. This implementation provides information which results in
Daniel Dunbar6bad2652009-02-03 06:51:18 +0000273/// self-consistent and sensible LLVM IR generation, but does not
274/// conform to any particular ABI.
Daniel Dunbar6b1da0e2008-10-13 17:02:26 +0000275class DefaultABIInfo : public ABIInfo {
Daniel Dunbar6bad2652009-02-03 06:51:18 +0000276 ABIArgInfo classifyReturnType(QualType RetTy,
277 ASTContext &Context) const;
278
279 ABIArgInfo classifyArgumentType(QualType RetTy,
280 ASTContext &Context) const;
Daniel Dunbar6b1da0e2008-10-13 17:02:26 +0000281
Daniel Dunbar6bad2652009-02-03 06:51:18 +0000282 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
283 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
284 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
285 it != ie; ++it)
286 it->info = classifyArgumentType(it->type, Context);
287 }
Daniel Dunbarb4094ea2009-02-10 20:44:09 +0000288
289 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
290 CodeGenFunction &CGF) const;
Daniel Dunbar6b1da0e2008-10-13 17:02:26 +0000291};
292
293/// X86_32ABIInfo - The X86-32 ABI information.
294class X86_32ABIInfo : public ABIInfo {
Douglas Gregor6ab35242009-04-09 21:40:53 +0000295 ASTContext &Context;
Eli Friedman9fd58e82009-03-23 23:26:24 +0000296 bool IsDarwin;
297
Daniel Dunbardfc6b802009-04-01 07:08:38 +0000298 static bool isRegisterSize(unsigned Size) {
299 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
300 }
301
Daniel Dunbarcf6bde32009-04-01 07:45:00 +0000302 static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context);
303
Daniel Dunbar6b1da0e2008-10-13 17:02:26 +0000304public:
Daniel Dunbar6bad2652009-02-03 06:51:18 +0000305 ABIArgInfo classifyReturnType(QualType RetTy,
306 ASTContext &Context) const;
Daniel Dunbar6b1da0e2008-10-13 17:02:26 +0000307
Daniel Dunbar6bad2652009-02-03 06:51:18 +0000308 ABIArgInfo classifyArgumentType(QualType RetTy,
309 ASTContext &Context) const;
310
311 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
312 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
313 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
314 it != ie; ++it)
315 it->info = classifyArgumentType(it->type, Context);
316 }
Daniel Dunbarb4094ea2009-02-10 20:44:09 +0000317
318 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
319 CodeGenFunction &CGF) const;
Eli Friedman9fd58e82009-03-23 23:26:24 +0000320
Douglas Gregor6ab35242009-04-09 21:40:53 +0000321 X86_32ABIInfo(ASTContext &Context, bool d)
322 : ABIInfo(), Context(Context), IsDarwin(d) {}
Daniel Dunbar6b1da0e2008-10-13 17:02:26 +0000323};
324}
325
Daniel Dunbarcf6bde32009-04-01 07:45:00 +0000326
327/// shouldReturnTypeInRegister - Determine if the given type should be
328/// passed in a register (for the Darwin ABI).
329bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
330 ASTContext &Context) {
331 uint64_t Size = Context.getTypeSize(Ty);
332
333 // Type must be register sized.
334 if (!isRegisterSize(Size))
335 return false;
336
337 if (Ty->isVectorType()) {
338 // 64- and 128- bit vectors inside structures are not returned in
339 // registers.
340 if (Size == 64 || Size == 128)
341 return false;
342
343 return true;
344 }
345
346 // If this is a builtin, pointer, or complex type, it is ok.
347 if (Ty->getAsBuiltinType() || Ty->isPointerType() || Ty->isAnyComplexType())
348 return true;
349
350 // Arrays are treated like records.
351 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
352 return shouldReturnTypeInRegister(AT->getElementType(), Context);
353
354 // Otherwise, it must be a record type.
355 const RecordType *RT = Ty->getAsRecordType();
356 if (!RT) return false;
357
358 // Structure types are passed in register if all fields would be
359 // passed in a register.
Douglas Gregor6ab35242009-04-09 21:40:53 +0000360 for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(Context),
361 e = RT->getDecl()->field_end(Context); i != e; ++i) {
Daniel Dunbarcf6bde32009-04-01 07:45:00 +0000362 const FieldDecl *FD = *i;
363
Daniel Dunbar573b9072009-05-11 18:58:49 +0000364 // Empty fields are ignored.
365 if (isEmptyField(Context, FD))
Daniel Dunbarcf6bde32009-04-01 07:45:00 +0000366 continue;
367
368 // Check fields recursively.
369 if (!shouldReturnTypeInRegister(FD->getType(), Context))
370 return false;
371 }
372
373 return true;
374}
375
Daniel Dunbar6b1da0e2008-10-13 17:02:26 +0000376ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
377 ASTContext &Context) const {
Daniel Dunbar0bcc5212009-02-03 06:30:17 +0000378 if (RetTy->isVoidType()) {
379 return ABIArgInfo::getIgnore();
Daniel Dunbar36043162009-04-01 06:13:08 +0000380 } else if (const VectorType *VT = RetTy->getAsVectorType()) {
381 // On Darwin, some vectors are returned in registers.
382 if (IsDarwin) {
383 uint64_t Size = Context.getTypeSize(RetTy);
384
385 // 128-bit vectors are a special case; they are returned in
386 // registers and we need to make sure to pick a type the LLVM
387 // backend will like.
388 if (Size == 128)
389 return ABIArgInfo::getCoerce(llvm::VectorType::get(llvm::Type::Int64Ty,
390 2));
391
392 // Always return in register if it fits in a general purpose
393 // register, or if it is 64 bits and has a single element.
394 if ((Size == 8 || Size == 16 || Size == 32) ||
395 (Size == 64 && VT->getNumElements() == 1))
396 return ABIArgInfo::getCoerce(llvm::IntegerType::get(Size));
397
398 return ABIArgInfo::getIndirect(0);
399 }
400
401 return ABIArgInfo::getDirect();
Daniel Dunbar0bcc5212009-02-03 06:30:17 +0000402 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
Daniel Dunbar8e034442009-04-27 18:31:32 +0000403 // Structures with flexible arrays are always indirect.
404 if (const RecordType *RT = RetTy->getAsStructureType())
405 if (RT->getDecl()->hasFlexibleArrayMember())
406 return ABIArgInfo::getIndirect(0);
407
Eli Friedman9fd58e82009-03-23 23:26:24 +0000408 // Outside of Darwin, structs and unions are always indirect.
409 if (!IsDarwin && !RetTy->isAnyComplexType())
410 return ABIArgInfo::getIndirect(0);
Daniel Dunbar8e034442009-04-27 18:31:32 +0000411
Daniel Dunbar834af452008-09-17 21:22:33 +0000412 // Classify "single element" structs as their element type.
Daniel Dunbardfc6b802009-04-01 07:08:38 +0000413 if (const Type *SeltTy = isSingleElementStruct(RetTy, Context)) {
Daniel Dunbar834af452008-09-17 21:22:33 +0000414 if (const BuiltinType *BT = SeltTy->getAsBuiltinType()) {
Daniel Dunbar834af452008-09-17 21:22:33 +0000415 if (BT->isIntegerType()) {
Daniel Dunbar2e001162009-05-08 21:30:11 +0000416 // We need to use the size of the structure, padding
417 // bit-fields can adjust that to be larger than the single
418 // element type.
419 uint64_t Size = Context.getTypeSize(RetTy);
Daniel Dunbar834af452008-09-17 21:22:33 +0000420 return ABIArgInfo::getCoerce(llvm::IntegerType::get((unsigned) Size));
421 } else if (BT->getKind() == BuiltinType::Float) {
Daniel Dunbar2e001162009-05-08 21:30:11 +0000422 assert(Context.getTypeSize(RetTy) == Context.getTypeSize(SeltTy) &&
423 "Unexpect single element structure size!");
Daniel Dunbar834af452008-09-17 21:22:33 +0000424 return ABIArgInfo::getCoerce(llvm::Type::FloatTy);
425 } else if (BT->getKind() == BuiltinType::Double) {
Daniel Dunbar2e001162009-05-08 21:30:11 +0000426 assert(Context.getTypeSize(RetTy) == Context.getTypeSize(SeltTy) &&
427 "Unexpect single element structure size!");
Daniel Dunbar834af452008-09-17 21:22:33 +0000428 return ABIArgInfo::getCoerce(llvm::Type::DoubleTy);
429 }
430 } else if (SeltTy->isPointerType()) {
Mike Stumpf5408fe2009-05-16 07:57:57 +0000431 // FIXME: It would be really nice if this could come out as the proper
432 // pointer type.
Daniel Dunbar834af452008-09-17 21:22:33 +0000433 llvm::Type *PtrTy =
434 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
435 return ABIArgInfo::getCoerce(PtrTy);
Daniel Dunbardfc6b802009-04-01 07:08:38 +0000436 } else if (SeltTy->isVectorType()) {
437 // 64- and 128-bit vectors are never returned in a
438 // register when inside a structure.
439 uint64_t Size = Context.getTypeSize(RetTy);
440 if (Size == 64 || Size == 128)
441 return ABIArgInfo::getIndirect(0);
442
443 return classifyReturnType(QualType(SeltTy, 0), Context);
Daniel Dunbar834af452008-09-17 21:22:33 +0000444 }
445 }
446
Daniel Dunbar836a0642009-05-12 17:00:20 +0000447 // Small structures which are register sized are generally returned
448 // in a register.
449 if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, Context)) {
450 uint64_t Size = Context.getTypeSize(RetTy);
451 return ABIArgInfo::getCoerce(llvm::IntegerType::get(Size));
Daniel Dunbarcf6bde32009-04-01 07:45:00 +0000452 }
Daniel Dunbardfc6b802009-04-01 07:08:38 +0000453
454 return ABIArgInfo::getIndirect(0);
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +0000455 } else {
Daniel Dunbar0bcc5212009-02-03 06:30:17 +0000456 return ABIArgInfo::getDirect();
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +0000457 }
458}
459
Daniel Dunbar6b1da0e2008-10-13 17:02:26 +0000460ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
Daniel Dunbarb4094ea2009-02-10 20:44:09 +0000461 ASTContext &Context) const {
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000462 // FIXME: Set alignment on indirect arguments.
Daniel Dunbarf0357382008-09-17 20:11:04 +0000463 if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000464 // Structures with flexible arrays are always indirect.
Daniel Dunbar834af452008-09-17 21:22:33 +0000465 if (const RecordType *RT = Ty->getAsStructureType())
466 if (RT->getDecl()->hasFlexibleArrayMember())
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000467 return ABIArgInfo::getIndirect(0);
Daniel Dunbar834af452008-09-17 21:22:33 +0000468
Daniel Dunbar3170c932009-02-05 01:50:07 +0000469 // Ignore empty structs.
Daniel Dunbar834af452008-09-17 21:22:33 +0000470 uint64_t Size = Context.getTypeSize(Ty);
471 if (Ty->isStructureType() && Size == 0)
Daniel Dunbar3170c932009-02-05 01:50:07 +0000472 return ABIArgInfo::getIgnore();
Daniel Dunbar834af452008-09-17 21:22:33 +0000473
474 // Expand structs with size <= 128-bits which consist only of
475 // basic types (int, long long, float, double, xxx*). This is
476 // non-recursive and does not ignore empty fields.
477 if (const RecordType *RT = Ty->getAsStructureType()) {
478 if (Context.getTypeSize(Ty) <= 4*32 &&
479 areAllFields32Or64BitBasicType(RT->getDecl(), Context))
480 return ABIArgInfo::getExpand();
481 }
482
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000483 return ABIArgInfo::getIndirect(0);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000484 } else {
Daniel Dunbar0bcc5212009-02-03 06:30:17 +0000485 return ABIArgInfo::getDirect();
Daniel Dunbar8951dbd2008-09-11 01:48:57 +0000486 }
487}
488
Daniel Dunbarb4094ea2009-02-10 20:44:09 +0000489llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
490 CodeGenFunction &CGF) const {
491 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
492 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
493
494 CGBuilderTy &Builder = CGF.Builder;
495 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
496 "ap");
497 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
498 llvm::Type *PTy =
499 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
500 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
501
Daniel Dunbar570f0cf2009-02-18 22:28:45 +0000502 uint64_t Offset =
503 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
Daniel Dunbarb4094ea2009-02-10 20:44:09 +0000504 llvm::Value *NextAddr =
505 Builder.CreateGEP(Addr,
Daniel Dunbar570f0cf2009-02-18 22:28:45 +0000506 llvm::ConstantInt::get(llvm::Type::Int32Ty, Offset),
Daniel Dunbarb4094ea2009-02-10 20:44:09 +0000507 "ap.next");
508 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
509
510 return AddrTyped;
511}
512
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000513namespace {
Daniel Dunbarc4503572009-01-31 00:06:58 +0000514/// X86_64ABIInfo - The X86_64 ABI information.
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000515class X86_64ABIInfo : public ABIInfo {
516 enum Class {
517 Integer = 0,
518 SSE,
519 SSEUp,
520 X87,
521 X87Up,
522 ComplexX87,
523 NoClass,
524 Memory
525 };
526
Daniel Dunbar8562ae72009-01-30 08:09:32 +0000527 /// merge - Implement the X86_64 ABI merging algorithm.
528 ///
Daniel Dunbarc4503572009-01-31 00:06:58 +0000529 /// Merge an accumulating classification \arg Accum with a field
530 /// classification \arg Field.
531 ///
532 /// \param Accum - The accumulating classification. This should
533 /// always be either NoClass or the result of a previous merge
534 /// call. In addition, this should never be Memory (the caller
535 /// should just return Memory for the aggregate).
536 Class merge(Class Accum, Class Field) const;
Daniel Dunbar8562ae72009-01-30 08:09:32 +0000537
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000538 /// classify - Determine the x86_64 register classes in which the
539 /// given type T should be passed.
540 ///
Daniel Dunbarc4503572009-01-31 00:06:58 +0000541 /// \param Lo - The classification for the parts of the type
542 /// residing in the low word of the containing object.
543 ///
544 /// \param Hi - The classification for the parts of the type
545 /// residing in the high word of the containing object.
546 ///
547 /// \param OffsetBase - The bit offset of this type in the
Daniel Dunbarcdf920e2009-01-30 22:40:15 +0000548 /// containing object. Some parameters are classified different
549 /// depending on whether they straddle an eightbyte boundary.
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000550 ///
551 /// If a word is unused its result will be NoClass; if a type should
552 /// be passed in Memory then at least the classification of \arg Lo
553 /// will be Memory.
554 ///
555 /// The \arg Lo class will be NoClass iff the argument is ignored.
556 ///
557 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
Daniel Dunbar6e53e9b2009-02-17 07:55:55 +0000558 /// also be ComplexX87.
Daniel Dunbare620ecd2009-01-30 00:47:38 +0000559 void classify(QualType T, ASTContext &Context, uint64_t OffsetBase,
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000560 Class &Lo, Class &Hi) const;
Daniel Dunbarc4503572009-01-31 00:06:58 +0000561
Daniel Dunbar644f4c32009-02-14 02:09:24 +0000562 /// getCoerceResult - Given a source type \arg Ty and an LLVM type
563 /// to coerce to, chose the best way to pass Ty in the same place
564 /// that \arg CoerceTo would be passed, but while keeping the
565 /// emitted code as simple as possible.
566 ///
Mike Stumpf5408fe2009-05-16 07:57:57 +0000567 /// FIXME: Note, this should be cleaned up to just take an enumeration of all
568 /// the ways we might want to pass things, instead of constructing an LLVM
569 /// type. This makes this code more explicit, and it makes it clearer that we
570 /// are also doing this for correctness in the case of passing scalar types.
Daniel Dunbar644f4c32009-02-14 02:09:24 +0000571 ABIArgInfo getCoerceResult(QualType Ty,
572 const llvm::Type *CoerceTo,
573 ASTContext &Context) const;
574
Daniel Dunbar86e13ee2009-05-26 16:37:37 +0000575 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
576 /// such that the argument will be passed in memory.
577 ABIArgInfo getIndirectResult(QualType Ty,
578 ASTContext &Context) const;
579
Daniel Dunbar6bad2652009-02-03 06:51:18 +0000580 ABIArgInfo classifyReturnType(QualType RetTy,
Daniel Dunbar59e5a0e2009-02-03 20:00:13 +0000581 ASTContext &Context) const;
582
583 ABIArgInfo classifyArgumentType(QualType Ty,
584 ASTContext &Context,
Daniel Dunbar3b4e9cd2009-02-10 17:06:09 +0000585 unsigned &neededInt,
586 unsigned &neededSSE) const;
Daniel Dunbar59e5a0e2009-02-03 20:00:13 +0000587
588public:
589 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const;
Daniel Dunbarb4094ea2009-02-10 20:44:09 +0000590
591 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
592 CodeGenFunction &CGF) const;
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000593};
594}
595
Daniel Dunbarc4503572009-01-31 00:06:58 +0000596X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum,
597 Class Field) const {
Daniel Dunbar8562ae72009-01-30 08:09:32 +0000598 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
599 // classified recursively so that always two fields are
600 // considered. The resulting class is calculated according to
601 // the classes of the fields in the eightbyte:
602 //
603 // (a) If both classes are equal, this is the resulting class.
604 //
605 // (b) If one of the classes is NO_CLASS, the resulting class is
606 // the other class.
607 //
608 // (c) If one of the classes is MEMORY, the result is the MEMORY
609 // class.
610 //
611 // (d) If one of the classes is INTEGER, the result is the
612 // INTEGER.
613 //
614 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
615 // MEMORY is used as class.
616 //
617 // (f) Otherwise class SSE is used.
Daniel Dunbar100f4022009-03-06 17:50:25 +0000618
619 // Accum should never be memory (we should have returned) or
620 // ComplexX87 (because this cannot be passed in a structure).
621 assert((Accum != Memory && Accum != ComplexX87) &&
Daniel Dunbarc4503572009-01-31 00:06:58 +0000622 "Invalid accumulated classification during merge.");
623 if (Accum == Field || Field == NoClass)
624 return Accum;
625 else if (Field == Memory)
626 return Memory;
627 else if (Accum == NoClass)
628 return Field;
629 else if (Accum == Integer || Field == Integer)
630 return Integer;
Daniel Dunbar20e95c52009-05-12 15:22:40 +0000631 else if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
632 Accum == X87 || Accum == X87Up)
Daniel Dunbarc4503572009-01-31 00:06:58 +0000633 return Memory;
Daniel Dunbar8562ae72009-01-30 08:09:32 +0000634 else
Daniel Dunbarc4503572009-01-31 00:06:58 +0000635 return SSE;
Daniel Dunbar8562ae72009-01-30 08:09:32 +0000636}
637
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000638void X86_64ABIInfo::classify(QualType Ty,
639 ASTContext &Context,
Daniel Dunbare620ecd2009-01-30 00:47:38 +0000640 uint64_t OffsetBase,
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000641 Class &Lo, Class &Hi) const {
Mike Stumpf5408fe2009-05-16 07:57:57 +0000642 // FIXME: This code can be simplified by introducing a simple value class for
643 // Class pairs with appropriate constructor methods for the various
644 // situations.
Daniel Dunbar9a82b522009-02-02 18:06:39 +0000645
Mike Stumpf5408fe2009-05-16 07:57:57 +0000646 // FIXME: Some of the split computations are wrong; unaligned vectors
647 // shouldn't be passed in registers for example, so there is no chance they
648 // can straddle an eightbyte. Verify & simplify.
Daniel Dunbare28099b2009-02-22 04:48:22 +0000649
Daniel Dunbarc4503572009-01-31 00:06:58 +0000650 Lo = Hi = NoClass;
651
652 Class &Current = OffsetBase < 64 ? Lo : Hi;
653 Current = Memory;
654
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000655 if (const BuiltinType *BT = Ty->getAsBuiltinType()) {
656 BuiltinType::Kind k = BT->getKind();
657
Daniel Dunbar11434922009-01-26 21:26:08 +0000658 if (k == BuiltinType::Void) {
Daniel Dunbarc4503572009-01-31 00:06:58 +0000659 Current = NoClass;
Chris Lattner2df9ced2009-04-30 02:43:43 +0000660 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
Chris Lattnerae69e002009-04-30 06:22:07 +0000661 Lo = Integer;
662 Hi = Integer;
Daniel Dunbar11434922009-01-26 21:26:08 +0000663 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
Daniel Dunbarc4503572009-01-31 00:06:58 +0000664 Current = Integer;
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000665 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Daniel Dunbarc4503572009-01-31 00:06:58 +0000666 Current = SSE;
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000667 } else if (k == BuiltinType::LongDouble) {
668 Lo = X87;
669 Hi = X87Up;
670 }
Daniel Dunbar7a6605d2009-01-27 02:01:34 +0000671 // FIXME: _Decimal32 and _Decimal64 are SSE.
672 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Anders Carlsson708762b2009-02-26 17:31:15 +0000673 } else if (const EnumType *ET = Ty->getAsEnumType()) {
674 // Classify the underlying integer type.
675 classify(ET->getDecl()->getIntegerType(), Context, OffsetBase, Lo, Hi);
Daniel Dunbar89588912009-02-26 20:52:22 +0000676 } else if (Ty->hasPointerRepresentation()) {
Daniel Dunbarc4503572009-01-31 00:06:58 +0000677 Current = Integer;
Daniel Dunbar7a6605d2009-01-27 02:01:34 +0000678 } else if (const VectorType *VT = Ty->getAsVectorType()) {
Daniel Dunbare620ecd2009-01-30 00:47:38 +0000679 uint64_t Size = Context.getTypeSize(VT);
Daniel Dunbare28099b2009-02-22 04:48:22 +0000680 if (Size == 32) {
681 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
682 // float> as integer.
683 Current = Integer;
684
685 // If this type crosses an eightbyte boundary, it should be
686 // split.
687 uint64_t EB_Real = (OffsetBase) / 64;
688 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
689 if (EB_Real != EB_Imag)
690 Hi = Lo;
691 } else if (Size == 64) {
Daniel Dunbar0af99292009-02-22 04:16:10 +0000692 // gcc passes <1 x double> in memory. :(
693 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
Daniel Dunbard4cd1b02009-01-30 19:38:39 +0000694 return;
Daniel Dunbar0af99292009-02-22 04:16:10 +0000695
696 // gcc passes <1 x long long> as INTEGER.
697 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong))
698 Current = Integer;
699 else
700 Current = SSE;
Daniel Dunbare33edf12009-01-30 18:40:10 +0000701
702 // If this type crosses an eightbyte boundary, it should be
703 // split.
Daniel Dunbarcdf920e2009-01-30 22:40:15 +0000704 if (OffsetBase && OffsetBase != 64)
Daniel Dunbare33edf12009-01-30 18:40:10 +0000705 Hi = Lo;
Daniel Dunbar7a6605d2009-01-27 02:01:34 +0000706 } else if (Size == 128) {
707 Lo = SSE;
708 Hi = SSEUp;
709 }
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000710 } else if (const ComplexType *CT = Ty->getAsComplexType()) {
Daniel Dunbar3327f6e2009-02-14 02:45:45 +0000711 QualType ET = Context.getCanonicalType(CT->getElementType());
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000712
Daniel Dunbare33edf12009-01-30 18:40:10 +0000713 uint64_t Size = Context.getTypeSize(Ty);
Daniel Dunbar0af99292009-02-22 04:16:10 +0000714 if (ET->isIntegralType()) {
Daniel Dunbareac48dc2009-01-29 07:22:20 +0000715 if (Size <= 64)
Daniel Dunbarc4503572009-01-31 00:06:58 +0000716 Current = Integer;
Daniel Dunbareac48dc2009-01-29 07:22:20 +0000717 else if (Size <= 128)
718 Lo = Hi = Integer;
719 } else if (ET == Context.FloatTy)
Daniel Dunbarc4503572009-01-31 00:06:58 +0000720 Current = SSE;
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000721 else if (ET == Context.DoubleTy)
722 Lo = Hi = SSE;
723 else if (ET == Context.LongDoubleTy)
Daniel Dunbarc4503572009-01-31 00:06:58 +0000724 Current = ComplexX87;
Daniel Dunbarf04d69b2009-01-29 09:42:07 +0000725
726 // If this complex type crosses an eightbyte boundary then it
727 // should be split.
Daniel Dunbarcdf920e2009-01-30 22:40:15 +0000728 uint64_t EB_Real = (OffsetBase) / 64;
729 uint64_t EB_Imag = (OffsetBase + Context.getTypeSize(ET)) / 64;
Daniel Dunbarf04d69b2009-01-29 09:42:07 +0000730 if (Hi == NoClass && EB_Real != EB_Imag)
731 Hi = Lo;
Daniel Dunbar8562ae72009-01-30 08:09:32 +0000732 } else if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
733 // Arrays are treated like structures.
734
735 uint64_t Size = Context.getTypeSize(Ty);
736
737 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
738 // than two eightbytes, ..., it has class MEMORY.
739 if (Size > 128)
740 return;
741
742 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
743 // fields, it has class MEMORY.
744 //
745 // Only need to check alignment of array base.
Daniel Dunbarc4503572009-01-31 00:06:58 +0000746 if (OffsetBase % Context.getTypeAlign(AT->getElementType()))
Daniel Dunbar8562ae72009-01-30 08:09:32 +0000747 return;
Daniel Dunbar8562ae72009-01-30 08:09:32 +0000748
749 // Otherwise implement simplified merge. We could be smarter about
750 // this, but it isn't worth it and would be harder to verify.
Daniel Dunbarc4503572009-01-31 00:06:58 +0000751 Current = NoClass;
Daniel Dunbar8562ae72009-01-30 08:09:32 +0000752 uint64_t EltSize = Context.getTypeSize(AT->getElementType());
753 uint64_t ArraySize = AT->getSize().getZExtValue();
754 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
755 Class FieldLo, FieldHi;
756 classify(AT->getElementType(), Context, Offset, FieldLo, FieldHi);
Daniel Dunbarc4503572009-01-31 00:06:58 +0000757 Lo = merge(Lo, FieldLo);
758 Hi = merge(Hi, FieldHi);
759 if (Lo == Memory || Hi == Memory)
760 break;
Daniel Dunbar8562ae72009-01-30 08:09:32 +0000761 }
Daniel Dunbarc4503572009-01-31 00:06:58 +0000762
763 // Do post merger cleanup (see below). Only case we worry about is Memory.
764 if (Hi == Memory)
765 Lo = Memory;
766 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Daniel Dunbar99037e52009-01-29 08:13:58 +0000767 } else if (const RecordType *RT = Ty->getAsRecordType()) {
Daniel Dunbare620ecd2009-01-30 00:47:38 +0000768 uint64_t Size = Context.getTypeSize(Ty);
Daniel Dunbar99037e52009-01-29 08:13:58 +0000769
770 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
771 // than two eightbytes, ..., it has class MEMORY.
772 if (Size > 128)
773 return;
774
775 const RecordDecl *RD = RT->getDecl();
776
777 // Assume variable sized types are passed in memory.
778 if (RD->hasFlexibleArrayMember())
779 return;
780
781 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
782
783 // Reset Lo class, this will be recomputed.
Daniel Dunbarc4503572009-01-31 00:06:58 +0000784 Current = NoClass;
Daniel Dunbar99037e52009-01-29 08:13:58 +0000785 unsigned idx = 0;
Douglas Gregor6ab35242009-04-09 21:40:53 +0000786 for (RecordDecl::field_iterator i = RD->field_begin(Context),
787 e = RD->field_end(Context); i != e; ++i, ++idx) {
Daniel Dunbar8562ae72009-01-30 08:09:32 +0000788 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Daniel Dunbardd81d442009-02-17 02:45:44 +0000789 bool BitField = i->isBitField();
Daniel Dunbar99037e52009-01-29 08:13:58 +0000790
Daniel Dunbar8562ae72009-01-30 08:09:32 +0000791 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
792 // fields, it has class MEMORY.
Daniel Dunbardd81d442009-02-17 02:45:44 +0000793 //
Daniel Dunbar8e034442009-04-27 18:31:32 +0000794 // Note, skip this test for bit-fields, see below.
Daniel Dunbardd81d442009-02-17 02:45:44 +0000795 if (!BitField && Offset % Context.getTypeAlign(i->getType())) {
Daniel Dunbar99037e52009-01-29 08:13:58 +0000796 Lo = Memory;
797 return;
798 }
799
Daniel Dunbar99037e52009-01-29 08:13:58 +0000800 // Classify this field.
Daniel Dunbarc4503572009-01-31 00:06:58 +0000801 //
802 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
803 // exceeds a single eightbyte, each is classified
804 // separately. Each eightbyte gets initialized to class
805 // NO_CLASS.
Daniel Dunbar99037e52009-01-29 08:13:58 +0000806 Class FieldLo, FieldHi;
Daniel Dunbardd81d442009-02-17 02:45:44 +0000807
Daniel Dunbar8e034442009-04-27 18:31:32 +0000808 // Bit-fields require special handling, they do not force the
Daniel Dunbardd81d442009-02-17 02:45:44 +0000809 // structure to be passed in memory even if unaligned, and
810 // therefore they can straddle an eightbyte.
811 if (BitField) {
Daniel Dunbar8236bf12009-05-08 22:26:44 +0000812 // Ignore padding bit-fields.
813 if (i->isUnnamedBitfield())
814 continue;
815
Daniel Dunbardd81d442009-02-17 02:45:44 +0000816 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Eli Friedman9a901bb2009-04-26 19:19:15 +0000817 uint64_t Size = i->getBitWidth()->EvaluateAsInt(Context).getZExtValue();
Daniel Dunbardd81d442009-02-17 02:45:44 +0000818
819 uint64_t EB_Lo = Offset / 64;
820 uint64_t EB_Hi = (Offset + Size - 1) / 64;
821 FieldLo = FieldHi = NoClass;
822 if (EB_Lo) {
823 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
824 FieldLo = NoClass;
825 FieldHi = Integer;
826 } else {
827 FieldLo = Integer;
828 FieldHi = EB_Hi ? Integer : NoClass;
829 }
830 } else
831 classify(i->getType(), Context, Offset, FieldLo, FieldHi);
Daniel Dunbarc4503572009-01-31 00:06:58 +0000832 Lo = merge(Lo, FieldLo);
833 Hi = merge(Hi, FieldHi);
834 if (Lo == Memory || Hi == Memory)
835 break;
Daniel Dunbar99037e52009-01-29 08:13:58 +0000836 }
837
838 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
839 //
840 // (a) If one of the classes is MEMORY, the whole argument is
841 // passed in memory.
842 //
843 // (b) If SSEUP is not preceeded by SSE, it is converted to SSE.
844
845 // The first of these conditions is guaranteed by how we implement
Daniel Dunbarc4503572009-01-31 00:06:58 +0000846 // the merge (just bail).
847 //
848 // The second condition occurs in the case of unions; for example
849 // union { _Complex double; unsigned; }.
850 if (Hi == Memory)
851 Lo = Memory;
Daniel Dunbar99037e52009-01-29 08:13:58 +0000852 if (Hi == SSEUp && Lo != SSE)
Daniel Dunbarc4503572009-01-31 00:06:58 +0000853 Hi = SSE;
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000854 }
855}
856
Daniel Dunbar644f4c32009-02-14 02:09:24 +0000857ABIArgInfo X86_64ABIInfo::getCoerceResult(QualType Ty,
858 const llvm::Type *CoerceTo,
859 ASTContext &Context) const {
860 if (CoerceTo == llvm::Type::Int64Ty) {
861 // Integer and pointer types will end up in a general purpose
862 // register.
Daniel Dunbar0af99292009-02-22 04:16:10 +0000863 if (Ty->isIntegralType() || Ty->isPointerType())
Daniel Dunbar644f4c32009-02-14 02:09:24 +0000864 return ABIArgInfo::getDirect();
Daniel Dunbar0af99292009-02-22 04:16:10 +0000865
Daniel Dunbar644f4c32009-02-14 02:09:24 +0000866 } else if (CoerceTo == llvm::Type::DoubleTy) {
Mike Stumpf5408fe2009-05-16 07:57:57 +0000867 // FIXME: It would probably be better to make CGFunctionInfo only map using
868 // canonical types than to canonize here.
Daniel Dunbar3327f6e2009-02-14 02:45:45 +0000869 QualType CTy = Context.getCanonicalType(Ty);
870
Daniel Dunbar644f4c32009-02-14 02:09:24 +0000871 // Float and double end up in a single SSE reg.
Daniel Dunbar3327f6e2009-02-14 02:45:45 +0000872 if (CTy == Context.FloatTy || CTy == Context.DoubleTy)
Daniel Dunbar644f4c32009-02-14 02:09:24 +0000873 return ABIArgInfo::getDirect();
Daniel Dunbar0af99292009-02-22 04:16:10 +0000874
Daniel Dunbar644f4c32009-02-14 02:09:24 +0000875 }
876
877 return ABIArgInfo::getCoerce(CoerceTo);
878}
Daniel Dunbarc4503572009-01-31 00:06:58 +0000879
Daniel Dunbar86e13ee2009-05-26 16:37:37 +0000880ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
881 ASTContext &Context) const {
882 // If this is a scalar LLVM value then assume LLVM will pass it in the right
883 // place naturally.
884 if (!CodeGenFunction::hasAggregateLLVMType(Ty))
885 return ABIArgInfo::getDirect();
886
887 // FIXME: Set alignment correctly.
888 return ABIArgInfo::getIndirect(0);
889}
890
Daniel Dunbard4edfe42009-01-15 18:18:40 +0000891ABIArgInfo X86_64ABIInfo::classifyReturnType(QualType RetTy,
892 ASTContext &Context) const {
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000893 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
894 // classification algorithm.
895 X86_64ABIInfo::Class Lo, Hi;
Daniel Dunbarf04d69b2009-01-29 09:42:07 +0000896 classify(RetTy, Context, 0, Lo, Hi);
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000897
Daniel Dunbarc4503572009-01-31 00:06:58 +0000898 // Check some invariants.
899 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
900 assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification.");
901 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
902
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000903 const llvm::Type *ResType = 0;
904 switch (Lo) {
905 case NoClass:
Daniel Dunbar11434922009-01-26 21:26:08 +0000906 return ABIArgInfo::getIgnore();
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000907
908 case SSEUp:
909 case X87Up:
910 assert(0 && "Invalid classification for lo word.");
911
Daniel Dunbarc4503572009-01-31 00:06:58 +0000912 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
Daniel Dunbar11e383a2009-02-05 08:00:50 +0000913 // hidden argument.
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000914 case Memory:
Daniel Dunbar86e13ee2009-05-26 16:37:37 +0000915 return getIndirectResult(RetTy, Context);
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000916
917 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
918 // available register of the sequence %rax, %rdx is used.
919 case Integer:
920 ResType = llvm::Type::Int64Ty; break;
921
922 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
923 // available SSE register of the sequence %xmm0, %xmm1 is used.
924 case SSE:
925 ResType = llvm::Type::DoubleTy; break;
926
927 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
928 // returned on the X87 stack in %st0 as 80-bit x87 number.
929 case X87:
930 ResType = llvm::Type::X86_FP80Ty; break;
931
Daniel Dunbarc4503572009-01-31 00:06:58 +0000932 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
933 // part of the value is returned in %st0 and the imaginary part in
934 // %st1.
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000935 case ComplexX87:
Daniel Dunbar6e53e9b2009-02-17 07:55:55 +0000936 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Daniel Dunbar3e030b42009-02-18 03:44:19 +0000937 ResType = llvm::StructType::get(llvm::Type::X86_FP80Ty,
938 llvm::Type::X86_FP80Ty,
939 NULL);
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000940 break;
941 }
942
943 switch (Hi) {
Daniel Dunbar6e53e9b2009-02-17 07:55:55 +0000944 // Memory was handled previously and X87 should
945 // never occur as a hi class.
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000946 case Memory:
947 case X87:
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000948 assert(0 && "Invalid classification for hi word.");
949
Daniel Dunbar6e53e9b2009-02-17 07:55:55 +0000950 case ComplexX87: // Previously handled.
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000951 case NoClass: break;
Daniel Dunbar6e53e9b2009-02-17 07:55:55 +0000952
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000953 case Integer:
Daniel Dunbarb0e14f22009-01-29 07:36:07 +0000954 ResType = llvm::StructType::get(ResType, llvm::Type::Int64Ty, NULL);
955 break;
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000956 case SSE:
Daniel Dunbarb0e14f22009-01-29 07:36:07 +0000957 ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL);
958 break;
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000959
960 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
961 // is passed in the upper half of the last used SSE register.
962 //
963 // SSEUP should always be preceeded by SSE, just widen.
964 case SSEUp:
965 assert(Lo == SSE && "Unexpected SSEUp classification.");
966 ResType = llvm::VectorType::get(llvm::Type::DoubleTy, 2);
967 break;
968
969 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
Daniel Dunbarb0e14f22009-01-29 07:36:07 +0000970 // returned together with the previous X87 value in %st0.
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000971 case X87Up:
Daniel Dunbar100f4022009-03-06 17:50:25 +0000972 // If X87Up is preceeded by X87, we don't need to do
973 // anything. However, in some cases with unions it may not be
974 // preceeded by X87. In such situations we follow gcc and pass the
975 // extra bits in an SSE reg.
976 if (Lo != X87)
977 ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL);
Daniel Dunbar6f3e7fa2009-01-24 08:32:22 +0000978 break;
979 }
980
Daniel Dunbar644f4c32009-02-14 02:09:24 +0000981 return getCoerceResult(RetTy, ResType, Context);
Daniel Dunbard4edfe42009-01-15 18:18:40 +0000982}
983
Daniel Dunbar59e5a0e2009-02-03 20:00:13 +0000984ABIArgInfo X86_64ABIInfo::classifyArgumentType(QualType Ty, ASTContext &Context,
Daniel Dunbar3b4e9cd2009-02-10 17:06:09 +0000985 unsigned &neededInt,
986 unsigned &neededSSE) const {
Daniel Dunbar59e5a0e2009-02-03 20:00:13 +0000987 X86_64ABIInfo::Class Lo, Hi;
988 classify(Ty, Context, 0, Lo, Hi);
989
990 // Check some invariants.
991 // FIXME: Enforce these by construction.
992 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
993 assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification.");
994 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
995
Daniel Dunbar3b4e9cd2009-02-10 17:06:09 +0000996 neededInt = 0;
997 neededSSE = 0;
Daniel Dunbar59e5a0e2009-02-03 20:00:13 +0000998 const llvm::Type *ResType = 0;
999 switch (Lo) {
1000 case NoClass:
1001 return ABIArgInfo::getIgnore();
1002
1003 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
1004 // on the stack.
1005 case Memory:
1006
1007 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
1008 // COMPLEX_X87, it is passed in memory.
1009 case X87:
1010 case ComplexX87:
Daniel Dunbar86e13ee2009-05-26 16:37:37 +00001011 return getIndirectResult(Ty, Context);
Daniel Dunbar59e5a0e2009-02-03 20:00:13 +00001012
1013 case SSEUp:
1014 case X87Up:
1015 assert(0 && "Invalid classification for lo word.");
1016
1017 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
1018 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
1019 // and %r9 is used.
1020 case Integer:
1021 ++neededInt;
1022 ResType = llvm::Type::Int64Ty;
1023 break;
1024
1025 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
1026 // available SSE register is used, the registers are taken in the
1027 // order from %xmm0 to %xmm7.
1028 case SSE:
1029 ++neededSSE;
1030 ResType = llvm::Type::DoubleTy;
1031 break;
Daniel Dunbar0bcc5212009-02-03 06:30:17 +00001032 }
Daniel Dunbar59e5a0e2009-02-03 20:00:13 +00001033
1034 switch (Hi) {
1035 // Memory was handled previously, ComplexX87 and X87 should
1036 // never occur as hi classes, and X87Up must be preceed by X87,
1037 // which is passed in memory.
1038 case Memory:
1039 case X87:
Daniel Dunbar59e5a0e2009-02-03 20:00:13 +00001040 case ComplexX87:
1041 assert(0 && "Invalid classification for hi word.");
Daniel Dunbar100f4022009-03-06 17:50:25 +00001042 break;
Daniel Dunbar59e5a0e2009-02-03 20:00:13 +00001043
1044 case NoClass: break;
1045 case Integer:
1046 ResType = llvm::StructType::get(ResType, llvm::Type::Int64Ty, NULL);
1047 ++neededInt;
1048 break;
Daniel Dunbar100f4022009-03-06 17:50:25 +00001049
1050 // X87Up generally doesn't occur here (long double is passed in
1051 // memory), except in situations involving unions.
1052 case X87Up:
1053 case SSE:
Daniel Dunbar59e5a0e2009-02-03 20:00:13 +00001054 ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL);
1055 ++neededSSE;
1056 break;
1057
1058 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
1059 // eightbyte is passed in the upper half of the last used SSE
1060 // register.
1061 case SSEUp:
1062 assert(Lo == SSE && "Unexpected SSEUp classification.");
1063 ResType = llvm::VectorType::get(llvm::Type::DoubleTy, 2);
1064 break;
1065 }
1066
Daniel Dunbar644f4c32009-02-14 02:09:24 +00001067 return getCoerceResult(Ty, ResType, Context);
Daniel Dunbar59e5a0e2009-02-03 20:00:13 +00001068}
1069
1070void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
1071 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
1072
1073 // Keep track of the number of assigned registers.
1074 unsigned freeIntRegs = 6, freeSSERegs = 8;
Daniel Dunbar3a5f5c52009-05-22 17:33:44 +00001075
1076 // If the return value is indirect, then the hidden argument is consuming one
1077 // integer register.
1078 if (FI.getReturnInfo().isIndirect())
1079 --freeIntRegs;
Daniel Dunbar59e5a0e2009-02-03 20:00:13 +00001080
1081 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
1082 // get assigned (in left-to-right order) for passing as follows...
1083 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Daniel Dunbar3b4e9cd2009-02-10 17:06:09 +00001084 it != ie; ++it) {
1085 unsigned neededInt, neededSSE;
1086 it->info = classifyArgumentType(it->type, Context, neededInt, neededSSE);
1087
1088 // AMD64-ABI 3.2.3p3: If there are no registers available for any
1089 // eightbyte of an argument, the whole argument is passed on the
1090 // stack. If registers have already been assigned for some
1091 // eightbytes of such an argument, the assignments get reverted.
1092 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
1093 freeIntRegs -= neededInt;
1094 freeSSERegs -= neededSSE;
1095 } else {
Daniel Dunbar86e13ee2009-05-26 16:37:37 +00001096 it->info = getIndirectResult(it->type, Context);
Daniel Dunbar3b4e9cd2009-02-10 17:06:09 +00001097 }
1098 }
Daniel Dunbard4edfe42009-01-15 18:18:40 +00001099}
1100
Daniel Dunbarbe9eb092009-02-12 09:04:14 +00001101static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
1102 QualType Ty,
1103 CodeGenFunction &CGF) {
1104 llvm::Value *overflow_arg_area_p =
1105 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
1106 llvm::Value *overflow_arg_area =
1107 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
1108
1109 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
1110 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Daniel Dunbarc5bcee42009-02-16 23:38:56 +00001111 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
Daniel Dunbarbe9eb092009-02-12 09:04:14 +00001112 if (Align > 8) {
Daniel Dunbarc5bcee42009-02-16 23:38:56 +00001113 // Note that we follow the ABI & gcc here, even though the type
1114 // could in theory have an alignment greater than 16. This case
1115 // shouldn't ever matter in practice.
Daniel Dunbarbe9eb092009-02-12 09:04:14 +00001116
Daniel Dunbarc5bcee42009-02-16 23:38:56 +00001117 // overflow_arg_area = (overflow_arg_area + 15) & ~15;
1118 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty, 15);
1119 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
1120 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
1121 llvm::Type::Int64Ty);
1122 llvm::Value *Mask = llvm::ConstantInt::get(llvm::Type::Int64Ty, ~15LL);
1123 overflow_arg_area =
1124 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1125 overflow_arg_area->getType(),
1126 "overflow_arg_area.align");
Daniel Dunbarbe9eb092009-02-12 09:04:14 +00001127 }
1128
1129 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
1130 const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1131 llvm::Value *Res =
1132 CGF.Builder.CreateBitCast(overflow_arg_area,
1133 llvm::PointerType::getUnqual(LTy));
1134
1135 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
1136 // l->overflow_arg_area + sizeof(type).
1137 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
1138 // an 8 byte boundary.
1139
1140 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
1141 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty,
1142 (SizeInBytes + 7) & ~7);
1143 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
1144 "overflow_arg_area.next");
1145 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
1146
1147 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
1148 return Res;
1149}
1150
Daniel Dunbarb4094ea2009-02-10 20:44:09 +00001151llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1152 CodeGenFunction &CGF) const {
Daniel Dunbarbe9eb092009-02-12 09:04:14 +00001153 // Assume that va_list type is correct; should be pointer to LLVM type:
1154 // struct {
1155 // i32 gp_offset;
1156 // i32 fp_offset;
1157 // i8* overflow_arg_area;
1158 // i8* reg_save_area;
1159 // };
1160 unsigned neededInt, neededSSE;
1161 ABIArgInfo AI = classifyArgumentType(Ty, CGF.getContext(),
1162 neededInt, neededSSE);
1163
1164 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
1165 // in the registers. If not go to step 7.
1166 if (!neededInt && !neededSSE)
1167 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1168
1169 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
1170 // general purpose registers needed to pass type and num_fp to hold
1171 // the number of floating point registers needed.
1172
1173 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
1174 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
1175 // l->fp_offset > 304 - num_fp * 16 go to step 7.
1176 //
1177 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
1178 // register save space).
1179
1180 llvm::Value *InRegs = 0;
1181 llvm::Value *gp_offset_p = 0, *gp_offset = 0;
1182 llvm::Value *fp_offset_p = 0, *fp_offset = 0;
1183 if (neededInt) {
1184 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
1185 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
1186 InRegs =
1187 CGF.Builder.CreateICmpULE(gp_offset,
1188 llvm::ConstantInt::get(llvm::Type::Int32Ty,
1189 48 - neededInt * 8),
1190 "fits_in_gp");
1191 }
1192
1193 if (neededSSE) {
1194 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
1195 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
1196 llvm::Value *FitsInFP =
1197 CGF.Builder.CreateICmpULE(fp_offset,
1198 llvm::ConstantInt::get(llvm::Type::Int32Ty,
Daniel Dunbar90dafa12009-02-18 22:19:44 +00001199 176 - neededSSE * 16),
Daniel Dunbarbe9eb092009-02-12 09:04:14 +00001200 "fits_in_fp");
Daniel Dunbarf2313462009-02-18 22:05:01 +00001201 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
Daniel Dunbarbe9eb092009-02-12 09:04:14 +00001202 }
1203
1204 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
1205 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
1206 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
1207 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
1208
1209 // Emit code to load the value if it was passed in registers.
1210
1211 CGF.EmitBlock(InRegBlock);
1212
1213 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
1214 // an offset of l->gp_offset and/or l->fp_offset. This may require
1215 // copying to a temporary location in case the parameter is passed
1216 // in different register classes or requires an alignment greater
1217 // than 8 for general purpose registers and 16 for XMM registers.
Daniel Dunbar3e030b42009-02-18 03:44:19 +00001218 //
Mike Stumpf5408fe2009-05-16 07:57:57 +00001219 // FIXME: This really results in shameful code when we end up needing to
1220 // collect arguments from different places; often what should result in a
1221 // simple assembling of a structure from scattered addresses has many more
1222 // loads than necessary. Can we clean this up?
Daniel Dunbarbe9eb092009-02-12 09:04:14 +00001223 const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1224 llvm::Value *RegAddr =
1225 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
1226 "reg_save_area");
1227 if (neededInt && neededSSE) {
Daniel Dunbar55e5d892009-02-13 17:46:31 +00001228 // FIXME: Cleanup.
1229 assert(AI.isCoerce() && "Unexpected ABI info for mixed regs");
1230 const llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
1231 llvm::Value *Tmp = CGF.CreateTempAlloca(ST);
1232 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
1233 const llvm::Type *TyLo = ST->getElementType(0);
1234 const llvm::Type *TyHi = ST->getElementType(1);
1235 assert((TyLo->isFloatingPoint() ^ TyHi->isFloatingPoint()) &&
1236 "Unexpected ABI info for mixed regs");
1237 const llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
1238 const llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
1239 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1240 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1241 llvm::Value *RegLoAddr = TyLo->isFloatingPoint() ? FPAddr : GPAddr;
1242 llvm::Value *RegHiAddr = TyLo->isFloatingPoint() ? GPAddr : FPAddr;
1243 llvm::Value *V =
1244 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
1245 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1246 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
1247 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1248
1249 RegAddr = CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(LTy));
Daniel Dunbarbe9eb092009-02-12 09:04:14 +00001250 } else if (neededInt) {
1251 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1252 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1253 llvm::PointerType::getUnqual(LTy));
1254 } else {
Daniel Dunbar3e030b42009-02-18 03:44:19 +00001255 if (neededSSE == 1) {
1256 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1257 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1258 llvm::PointerType::getUnqual(LTy));
1259 } else {
1260 assert(neededSSE == 2 && "Invalid number of needed registers!");
1261 // SSE registers are spaced 16 bytes apart in the register save
1262 // area, we need to collect the two eightbytes together.
1263 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1264 llvm::Value *RegAddrHi =
1265 CGF.Builder.CreateGEP(RegAddrLo,
1266 llvm::ConstantInt::get(llvm::Type::Int32Ty, 16));
1267 const llvm::Type *DblPtrTy =
1268 llvm::PointerType::getUnqual(llvm::Type::DoubleTy);
1269 const llvm::StructType *ST = llvm::StructType::get(llvm::Type::DoubleTy,
1270 llvm::Type::DoubleTy,
1271 NULL);
1272 llvm::Value *V, *Tmp = CGF.CreateTempAlloca(ST);
1273 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
1274 DblPtrTy));
1275 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1276 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
1277 DblPtrTy));
1278 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1279 RegAddr = CGF.Builder.CreateBitCast(Tmp,
1280 llvm::PointerType::getUnqual(LTy));
1281 }
Daniel Dunbarbe9eb092009-02-12 09:04:14 +00001282 }
1283
1284 // AMD64-ABI 3.5.7p5: Step 5. Set:
1285 // l->gp_offset = l->gp_offset + num_gp * 8
1286 // l->fp_offset = l->fp_offset + num_fp * 16.
1287 if (neededInt) {
1288 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty,
1289 neededInt * 8);
1290 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
1291 gp_offset_p);
1292 }
1293 if (neededSSE) {
1294 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty,
1295 neededSSE * 16);
1296 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
1297 fp_offset_p);
1298 }
1299 CGF.EmitBranch(ContBlock);
1300
1301 // Emit code to load the value if it was passed in memory.
1302
1303 CGF.EmitBlock(InMemBlock);
1304 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1305
1306 // Return the appropriate result.
1307
1308 CGF.EmitBlock(ContBlock);
1309 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(),
1310 "vaarg.addr");
1311 ResAddr->reserveOperandSpace(2);
1312 ResAddr->addIncoming(RegAddr, InRegBlock);
1313 ResAddr->addIncoming(MemAddr, InMemBlock);
1314
1315 return ResAddr;
Daniel Dunbarb4094ea2009-02-10 20:44:09 +00001316}
1317
Sanjiv Gupta70aa5f92009-04-21 06:01:16 +00001318// ABI Info for PIC16
1319class PIC16ABIInfo : public ABIInfo {
1320 ABIArgInfo classifyReturnType(QualType RetTy,
1321 ASTContext &Context) const;
1322
1323 ABIArgInfo classifyArgumentType(QualType RetTy,
1324 ASTContext &Context) const;
1325
1326 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
1327 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
1328 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1329 it != ie; ++it)
1330 it->info = classifyArgumentType(it->type, Context);
1331 }
1332
1333 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1334 CodeGenFunction &CGF) const;
1335
1336};
1337
1338ABIArgInfo PIC16ABIInfo::classifyReturnType(QualType RetTy,
1339 ASTContext &Context) const {
1340 if (RetTy->isVoidType()) {
1341 return ABIArgInfo::getIgnore();
1342 } else {
1343 return ABIArgInfo::getDirect();
1344 }
1345}
1346
1347ABIArgInfo PIC16ABIInfo::classifyArgumentType(QualType Ty,
1348 ASTContext &Context) const {
1349 return ABIArgInfo::getDirect();
1350}
1351
1352llvm::Value *PIC16ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1353 CodeGenFunction &CGF) const {
1354 return 0;
1355}
1356
Eli Friedmana027ea92009-03-29 00:15:25 +00001357class ARMABIInfo : public ABIInfo {
1358 ABIArgInfo classifyReturnType(QualType RetTy,
1359 ASTContext &Context) const;
1360
1361 ABIArgInfo classifyArgumentType(QualType RetTy,
1362 ASTContext &Context) const;
1363
1364 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const;
1365
1366 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1367 CodeGenFunction &CGF) const;
1368};
1369
1370void ARMABIInfo::computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
1371 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
1372 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1373 it != ie; ++it) {
1374 it->info = classifyArgumentType(it->type, Context);
1375 }
1376}
1377
1378ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
1379 ASTContext &Context) const {
1380 if (!CodeGenFunction::hasAggregateLLVMType(Ty)) {
1381 return ABIArgInfo::getDirect();
1382 }
Mike Stumpf5408fe2009-05-16 07:57:57 +00001383 // FIXME: This is kind of nasty... but there isn't much choice because the ARM
1384 // backend doesn't support byval.
Eli Friedmana027ea92009-03-29 00:15:25 +00001385 // FIXME: This doesn't handle alignment > 64 bits.
1386 const llvm::Type* ElemTy;
1387 unsigned SizeRegs;
1388 if (Context.getTypeAlign(Ty) > 32) {
1389 ElemTy = llvm::Type::Int64Ty;
1390 SizeRegs = (Context.getTypeSize(Ty) + 63) / 64;
1391 } else {
1392 ElemTy = llvm::Type::Int32Ty;
1393 SizeRegs = (Context.getTypeSize(Ty) + 31) / 32;
1394 }
1395 std::vector<const llvm::Type*> LLVMFields;
1396 LLVMFields.push_back(llvm::ArrayType::get(ElemTy, SizeRegs));
1397 const llvm::Type* STy = llvm::StructType::get(LLVMFields, true);
1398 return ABIArgInfo::getCoerce(STy);
1399}
1400
1401ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
1402 ASTContext &Context) const {
1403 if (RetTy->isVoidType()) {
1404 return ABIArgInfo::getIgnore();
1405 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1406 // Aggregates <= 4 bytes are returned in r0; other aggregates
1407 // are returned indirectly.
1408 uint64_t Size = Context.getTypeSize(RetTy);
1409 if (Size <= 32)
1410 return ABIArgInfo::getCoerce(llvm::Type::Int32Ty);
1411 return ABIArgInfo::getIndirect(0);
1412 } else {
1413 return ABIArgInfo::getDirect();
1414 }
1415}
1416
1417llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1418 CodeGenFunction &CGF) const {
1419 // FIXME: Need to handle alignment
1420 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1421 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
1422
1423 CGBuilderTy &Builder = CGF.Builder;
1424 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1425 "ap");
1426 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
1427 llvm::Type *PTy =
1428 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
1429 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1430
1431 uint64_t Offset =
1432 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
1433 llvm::Value *NextAddr =
1434 Builder.CreateGEP(Addr,
1435 llvm::ConstantInt::get(llvm::Type::Int32Ty, Offset),
1436 "ap.next");
1437 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1438
1439 return AddrTyped;
1440}
1441
Daniel Dunbar6b1da0e2008-10-13 17:02:26 +00001442ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy,
Daniel Dunbarb4094ea2009-02-10 20:44:09 +00001443 ASTContext &Context) const {
Daniel Dunbar0bcc5212009-02-03 06:30:17 +00001444 if (RetTy->isVoidType()) {
1445 return ABIArgInfo::getIgnore();
1446 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
Daniel Dunbar11e383a2009-02-05 08:00:50 +00001447 return ABIArgInfo::getIndirect(0);
Daniel Dunbar0bcc5212009-02-03 06:30:17 +00001448 } else {
1449 return ABIArgInfo::getDirect();
1450 }
Daniel Dunbar6b1da0e2008-10-13 17:02:26 +00001451}
1452
1453ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty,
Daniel Dunbarb4094ea2009-02-10 20:44:09 +00001454 ASTContext &Context) const {
Daniel Dunbar0bcc5212009-02-03 06:30:17 +00001455 if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
Daniel Dunbar11e383a2009-02-05 08:00:50 +00001456 return ABIArgInfo::getIndirect(0);
Daniel Dunbar0bcc5212009-02-03 06:30:17 +00001457 } else {
1458 return ABIArgInfo::getDirect();
1459 }
Daniel Dunbar6b1da0e2008-10-13 17:02:26 +00001460}
1461
Daniel Dunbarb4094ea2009-02-10 20:44:09 +00001462llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1463 CodeGenFunction &CGF) const {
1464 return 0;
1465}
1466
Daniel Dunbar6b1da0e2008-10-13 17:02:26 +00001467const ABIInfo &CodeGenTypes::getABIInfo() const {
1468 if (TheABIInfo)
1469 return *TheABIInfo;
1470
1471 // For now we just cache this in the CodeGenTypes and don't bother
1472 // to free it.
1473 const char *TargetPrefix = getContext().Target.getTargetPrefix();
1474 if (strcmp(TargetPrefix, "x86") == 0) {
Eli Friedman9fd58e82009-03-23 23:26:24 +00001475 bool IsDarwin = strstr(getContext().Target.getTargetTriple(), "darwin");
Daniel Dunbard4edfe42009-01-15 18:18:40 +00001476 switch (getContext().Target.getPointerWidth(0)) {
1477 case 32:
Douglas Gregor6ab35242009-04-09 21:40:53 +00001478 return *(TheABIInfo = new X86_32ABIInfo(Context, IsDarwin));
Daniel Dunbard4edfe42009-01-15 18:18:40 +00001479 case 64:
Daniel Dunbar11a76ed2009-01-30 18:47:53 +00001480 return *(TheABIInfo = new X86_64ABIInfo());
Daniel Dunbard4edfe42009-01-15 18:18:40 +00001481 }
Eli Friedmana027ea92009-03-29 00:15:25 +00001482 } else if (strcmp(TargetPrefix, "arm") == 0) {
1483 // FIXME: Support for OABI?
1484 return *(TheABIInfo = new ARMABIInfo());
Sanjiv Gupta70aa5f92009-04-21 06:01:16 +00001485 } else if (strcmp(TargetPrefix, "pic16") == 0) {
1486 return *(TheABIInfo = new PIC16ABIInfo());
Daniel Dunbar6b1da0e2008-10-13 17:02:26 +00001487 }
1488
1489 return *(TheABIInfo = new DefaultABIInfo);
1490}
1491
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001492/***/
1493
Daniel Dunbar88c2fa92009-02-03 05:31:23 +00001494CGFunctionInfo::CGFunctionInfo(QualType ResTy,
1495 const llvm::SmallVector<QualType, 16> &ArgTys) {
1496 NumArgs = ArgTys.size();
1497 Args = new ArgInfo[1 + NumArgs];
1498 Args[0].type = ResTy;
1499 for (unsigned i = 0; i < NumArgs; ++i)
1500 Args[1 + i].type = ArgTys[i];
1501}
1502
1503/***/
1504
Daniel Dunbar56273772008-09-17 00:51:38 +00001505void CodeGenTypes::GetExpandedTypes(QualType Ty,
1506 std::vector<const llvm::Type*> &ArgTys) {
1507 const RecordType *RT = Ty->getAsStructureType();
1508 assert(RT && "Can only expand structure types.");
1509 const RecordDecl *RD = RT->getDecl();
1510 assert(!RD->hasFlexibleArrayMember() &&
1511 "Cannot expand structure with flexible array.");
1512
Douglas Gregor6ab35242009-04-09 21:40:53 +00001513 for (RecordDecl::field_iterator i = RD->field_begin(Context),
1514 e = RD->field_end(Context); i != e; ++i) {
Daniel Dunbar56273772008-09-17 00:51:38 +00001515 const FieldDecl *FD = *i;
1516 assert(!FD->isBitField() &&
1517 "Cannot expand structure with bit-field members.");
1518
1519 QualType FT = FD->getType();
1520 if (CodeGenFunction::hasAggregateLLVMType(FT)) {
1521 GetExpandedTypes(FT, ArgTys);
1522 } else {
1523 ArgTys.push_back(ConvertType(FT));
1524 }
1525 }
1526}
1527
1528llvm::Function::arg_iterator
1529CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
1530 llvm::Function::arg_iterator AI) {
1531 const RecordType *RT = Ty->getAsStructureType();
1532 assert(RT && "Can only expand structure types.");
1533
1534 RecordDecl *RD = RT->getDecl();
1535 assert(LV.isSimple() &&
1536 "Unexpected non-simple lvalue during struct expansion.");
1537 llvm::Value *Addr = LV.getAddress();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001538 for (RecordDecl::field_iterator i = RD->field_begin(getContext()),
1539 e = RD->field_end(getContext()); i != e; ++i) {
Daniel Dunbar56273772008-09-17 00:51:38 +00001540 FieldDecl *FD = *i;
1541 QualType FT = FD->getType();
1542
1543 // FIXME: What are the right qualifiers here?
1544 LValue LV = EmitLValueForField(Addr, FD, false, 0);
1545 if (CodeGenFunction::hasAggregateLLVMType(FT)) {
1546 AI = ExpandTypeFromArgs(FT, LV, AI);
1547 } else {
1548 EmitStoreThroughLValue(RValue::get(AI), LV, FT);
1549 ++AI;
1550 }
1551 }
1552
1553 return AI;
1554}
1555
1556void
1557CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
1558 llvm::SmallVector<llvm::Value*, 16> &Args) {
1559 const RecordType *RT = Ty->getAsStructureType();
1560 assert(RT && "Can only expand structure types.");
1561
1562 RecordDecl *RD = RT->getDecl();
1563 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
1564 llvm::Value *Addr = RV.getAggregateAddr();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001565 for (RecordDecl::field_iterator i = RD->field_begin(getContext()),
1566 e = RD->field_end(getContext()); i != e; ++i) {
Daniel Dunbar56273772008-09-17 00:51:38 +00001567 FieldDecl *FD = *i;
1568 QualType FT = FD->getType();
1569
1570 // FIXME: What are the right qualifiers here?
1571 LValue LV = EmitLValueForField(Addr, FD, false, 0);
1572 if (CodeGenFunction::hasAggregateLLVMType(FT)) {
1573 ExpandTypeToArgs(FT, RValue::getAggregate(LV.getAddress()), Args);
1574 } else {
1575 RValue RV = EmitLoadOfLValue(LV, FT);
1576 assert(RV.isScalar() &&
1577 "Unexpected non-scalar rvalue during struct expansion.");
1578 Args.push_back(RV.getScalarVal());
1579 }
1580 }
1581}
1582
Daniel Dunbar275e10d2009-02-02 19:06:38 +00001583/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
1584/// a pointer to an object of type \arg Ty.
1585///
1586/// This safely handles the case when the src type is smaller than the
1587/// destination type; in this situation the values of bits which not
1588/// present in the src are undefined.
1589static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
1590 const llvm::Type *Ty,
1591 CodeGenFunction &CGF) {
1592 const llvm::Type *SrcTy =
1593 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
Duncan Sands9408c452009-05-09 07:08:47 +00001594 uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy);
1595 uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(Ty);
Daniel Dunbar275e10d2009-02-02 19:06:38 +00001596
Daniel Dunbarb225be42009-02-03 05:59:18 +00001597 // If load is legal, just bitcast the src pointer.
Daniel Dunbar7ef455b2009-05-13 18:54:26 +00001598 if (SrcSize >= DstSize) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00001599 // Generally SrcSize is never greater than DstSize, since this means we are
1600 // losing bits. However, this can happen in cases where the structure has
1601 // additional padding, for example due to a user specified alignment.
Daniel Dunbar7ef455b2009-05-13 18:54:26 +00001602 //
Mike Stumpf5408fe2009-05-16 07:57:57 +00001603 // FIXME: Assert that we aren't truncating non-padding bits when have access
1604 // to that information.
Daniel Dunbar275e10d2009-02-02 19:06:38 +00001605 llvm::Value *Casted =
1606 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbar386621f2009-02-07 02:46:03 +00001607 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
1608 // FIXME: Use better alignment / avoid requiring aligned load.
1609 Load->setAlignment(1);
1610 return Load;
Daniel Dunbar275e10d2009-02-02 19:06:38 +00001611 } else {
Daniel Dunbar275e10d2009-02-02 19:06:38 +00001612 // Otherwise do coercion through memory. This is stupid, but
1613 // simple.
1614 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
1615 llvm::Value *Casted =
1616 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbar386621f2009-02-07 02:46:03 +00001617 llvm::StoreInst *Store =
1618 CGF.Builder.CreateStore(CGF.Builder.CreateLoad(SrcPtr), Casted);
1619 // FIXME: Use better alignment / avoid requiring aligned store.
1620 Store->setAlignment(1);
Daniel Dunbar275e10d2009-02-02 19:06:38 +00001621 return CGF.Builder.CreateLoad(Tmp);
1622 }
1623}
1624
1625/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
1626/// where the source and destination may have different types.
1627///
1628/// This safely handles the case when the src type is larger than the
1629/// destination type; the upper bits of the src will be lost.
1630static void CreateCoercedStore(llvm::Value *Src,
1631 llvm::Value *DstPtr,
1632 CodeGenFunction &CGF) {
1633 const llvm::Type *SrcTy = Src->getType();
1634 const llvm::Type *DstTy =
1635 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
1636
Duncan Sands9408c452009-05-09 07:08:47 +00001637 uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy);
1638 uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(DstTy);
Daniel Dunbar275e10d2009-02-02 19:06:38 +00001639
Daniel Dunbar88c2fa92009-02-03 05:31:23 +00001640 // If store is legal, just bitcast the src pointer.
Daniel Dunbarfdf49862009-06-05 07:58:54 +00001641 if (SrcSize <= DstSize) {
Daniel Dunbar275e10d2009-02-02 19:06:38 +00001642 llvm::Value *Casted =
1643 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbar386621f2009-02-07 02:46:03 +00001644 // FIXME: Use better alignment / avoid requiring aligned store.
1645 CGF.Builder.CreateStore(Src, Casted)->setAlignment(1);
Daniel Dunbar275e10d2009-02-02 19:06:38 +00001646 } else {
Daniel Dunbar275e10d2009-02-02 19:06:38 +00001647 // Otherwise do coercion through memory. This is stupid, but
1648 // simple.
Daniel Dunbarfdf49862009-06-05 07:58:54 +00001649
1650 // Generally SrcSize is never greater than DstSize, since this means we are
1651 // losing bits. However, this can happen in cases where the structure has
1652 // additional padding, for example due to a user specified alignment.
1653 //
1654 // FIXME: Assert that we aren't truncating non-padding bits when have access
1655 // to that information.
Daniel Dunbar275e10d2009-02-02 19:06:38 +00001656 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
1657 CGF.Builder.CreateStore(Src, Tmp);
1658 llvm::Value *Casted =
1659 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(DstTy));
Daniel Dunbar386621f2009-02-07 02:46:03 +00001660 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
1661 // FIXME: Use better alignment / avoid requiring aligned load.
1662 Load->setAlignment(1);
1663 CGF.Builder.CreateStore(Load, DstPtr);
Daniel Dunbar275e10d2009-02-02 19:06:38 +00001664 }
1665}
1666
Daniel Dunbar56273772008-09-17 00:51:38 +00001667/***/
1668
Daniel Dunbar88b53962009-02-02 22:03:45 +00001669bool CodeGenModule::ReturnTypeUsesSret(const CGFunctionInfo &FI) {
Daniel Dunbar11e383a2009-02-05 08:00:50 +00001670 return FI.getReturnInfo().isIndirect();
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001671}
1672
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001673const llvm::FunctionType *
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001674CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI, bool IsVariadic) {
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001675 std::vector<const llvm::Type*> ArgTys;
1676
1677 const llvm::Type *ResultType = 0;
1678
Daniel Dunbara0a99e02009-02-02 23:43:58 +00001679 QualType RetTy = FI.getReturnType();
Daniel Dunbarb225be42009-02-03 05:59:18 +00001680 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001681 switch (RetAI.getKind()) {
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001682 case ABIArgInfo::Expand:
1683 assert(0 && "Invalid ABI kind for return argument");
1684
Daniel Dunbar46327aa2009-02-03 06:17:37 +00001685 case ABIArgInfo::Direct:
1686 ResultType = ConvertType(RetTy);
1687 break;
1688
Daniel Dunbar11e383a2009-02-05 08:00:50 +00001689 case ABIArgInfo::Indirect: {
1690 assert(!RetAI.getIndirectAlign() && "Align unused on indirect return.");
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001691 ResultType = llvm::Type::VoidTy;
Daniel Dunbar62d5c1b2008-09-10 07:00:50 +00001692 const llvm::Type *STy = ConvertType(RetTy);
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001693 ArgTys.push_back(llvm::PointerType::get(STy, RetTy.getAddressSpace()));
1694 break;
1695 }
1696
Daniel Dunbar11434922009-01-26 21:26:08 +00001697 case ABIArgInfo::Ignore:
1698 ResultType = llvm::Type::VoidTy;
1699 break;
1700
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001701 case ABIArgInfo::Coerce:
Daniel Dunbar639ffe42008-09-10 07:04:09 +00001702 ResultType = RetAI.getCoerceToType();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001703 break;
1704 }
1705
Daniel Dunbar88c2fa92009-02-03 05:31:23 +00001706 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1707 ie = FI.arg_end(); it != ie; ++it) {
1708 const ABIArgInfo &AI = it->info;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001709
1710 switch (AI.getKind()) {
Daniel Dunbar11434922009-01-26 21:26:08 +00001711 case ABIArgInfo::Ignore:
1712 break;
1713
Daniel Dunbar56273772008-09-17 00:51:38 +00001714 case ABIArgInfo::Coerce:
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001715 ArgTys.push_back(AI.getCoerceToType());
1716 break;
1717
Daniel Dunbaradc8bdd2009-02-10 01:51:39 +00001718 case ABIArgInfo::Indirect: {
Daniel Dunbar11e383a2009-02-05 08:00:50 +00001719 // indirect arguments are always on the stack, which is addr space #0.
Daniel Dunbaradc8bdd2009-02-10 01:51:39 +00001720 const llvm::Type *LTy = ConvertTypeForMem(it->type);
1721 ArgTys.push_back(llvm::PointerType::getUnqual(LTy));
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001722 break;
Daniel Dunbaradc8bdd2009-02-10 01:51:39 +00001723 }
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001724
Daniel Dunbar46327aa2009-02-03 06:17:37 +00001725 case ABIArgInfo::Direct:
Daniel Dunbar1f745982009-02-05 09:16:39 +00001726 ArgTys.push_back(ConvertType(it->type));
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001727 break;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001728
1729 case ABIArgInfo::Expand:
Daniel Dunbar88c2fa92009-02-03 05:31:23 +00001730 GetExpandedTypes(it->type, ArgTys);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001731 break;
1732 }
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001733 }
1734
Daniel Dunbarbb36d332009-02-02 21:43:58 +00001735 return llvm::FunctionType::get(ResultType, ArgTys, IsVariadic);
Daniel Dunbar3913f182008-09-09 23:48:28 +00001736}
1737
Daniel Dunbara0a99e02009-02-02 23:43:58 +00001738void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbar88b53962009-02-02 22:03:45 +00001739 const Decl *TargetDecl,
Devang Patel761d7f72008-09-25 21:02:23 +00001740 AttributeListType &PAL) {
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001741 unsigned FuncAttrs = 0;
Devang Patela2c69122008-09-26 22:53:57 +00001742 unsigned RetAttrs = 0;
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001743
Anton Korobeynikov1102f422009-04-04 00:49:24 +00001744 // FIXME: handle sseregparm someday...
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001745 if (TargetDecl) {
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +00001746 if (TargetDecl->hasAttr<NoThrowAttr>())
Devang Patel761d7f72008-09-25 21:02:23 +00001747 FuncAttrs |= llvm::Attribute::NoUnwind;
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +00001748 if (TargetDecl->hasAttr<NoReturnAttr>())
Devang Patel761d7f72008-09-25 21:02:23 +00001749 FuncAttrs |= llvm::Attribute::NoReturn;
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +00001750 if (TargetDecl->hasAttr<ConstAttr>())
Anders Carlsson232eb7d2008-10-05 23:32:53 +00001751 FuncAttrs |= llvm::Attribute::ReadNone;
Daniel Dunbarb11fa0d2009-04-13 21:08:27 +00001752 else if (TargetDecl->hasAttr<PureAttr>())
Daniel Dunbar64c2e072009-04-10 22:14:52 +00001753 FuncAttrs |= llvm::Attribute::ReadOnly;
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001754 }
1755
Devang Patel24095da2009-06-04 23:32:02 +00001756 if (CompileOpts.DisableRedZone)
1757 FuncAttrs |= llvm::Attribute::NoRedZone;
1758
Daniel Dunbara0a99e02009-02-02 23:43:58 +00001759 QualType RetTy = FI.getReturnType();
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001760 unsigned Index = 1;
Daniel Dunbarb225be42009-02-03 05:59:18 +00001761 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar45c25ba2008-09-10 04:01:49 +00001762 switch (RetAI.getKind()) {
Daniel Dunbar46327aa2009-02-03 06:17:37 +00001763 case ABIArgInfo::Direct:
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001764 if (RetTy->isPromotableIntegerType()) {
1765 if (RetTy->isSignedIntegerType()) {
Devang Patela2c69122008-09-26 22:53:57 +00001766 RetAttrs |= llvm::Attribute::SExt;
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001767 } else if (RetTy->isUnsignedIntegerType()) {
Devang Patela2c69122008-09-26 22:53:57 +00001768 RetAttrs |= llvm::Attribute::ZExt;
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001769 }
1770 }
1771 break;
1772
Daniel Dunbar11e383a2009-02-05 08:00:50 +00001773 case ABIArgInfo::Indirect:
Devang Patel761d7f72008-09-25 21:02:23 +00001774 PAL.push_back(llvm::AttributeWithIndex::get(Index,
Daniel Dunbar725ad312009-01-31 02:19:00 +00001775 llvm::Attribute::StructRet |
1776 llvm::Attribute::NoAlias));
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001777 ++Index;
Daniel Dunbar0ac86f02009-03-18 19:51:01 +00001778 // sret disables readnone and readonly
1779 FuncAttrs &= ~(llvm::Attribute::ReadOnly |
1780 llvm::Attribute::ReadNone);
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001781 break;
1782
Daniel Dunbar11434922009-01-26 21:26:08 +00001783 case ABIArgInfo::Ignore:
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001784 case ABIArgInfo::Coerce:
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001785 break;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001786
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001787 case ABIArgInfo::Expand:
1788 assert(0 && "Invalid ABI kind for return argument");
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001789 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001790
Devang Patela2c69122008-09-26 22:53:57 +00001791 if (RetAttrs)
1792 PAL.push_back(llvm::AttributeWithIndex::get(0, RetAttrs));
Anton Korobeynikov1102f422009-04-04 00:49:24 +00001793
1794 // FIXME: we need to honour command line settings also...
1795 // FIXME: RegParm should be reduced in case of nested functions and/or global
1796 // register variable.
1797 signed RegParm = 0;
1798 if (TargetDecl)
1799 if (const RegparmAttr *RegParmAttr = TargetDecl->getAttr<RegparmAttr>())
1800 RegParm = RegParmAttr->getNumParams();
1801
1802 unsigned PointerWidth = getContext().Target.getPointerWidth(0);
Daniel Dunbar88c2fa92009-02-03 05:31:23 +00001803 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1804 ie = FI.arg_end(); it != ie; ++it) {
1805 QualType ParamType = it->type;
1806 const ABIArgInfo &AI = it->info;
Devang Patel761d7f72008-09-25 21:02:23 +00001807 unsigned Attributes = 0;
Anton Korobeynikov1102f422009-04-04 00:49:24 +00001808
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001809 switch (AI.getKind()) {
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001810 case ABIArgInfo::Coerce:
1811 break;
1812
Daniel Dunbar11e383a2009-02-05 08:00:50 +00001813 case ABIArgInfo::Indirect:
Devang Patel761d7f72008-09-25 21:02:23 +00001814 Attributes |= llvm::Attribute::ByVal;
Anton Korobeynikov1102f422009-04-04 00:49:24 +00001815 Attributes |=
Daniel Dunbar11e383a2009-02-05 08:00:50 +00001816 llvm::Attribute::constructAlignmentFromInt(AI.getIndirectAlign());
Daniel Dunbar0ac86f02009-03-18 19:51:01 +00001817 // byval disables readnone and readonly.
1818 FuncAttrs &= ~(llvm::Attribute::ReadOnly |
1819 llvm::Attribute::ReadNone);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001820 break;
1821
Daniel Dunbar46327aa2009-02-03 06:17:37 +00001822 case ABIArgInfo::Direct:
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001823 if (ParamType->isPromotableIntegerType()) {
1824 if (ParamType->isSignedIntegerType()) {
Devang Patel761d7f72008-09-25 21:02:23 +00001825 Attributes |= llvm::Attribute::SExt;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001826 } else if (ParamType->isUnsignedIntegerType()) {
Devang Patel761d7f72008-09-25 21:02:23 +00001827 Attributes |= llvm::Attribute::ZExt;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001828 }
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001829 }
Anton Korobeynikov1102f422009-04-04 00:49:24 +00001830 if (RegParm > 0 &&
1831 (ParamType->isIntegerType() || ParamType->isPointerType())) {
1832 RegParm -=
1833 (Context.getTypeSize(ParamType) + PointerWidth - 1) / PointerWidth;
1834 if (RegParm >= 0)
1835 Attributes |= llvm::Attribute::InReg;
1836 }
1837 // FIXME: handle sseregparm someday...
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001838 break;
Anton Korobeynikov1102f422009-04-04 00:49:24 +00001839
Daniel Dunbar11434922009-01-26 21:26:08 +00001840 case ABIArgInfo::Ignore:
1841 // Skip increment, no matching LLVM parameter.
1842 continue;
1843
Daniel Dunbar56273772008-09-17 00:51:38 +00001844 case ABIArgInfo::Expand: {
1845 std::vector<const llvm::Type*> Tys;
Mike Stumpf5408fe2009-05-16 07:57:57 +00001846 // FIXME: This is rather inefficient. Do we ever actually need to do
1847 // anything here? The result should be just reconstructed on the other
1848 // side, so extension should be a non-issue.
Daniel Dunbar56273772008-09-17 00:51:38 +00001849 getTypes().GetExpandedTypes(ParamType, Tys);
1850 Index += Tys.size();
1851 continue;
1852 }
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001853 }
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001854
Devang Patel761d7f72008-09-25 21:02:23 +00001855 if (Attributes)
1856 PAL.push_back(llvm::AttributeWithIndex::get(Index, Attributes));
Daniel Dunbar56273772008-09-17 00:51:38 +00001857 ++Index;
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001858 }
Devang Patela2c69122008-09-26 22:53:57 +00001859 if (FuncAttrs)
1860 PAL.push_back(llvm::AttributeWithIndex::get(~0, FuncAttrs));
Daniel Dunbar5323a4b2008-09-10 00:32:18 +00001861}
1862
Daniel Dunbar88b53962009-02-02 22:03:45 +00001863void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1864 llvm::Function *Fn,
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001865 const FunctionArgList &Args) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00001866 // FIXME: We no longer need the types from FunctionArgList; lift up and
1867 // simplify.
Daniel Dunbar5251afa2009-02-03 06:02:10 +00001868
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001869 // Emit allocs for param decls. Give the LLVM Argument nodes names.
1870 llvm::Function::arg_iterator AI = Fn->arg_begin();
1871
1872 // Name the struct return argument.
Daniel Dunbar88b53962009-02-02 22:03:45 +00001873 if (CGM.ReturnTypeUsesSret(FI)) {
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001874 AI->setName("agg.result");
1875 ++AI;
1876 }
Daniel Dunbarb225be42009-02-03 05:59:18 +00001877
Daniel Dunbar4b5f0a42009-02-04 21:17:21 +00001878 assert(FI.arg_size() == Args.size() &&
1879 "Mismatch between function signature & arguments.");
Daniel Dunbarb225be42009-02-03 05:59:18 +00001880 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001881 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Daniel Dunbarb225be42009-02-03 05:59:18 +00001882 i != e; ++i, ++info_it) {
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001883 const VarDecl *Arg = i->first;
Daniel Dunbarb225be42009-02-03 05:59:18 +00001884 QualType Ty = info_it->type;
1885 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001886
1887 switch (ArgI.getKind()) {
Daniel Dunbar1f745982009-02-05 09:16:39 +00001888 case ABIArgInfo::Indirect: {
1889 llvm::Value* V = AI;
1890 if (hasAggregateLLVMType(Ty)) {
1891 // Do nothing, aggregates and complex variables are accessed by
1892 // reference.
1893 } else {
1894 // Load scalar value from indirect argument.
Daniel Dunbaradc8bdd2009-02-10 01:51:39 +00001895 V = EmitLoadOfScalar(V, false, Ty);
Daniel Dunbar1f745982009-02-05 09:16:39 +00001896 if (!getContext().typesAreCompatible(Ty, Arg->getType())) {
1897 // This must be a promotion, for something like
1898 // "void a(x) short x; {..."
1899 V = EmitScalarConversion(V, Ty, Arg->getType());
1900 }
1901 }
1902 EmitParmDecl(*Arg, V);
1903 break;
1904 }
1905
Daniel Dunbar46327aa2009-02-03 06:17:37 +00001906 case ABIArgInfo::Direct: {
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001907 assert(AI != Fn->arg_end() && "Argument mismatch!");
1908 llvm::Value* V = AI;
Daniel Dunbar2fbf2f52009-02-05 11:13:54 +00001909 if (hasAggregateLLVMType(Ty)) {
1910 // Create a temporary alloca to hold the argument; the rest of
1911 // codegen expects to access aggregates & complex values by
1912 // reference.
Daniel Dunbaradc8bdd2009-02-10 01:51:39 +00001913 V = CreateTempAlloca(ConvertTypeForMem(Ty));
Daniel Dunbar2fbf2f52009-02-05 11:13:54 +00001914 Builder.CreateStore(AI, V);
1915 } else {
1916 if (!getContext().typesAreCompatible(Ty, Arg->getType())) {
1917 // This must be a promotion, for something like
1918 // "void a(x) short x; {..."
1919 V = EmitScalarConversion(V, Ty, Arg->getType());
1920 }
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001921 }
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001922 EmitParmDecl(*Arg, V);
1923 break;
1924 }
Daniel Dunbar56273772008-09-17 00:51:38 +00001925
1926 case ABIArgInfo::Expand: {
Daniel Dunbarb225be42009-02-03 05:59:18 +00001927 // If this structure was expanded into multiple arguments then
Daniel Dunbar56273772008-09-17 00:51:38 +00001928 // we need to create a temporary and reconstruct it from the
1929 // arguments.
Chris Lattner39f34e92008-11-24 04:00:27 +00001930 std::string Name = Arg->getNameAsString();
Daniel Dunbaradc8bdd2009-02-10 01:51:39 +00001931 llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(Ty),
Daniel Dunbar56273772008-09-17 00:51:38 +00001932 (Name + ".addr").c_str());
1933 // FIXME: What are the right qualifiers here?
1934 llvm::Function::arg_iterator End =
1935 ExpandTypeFromArgs(Ty, LValue::MakeAddr(Temp,0), AI);
1936 EmitParmDecl(*Arg, Temp);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001937
Daniel Dunbar56273772008-09-17 00:51:38 +00001938 // Name the arguments used in expansion and increment AI.
1939 unsigned Index = 0;
1940 for (; AI != End; ++AI, ++Index)
1941 AI->setName(Name + "." + llvm::utostr(Index));
1942 continue;
1943 }
Daniel Dunbar11434922009-01-26 21:26:08 +00001944
1945 case ABIArgInfo::Ignore:
Daniel Dunbar8b979d92009-02-10 00:06:49 +00001946 // Initialize the local variable appropriately.
1947 if (hasAggregateLLVMType(Ty)) {
Daniel Dunbaradc8bdd2009-02-10 01:51:39 +00001948 EmitParmDecl(*Arg, CreateTempAlloca(ConvertTypeForMem(Ty)));
Daniel Dunbar8b979d92009-02-10 00:06:49 +00001949 } else {
1950 EmitParmDecl(*Arg, llvm::UndefValue::get(ConvertType(Arg->getType())));
1951 }
1952
Daniel Dunbar59e5a0e2009-02-03 20:00:13 +00001953 // Skip increment, no matching LLVM parameter.
1954 continue;
Daniel Dunbar11434922009-01-26 21:26:08 +00001955
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001956 case ABIArgInfo::Coerce: {
1957 assert(AI != Fn->arg_end() && "Argument mismatch!");
Mike Stumpf5408fe2009-05-16 07:57:57 +00001958 // FIXME: This is very wasteful; EmitParmDecl is just going to drop the
1959 // result in a new alloca anyway, so we could just store into that
1960 // directly if we broke the abstraction down more.
Daniel Dunbaradc8bdd2009-02-10 01:51:39 +00001961 llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(Ty), "coerce");
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001962 CreateCoercedStore(AI, V, *this);
1963 // Match to what EmitParmDecl is expecting for this type.
Daniel Dunbar8b29a382009-02-04 07:22:24 +00001964 if (!CodeGenFunction::hasAggregateLLVMType(Ty)) {
Daniel Dunbaradc8bdd2009-02-10 01:51:39 +00001965 V = EmitLoadOfScalar(V, false, Ty);
Daniel Dunbar8b29a382009-02-04 07:22:24 +00001966 if (!getContext().typesAreCompatible(Ty, Arg->getType())) {
1967 // This must be a promotion, for something like
1968 // "void a(x) short x; {..."
1969 V = EmitScalarConversion(V, Ty, Arg->getType());
1970 }
1971 }
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00001972 EmitParmDecl(*Arg, V);
1973 break;
1974 }
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00001975 }
Daniel Dunbar56273772008-09-17 00:51:38 +00001976
1977 ++AI;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001978 }
1979 assert(AI == Fn->arg_end() && "Argument mismatch!");
1980}
1981
Daniel Dunbar88b53962009-02-02 22:03:45 +00001982void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Daniel Dunbar17b708d2008-09-09 23:27:19 +00001983 llvm::Value *ReturnValue) {
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001984 llvm::Value *RV = 0;
1985
1986 // Functions with no result always return void.
1987 if (ReturnValue) {
Daniel Dunbar88b53962009-02-02 22:03:45 +00001988 QualType RetTy = FI.getReturnType();
Daniel Dunbarb225be42009-02-03 05:59:18 +00001989 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00001990
1991 switch (RetAI.getKind()) {
Daniel Dunbar11e383a2009-02-05 08:00:50 +00001992 case ABIArgInfo::Indirect:
Daniel Dunbar3aea8ca2008-12-18 04:52:14 +00001993 if (RetTy->isAnyComplexType()) {
Daniel Dunbar3aea8ca2008-12-18 04:52:14 +00001994 ComplexPairTy RT = LoadComplexFromAddr(ReturnValue, false);
1995 StoreComplexToAddr(RT, CurFn->arg_begin(), false);
1996 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1997 EmitAggregateCopy(CurFn->arg_begin(), ReturnValue, RetTy);
1998 } else {
Daniel Dunbaradc8bdd2009-02-10 01:51:39 +00001999 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue), CurFn->arg_begin(),
Anders Carlssonb4aa4662009-05-19 18:50:41 +00002000 false, RetTy);
Daniel Dunbar3aea8ca2008-12-18 04:52:14 +00002001 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00002002 break;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00002003
Daniel Dunbar46327aa2009-02-03 06:17:37 +00002004 case ABIArgInfo::Direct:
Daniel Dunbar2fbf2f52009-02-05 11:13:54 +00002005 // The internal return value temp always will have
2006 // pointer-to-return-type type.
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00002007 RV = Builder.CreateLoad(ReturnValue);
2008 break;
2009
Daniel Dunbar11434922009-01-26 21:26:08 +00002010 case ABIArgInfo::Ignore:
2011 break;
2012
Daniel Dunbaradc8bdd2009-02-10 01:51:39 +00002013 case ABIArgInfo::Coerce:
Daniel Dunbar54d1ccb2009-01-27 01:36:03 +00002014 RV = CreateCoercedLoad(ReturnValue, RetAI.getCoerceToType(), *this);
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00002015 break;
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00002016
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00002017 case ABIArgInfo::Expand:
2018 assert(0 && "Invalid ABI kind for return argument");
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002019 }
2020 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00002021
2022 if (RV) {
2023 Builder.CreateRet(RV);
2024 } else {
2025 Builder.CreateRetVoid();
2026 }
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002027}
2028
Anders Carlsson0139bb92009-04-08 20:47:54 +00002029RValue CodeGenFunction::EmitCallArg(const Expr *E, QualType ArgType) {
Anders Carlsson4029ca72009-05-20 00:24:07 +00002030 if (ArgType->isReferenceType())
2031 return EmitReferenceBindingToExpr(E, ArgType);
2032
Anders Carlsson0139bb92009-04-08 20:47:54 +00002033 return EmitAnyExprToTemp(E);
2034}
2035
Daniel Dunbar88b53962009-02-02 22:03:45 +00002036RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
2037 llvm::Value *Callee,
Daniel Dunbarc0ef9f52009-02-20 18:06:48 +00002038 const CallArgList &CallArgs,
2039 const Decl *TargetDecl) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00002040 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002041 llvm::SmallVector<llvm::Value*, 16> Args;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002042
2043 // Handle struct-return functions by passing a pointer to the
2044 // location that we would like to return into.
Daniel Dunbarbb36d332009-02-02 21:43:58 +00002045 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbarb225be42009-02-03 05:59:18 +00002046 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Daniel Dunbar2969a022009-02-05 09:24:53 +00002047 if (CGM.ReturnTypeUsesSret(CallInfo)) {
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002048 // Create a temporary alloca to hold the result of the call. :(
Daniel Dunbaradc8bdd2009-02-10 01:51:39 +00002049 Args.push_back(CreateTempAlloca(ConvertTypeForMem(RetTy)));
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002050 }
2051
Daniel Dunbar4b5f0a42009-02-04 21:17:21 +00002052 assert(CallInfo.arg_size() == CallArgs.size() &&
2053 "Mismatch between function signature & arguments.");
Daniel Dunbarb225be42009-02-03 05:59:18 +00002054 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002055 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Daniel Dunbarb225be42009-02-03 05:59:18 +00002056 I != E; ++I, ++info_it) {
2057 const ABIArgInfo &ArgInfo = info_it->info;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002058 RValue RV = I->first;
Daniel Dunbar56273772008-09-17 00:51:38 +00002059
2060 switch (ArgInfo.getKind()) {
Daniel Dunbar11e383a2009-02-05 08:00:50 +00002061 case ABIArgInfo::Indirect:
Daniel Dunbar1f745982009-02-05 09:16:39 +00002062 if (RV.isScalar() || RV.isComplex()) {
2063 // Make a temporary alloca to pass the argument.
Daniel Dunbaradc8bdd2009-02-10 01:51:39 +00002064 Args.push_back(CreateTempAlloca(ConvertTypeForMem(I->second)));
Daniel Dunbar1f745982009-02-05 09:16:39 +00002065 if (RV.isScalar())
Anders Carlssonb4aa4662009-05-19 18:50:41 +00002066 EmitStoreOfScalar(RV.getScalarVal(), Args.back(), false, I->second);
Daniel Dunbar1f745982009-02-05 09:16:39 +00002067 else
2068 StoreComplexToAddr(RV.getComplexVal(), Args.back(), false);
2069 } else {
2070 Args.push_back(RV.getAggregateAddr());
2071 }
2072 break;
2073
Daniel Dunbar46327aa2009-02-03 06:17:37 +00002074 case ABIArgInfo::Direct:
Daniel Dunbar56273772008-09-17 00:51:38 +00002075 if (RV.isScalar()) {
2076 Args.push_back(RV.getScalarVal());
2077 } else if (RV.isComplex()) {
Daniel Dunbar2fbf2f52009-02-05 11:13:54 +00002078 llvm::Value *Tmp = llvm::UndefValue::get(ConvertType(I->second));
2079 Tmp = Builder.CreateInsertValue(Tmp, RV.getComplexVal().first, 0);
2080 Tmp = Builder.CreateInsertValue(Tmp, RV.getComplexVal().second, 1);
2081 Args.push_back(Tmp);
Daniel Dunbar56273772008-09-17 00:51:38 +00002082 } else {
Daniel Dunbar2fbf2f52009-02-05 11:13:54 +00002083 Args.push_back(Builder.CreateLoad(RV.getAggregateAddr()));
Daniel Dunbar56273772008-09-17 00:51:38 +00002084 }
2085 break;
2086
Daniel Dunbar11434922009-01-26 21:26:08 +00002087 case ABIArgInfo::Ignore:
2088 break;
2089
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00002090 case ABIArgInfo::Coerce: {
2091 // FIXME: Avoid the conversion through memory if possible.
2092 llvm::Value *SrcPtr;
2093 if (RV.isScalar()) {
Daniel Dunbar5a1be6e2009-02-03 23:04:57 +00002094 SrcPtr = CreateTempAlloca(ConvertTypeForMem(I->second), "coerce");
Anders Carlssonb4aa4662009-05-19 18:50:41 +00002095 EmitStoreOfScalar(RV.getScalarVal(), SrcPtr, false, I->second);
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00002096 } else if (RV.isComplex()) {
Daniel Dunbaradc8bdd2009-02-10 01:51:39 +00002097 SrcPtr = CreateTempAlloca(ConvertTypeForMem(I->second), "coerce");
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00002098 StoreComplexToAddr(RV.getComplexVal(), SrcPtr, false);
2099 } else
2100 SrcPtr = RV.getAggregateAddr();
2101 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
2102 *this));
2103 break;
2104 }
2105
Daniel Dunbar56273772008-09-17 00:51:38 +00002106 case ABIArgInfo::Expand:
2107 ExpandTypeToArgs(I->second, RV, Args);
2108 break;
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002109 }
2110 }
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002111
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00002112 llvm::BasicBlock *InvokeDest = getInvokeDest();
Devang Patel761d7f72008-09-25 21:02:23 +00002113 CodeGen::AttributeListType AttributeList;
Daniel Dunbarc0ef9f52009-02-20 18:06:48 +00002114 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList);
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00002115 llvm::AttrListPtr Attrs = llvm::AttrListPtr::get(AttributeList.begin(),
2116 AttributeList.end());
Daniel Dunbar725ad312009-01-31 02:19:00 +00002117
Daniel Dunbard14151d2009-03-02 04:32:35 +00002118 llvm::CallSite CS;
2119 if (!InvokeDest || (Attrs.getFnAttributes() & llvm::Attribute::NoUnwind)) {
Jay Foadbeaaccd2009-05-21 09:52:38 +00002120 CS = Builder.CreateCall(Callee, Args.data(), Args.data()+Args.size());
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00002121 } else {
2122 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
Daniel Dunbard14151d2009-03-02 04:32:35 +00002123 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest,
Jay Foadbeaaccd2009-05-21 09:52:38 +00002124 Args.data(), Args.data()+Args.size());
Daniel Dunbar9834ffb2009-02-23 17:26:39 +00002125 EmitBlock(Cont);
Daniel Dunbarf4fe0f02009-02-20 18:54:31 +00002126 }
2127
Daniel Dunbard14151d2009-03-02 04:32:35 +00002128 CS.setAttributes(Attrs);
Torok Edwin6857d9d2009-05-22 07:25:06 +00002129 if (const llvm::Function *F = dyn_cast<llvm::Function>(Callee->stripPointerCasts()))
Daniel Dunbard14151d2009-03-02 04:32:35 +00002130 CS.setCallingConv(F->getCallingConv());
2131
2132 // If the call doesn't return, finish the basic block and clear the
2133 // insertion point; this allows the rest of IRgen to discard
2134 // unreachable code.
2135 if (CS.doesNotReturn()) {
2136 Builder.CreateUnreachable();
2137 Builder.ClearInsertionPoint();
2138
Mike Stumpf5408fe2009-05-16 07:57:57 +00002139 // FIXME: For now, emit a dummy basic block because expr emitters in
2140 // generally are not ready to handle emitting expressions at unreachable
2141 // points.
Daniel Dunbard14151d2009-03-02 04:32:35 +00002142 EnsureInsertPoint();
2143
2144 // Return a reasonable RValue.
2145 return GetUndefRValue(RetTy);
2146 }
2147
2148 llvm::Instruction *CI = CS.getInstruction();
Chris Lattner34030842009-03-22 00:32:22 +00002149 if (Builder.isNamePreserving() && CI->getType() != llvm::Type::VoidTy)
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002150 CI->setName("call");
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00002151
2152 switch (RetAI.getKind()) {
Daniel Dunbar11e383a2009-02-05 08:00:50 +00002153 case ABIArgInfo::Indirect:
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00002154 if (RetTy->isAnyComplexType())
Daniel Dunbar56273772008-09-17 00:51:38 +00002155 return RValue::getComplex(LoadComplexFromAddr(Args[0], false));
Chris Lattner34030842009-03-22 00:32:22 +00002156 if (CodeGenFunction::hasAggregateLLVMType(RetTy))
Daniel Dunbar56273772008-09-17 00:51:38 +00002157 return RValue::getAggregate(Args[0]);
Chris Lattner34030842009-03-22 00:32:22 +00002158 return RValue::get(EmitLoadOfScalar(Args[0], false, RetTy));
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00002159
Daniel Dunbar46327aa2009-02-03 06:17:37 +00002160 case ABIArgInfo::Direct:
Daniel Dunbar2fbf2f52009-02-05 11:13:54 +00002161 if (RetTy->isAnyComplexType()) {
2162 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
2163 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
2164 return RValue::getComplex(std::make_pair(Real, Imag));
Chris Lattner34030842009-03-22 00:32:22 +00002165 }
2166 if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
Daniel Dunbaradc8bdd2009-02-10 01:51:39 +00002167 llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(RetTy), "agg.tmp");
Daniel Dunbar2fbf2f52009-02-05 11:13:54 +00002168 Builder.CreateStore(CI, V);
2169 return RValue::getAggregate(V);
Chris Lattner34030842009-03-22 00:32:22 +00002170 }
2171 return RValue::get(CI);
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00002172
Daniel Dunbar11434922009-01-26 21:26:08 +00002173 case ABIArgInfo::Ignore:
Daniel Dunbar0bcc5212009-02-03 06:30:17 +00002174 // If we are ignoring an argument that had a result, make sure to
2175 // construct the appropriate return value for our caller.
Daniel Dunbar13e81732009-02-05 07:09:07 +00002176 return GetUndefRValue(RetTy);
Daniel Dunbar11434922009-01-26 21:26:08 +00002177
Daniel Dunbar639ffe42008-09-10 07:04:09 +00002178 case ABIArgInfo::Coerce: {
Daniel Dunbar89c9d8e2009-02-03 19:12:28 +00002179 // FIXME: Avoid the conversion through memory if possible.
Daniel Dunbaradc8bdd2009-02-10 01:51:39 +00002180 llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(RetTy), "coerce");
Daniel Dunbar54d1ccb2009-01-27 01:36:03 +00002181 CreateCoercedStore(CI, V, *this);
Anders Carlssonad3d6912008-11-25 22:21:48 +00002182 if (RetTy->isAnyComplexType())
2183 return RValue::getComplex(LoadComplexFromAddr(V, false));
Chris Lattner34030842009-03-22 00:32:22 +00002184 if (CodeGenFunction::hasAggregateLLVMType(RetTy))
Anders Carlssonad3d6912008-11-25 22:21:48 +00002185 return RValue::getAggregate(V);
Chris Lattner34030842009-03-22 00:32:22 +00002186 return RValue::get(EmitLoadOfScalar(V, false, RetTy));
Daniel Dunbar639ffe42008-09-10 07:04:09 +00002187 }
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00002188
Daniel Dunbar8951dbd2008-09-11 01:48:57 +00002189 case ABIArgInfo::Expand:
2190 assert(0 && "Invalid ABI kind for return argument");
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002191 }
Daniel Dunbar2c8e0f32008-09-10 02:41:04 +00002192
2193 assert(0 && "Unhandled ABIArgInfo::Kind");
2194 return RValue::get(0);
Daniel Dunbar17b708d2008-09-09 23:27:19 +00002195}
Daniel Dunbarb4094ea2009-02-10 20:44:09 +00002196
2197/* VarArg handling */
2198
2199llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
2200 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
2201}