blob: 974b9b46f6df5c8e1a5a52a8365156723a324be1 [file] [log] [blame]
Daniel Dunbara8f02052008-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 Dunbar3ef2e852008-09-10 00:41:16 +000017#include "CodeGenModule.h"
Daniel Dunbarf98eeff2008-10-13 17:02:26 +000018#include "clang/Basic/TargetInfo.h"
Daniel Dunbara8f02052008-09-08 21:33:45 +000019#include "clang/AST/ASTContext.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclObjC.h"
Daniel Dunbar51a2d192009-01-29 08:13:58 +000022#include "clang/AST/RecordLayout.h"
Daniel Dunbar04d35782008-09-17 00:51:38 +000023#include "llvm/ADT/StringExtras.h"
Devang Patel98bfe502008-09-24 01:01:36 +000024#include "llvm/Attributes.h"
Daniel Dunbare09a9692009-01-24 08:32:22 +000025#include "llvm/Support/CommandLine.h"
Daniel Dunbar3cfcec72009-02-12 09:04:14 +000026#include "llvm/Support/MathExtras.h"
Daniel Dunbar9f4874e2009-02-04 23:24:38 +000027#include "llvm/Support/raw_ostream.h"
Daniel Dunbar708d8a82009-01-27 01:36:03 +000028#include "llvm/Target/TargetData.h"
Daniel Dunbard283e632009-02-03 01:05:53 +000029
30#include "ABIInfo.h"
31
Daniel Dunbara8f02052008-09-08 21:33:45 +000032using namespace clang;
33using namespace CodeGen;
34
35/***/
36
Daniel Dunbara8f02052008-09-08 21:33:45 +000037// FIXME: Use iterator and sidestep silly type array creation.
38
Daniel Dunbar34bda882009-02-02 23:23:47 +000039const
40CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionTypeNoProto *FTNP) {
41 return getFunctionInfo(FTNP->getResultType(),
42 llvm::SmallVector<QualType, 16>());
Daniel Dunbar3ad1f072008-09-10 04:01:49 +000043}
44
Daniel Dunbar34bda882009-02-02 23:23:47 +000045const
46CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionTypeProto *FTP) {
47 llvm::SmallVector<QualType, 16> ArgTys;
48 // FIXME: Kill copy.
Daniel Dunbar3ad1f072008-09-10 04:01:49 +000049 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
Daniel Dunbar34bda882009-02-02 23:23:47 +000050 ArgTys.push_back(FTP->getArgType(i));
51 return getFunctionInfo(FTP->getResultType(), ArgTys);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +000052}
53
Daniel Dunbar34bda882009-02-02 23:23:47 +000054const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionDecl *FD) {
Daniel Dunbara8f02052008-09-08 21:33:45 +000055 const FunctionType *FTy = FD->getType()->getAsFunctionType();
Daniel Dunbar34bda882009-02-02 23:23:47 +000056 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FTy))
57 return getFunctionInfo(FTP);
58 return getFunctionInfo(cast<FunctionTypeNoProto>(FTy));
Daniel Dunbara8f02052008-09-08 21:33:45 +000059}
60
Daniel Dunbar34bda882009-02-02 23:23:47 +000061const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const ObjCMethodDecl *MD) {
62 llvm::SmallVector<QualType, 16> ArgTys;
63 ArgTys.push_back(MD->getSelfDecl()->getType());
64 ArgTys.push_back(Context.getObjCSelType());
65 // FIXME: Kill copy?
Chris Lattner9408eb12009-02-20 06:23:21 +000066 for (ObjCMethodDecl::param_iterator i = MD->param_begin(),
Daniel Dunbara8f02052008-09-08 21:33:45 +000067 e = MD->param_end(); i != e; ++i)
Daniel Dunbar34bda882009-02-02 23:23:47 +000068 ArgTys.push_back((*i)->getType());
69 return getFunctionInfo(MD->getResultType(), ArgTys);
Daniel Dunbara8f02052008-09-08 21:33:45 +000070}
71
Daniel Dunbar34bda882009-02-02 23:23:47 +000072const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
73 const CallArgList &Args) {
74 // FIXME: Kill copy.
75 llvm::SmallVector<QualType, 16> ArgTys;
Daniel Dunbarebbb8f32009-01-31 02:19:00 +000076 for (CallArgList::const_iterator i = Args.begin(), e = Args.end();
77 i != e; ++i)
Daniel Dunbar34bda882009-02-02 23:23:47 +000078 ArgTys.push_back(i->second);
79 return getFunctionInfo(ResTy, ArgTys);
Daniel Dunbarebbb8f32009-01-31 02:19:00 +000080}
81
Daniel Dunbar34bda882009-02-02 23:23:47 +000082const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
83 const FunctionArgList &Args) {
84 // FIXME: Kill copy.
85 llvm::SmallVector<QualType, 16> ArgTys;
Daniel Dunbar9fc15a82009-02-02 21:43:58 +000086 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
87 i != e; ++i)
Daniel Dunbar34bda882009-02-02 23:23:47 +000088 ArgTys.push_back(i->second);
89 return getFunctionInfo(ResTy, ArgTys);
90}
91
92const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
93 const llvm::SmallVector<QualType, 16> &ArgTys) {
Daniel Dunbardcf19d12009-02-03 00:07:12 +000094 // Lookup or create unique function info.
95 llvm::FoldingSetNodeID ID;
96 CGFunctionInfo::Profile(ID, ResTy, ArgTys.begin(), ArgTys.end());
97
98 void *InsertPos = 0;
99 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, InsertPos);
100 if (FI)
101 return *FI;
102
Daniel Dunbare92e0ab2009-02-03 05:31:23 +0000103 // Construct the function info.
Daniel Dunbardcf19d12009-02-03 00:07:12 +0000104 FI = new CGFunctionInfo(ResTy, ArgTys);
Daniel Dunbarb944cc92009-02-05 00:00:23 +0000105 FunctionInfos.InsertNode(FI, InsertPos);
Daniel Dunbare92e0ab2009-02-03 05:31:23 +0000106
107 // Compute ABI information.
Daniel Dunbar749e36b2009-02-03 06:51:18 +0000108 getABIInfo().computeInfo(*FI, getContext());
Daniel Dunbare92e0ab2009-02-03 05:31:23 +0000109
Daniel Dunbardcf19d12009-02-03 00:07:12 +0000110 return *FI;
Daniel Dunbar34bda882009-02-02 23:23:47 +0000111}
112
113/***/
114
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000115ABIInfo::~ABIInfo() {}
116
Daniel Dunbar9f4874e2009-02-04 23:24:38 +0000117void ABIArgInfo::dump() const {
118 fprintf(stderr, "(ABIArgInfo Kind=");
119 switch (TheKind) {
120 case Direct:
121 fprintf(stderr, "Direct");
122 break;
Daniel Dunbar9f4874e2009-02-04 23:24:38 +0000123 case Ignore:
124 fprintf(stderr, "Ignore");
125 break;
126 case Coerce:
127 fprintf(stderr, "Coerce Type=");
128 getCoerceToType()->print(llvm::errs());
129 // FIXME: This is ridiculous.
130 llvm::errs().flush();
131 break;
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000132 case Indirect:
133 fprintf(stderr, "Indirect Align=%d", getIndirectAlign());
Daniel Dunbar9f4874e2009-02-04 23:24:38 +0000134 break;
135 case Expand:
136 fprintf(stderr, "Expand");
137 break;
138 }
139 fprintf(stderr, ")\n");
140}
141
142/***/
143
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000144/// isEmptyStruct - Return true iff a structure has no non-empty
145/// members. Note that a structure with a flexible array member is not
146/// considered empty.
147static bool isEmptyStruct(QualType T) {
148 const RecordType *RT = T->getAsStructureType();
149 if (!RT)
150 return 0;
151 const RecordDecl *RD = RT->getDecl();
152 if (RD->hasFlexibleArrayMember())
153 return false;
Douglas Gregor5d764842009-01-09 17:18:27 +0000154 for (RecordDecl::field_iterator i = RD->field_begin(),
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000155 e = RD->field_end(); i != e; ++i) {
156 const FieldDecl *FD = *i;
157 if (!isEmptyStruct(FD->getType()))
158 return false;
159 }
160 return true;
161}
162
163/// isSingleElementStruct - Determine if a structure is a "single
164/// element struct", i.e. it has exactly one non-empty field or
165/// exactly one field which is itself a single element
166/// struct. Structures with flexible array members are never
167/// considered single element structs.
168///
169/// \return The field declaration for the single non-empty field, if
170/// it exists.
171static const FieldDecl *isSingleElementStruct(QualType T) {
172 const RecordType *RT = T->getAsStructureType();
173 if (!RT)
174 return 0;
175
176 const RecordDecl *RD = RT->getDecl();
177 if (RD->hasFlexibleArrayMember())
178 return 0;
179
180 const FieldDecl *Found = 0;
Douglas Gregor5d764842009-01-09 17:18:27 +0000181 for (RecordDecl::field_iterator i = RD->field_begin(),
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000182 e = RD->field_end(); i != e; ++i) {
183 const FieldDecl *FD = *i;
184 QualType FT = FD->getType();
185
186 if (isEmptyStruct(FT)) {
187 // Ignore
188 } else if (Found) {
189 return 0;
190 } else if (!CodeGenFunction::hasAggregateLLVMType(FT)) {
191 Found = FD;
192 } else {
193 Found = isSingleElementStruct(FT);
194 if (!Found)
195 return 0;
196 }
197 }
198
199 return Found;
200}
201
202static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
203 if (!Ty->getAsBuiltinType() && !Ty->isPointerType())
204 return false;
205
206 uint64_t Size = Context.getTypeSize(Ty);
207 return Size == 32 || Size == 64;
208}
209
210static bool areAllFields32Or64BitBasicType(const RecordDecl *RD,
211 ASTContext &Context) {
Douglas Gregor5d764842009-01-09 17:18:27 +0000212 for (RecordDecl::field_iterator i = RD->field_begin(),
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000213 e = RD->field_end(); i != e; ++i) {
214 const FieldDecl *FD = *i;
215
216 if (!is32Or64BitBasicType(FD->getType(), Context))
217 return false;
218
219 // If this is a bit-field we need to make sure it is still a
220 // 32-bit or 64-bit type.
221 if (Expr *BW = FD->getBitWidth()) {
222 unsigned Width = BW->getIntegerConstantExprValue(Context).getZExtValue();
223 if (Width <= 16)
224 return false;
225 }
226 }
227 return true;
228}
229
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000230namespace {
231/// DefaultABIInfo - The default implementation for ABI specific
232/// details. This implementation provides information which results in
Daniel Dunbar749e36b2009-02-03 06:51:18 +0000233/// self-consistent and sensible LLVM IR generation, but does not
234/// conform to any particular ABI.
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000235class DefaultABIInfo : public ABIInfo {
Daniel Dunbar749e36b2009-02-03 06:51:18 +0000236 ABIArgInfo classifyReturnType(QualType RetTy,
237 ASTContext &Context) const;
238
239 ABIArgInfo classifyArgumentType(QualType RetTy,
240 ASTContext &Context) const;
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000241
Daniel Dunbar749e36b2009-02-03 06:51:18 +0000242 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
243 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
244 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
245 it != ie; ++it)
246 it->info = classifyArgumentType(it->type, Context);
247 }
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000248
249 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
250 CodeGenFunction &CGF) const;
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000251};
252
253/// X86_32ABIInfo - The X86-32 ABI information.
254class X86_32ABIInfo : public ABIInfo {
255public:
Daniel Dunbar749e36b2009-02-03 06:51:18 +0000256 ABIArgInfo classifyReturnType(QualType RetTy,
257 ASTContext &Context) const;
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000258
Daniel Dunbar749e36b2009-02-03 06:51:18 +0000259 ABIArgInfo classifyArgumentType(QualType RetTy,
260 ASTContext &Context) const;
261
262 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
263 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
264 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
265 it != ie; ++it)
266 it->info = classifyArgumentType(it->type, Context);
267 }
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000268
269 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
270 CodeGenFunction &CGF) const;
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000271};
272}
273
274ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
275 ASTContext &Context) const {
Daniel Dunbareec02622009-02-03 06:30:17 +0000276 if (RetTy->isVoidType()) {
277 return ABIArgInfo::getIgnore();
278 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000279 // Classify "single element" structs as their element type.
280 const FieldDecl *SeltFD = isSingleElementStruct(RetTy);
281 if (SeltFD) {
282 QualType SeltTy = SeltFD->getType()->getDesugaredType();
283 if (const BuiltinType *BT = SeltTy->getAsBuiltinType()) {
284 // FIXME: This is gross, it would be nice if we could just
285 // pass back SeltTy and have clients deal with it. Is it worth
286 // supporting coerce to both LLVM and clang Types?
287 if (BT->isIntegerType()) {
288 uint64_t Size = Context.getTypeSize(SeltTy);
289 return ABIArgInfo::getCoerce(llvm::IntegerType::get((unsigned) Size));
290 } else if (BT->getKind() == BuiltinType::Float) {
291 return ABIArgInfo::getCoerce(llvm::Type::FloatTy);
292 } else if (BT->getKind() == BuiltinType::Double) {
293 return ABIArgInfo::getCoerce(llvm::Type::DoubleTy);
294 }
295 } else if (SeltTy->isPointerType()) {
296 // FIXME: It would be really nice if this could come out as
297 // the proper pointer type.
298 llvm::Type *PtrTy =
299 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
300 return ABIArgInfo::getCoerce(PtrTy);
301 }
302 }
303
Daniel Dunbar73d66602008-09-10 07:04:09 +0000304 uint64_t Size = Context.getTypeSize(RetTy);
305 if (Size == 8) {
306 return ABIArgInfo::getCoerce(llvm::Type::Int8Ty);
307 } else if (Size == 16) {
308 return ABIArgInfo::getCoerce(llvm::Type::Int16Ty);
309 } else if (Size == 32) {
310 return ABIArgInfo::getCoerce(llvm::Type::Int32Ty);
311 } else if (Size == 64) {
312 return ABIArgInfo::getCoerce(llvm::Type::Int64Ty);
313 } else {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000314 return ABIArgInfo::getIndirect(0);
Daniel Dunbar73d66602008-09-10 07:04:09 +0000315 }
Daniel Dunbare126ab12008-09-10 02:41:04 +0000316 } else {
Daniel Dunbareec02622009-02-03 06:30:17 +0000317 return ABIArgInfo::getDirect();
Daniel Dunbare126ab12008-09-10 02:41:04 +0000318 }
319}
320
Daniel Dunbarf98eeff2008-10-13 17:02:26 +0000321ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000322 ASTContext &Context) const {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000323 // FIXME: Set alignment on indirect arguments.
Daniel Dunbar3158c592008-09-17 20:11:04 +0000324 if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000325 // Structures with flexible arrays are always indirect.
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000326 if (const RecordType *RT = Ty->getAsStructureType())
327 if (RT->getDecl()->hasFlexibleArrayMember())
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000328 return ABIArgInfo::getIndirect(0);
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000329
Daniel Dunbar33b189a2009-02-05 01:50:07 +0000330 // Ignore empty structs.
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000331 uint64_t Size = Context.getTypeSize(Ty);
332 if (Ty->isStructureType() && Size == 0)
Daniel Dunbar33b189a2009-02-05 01:50:07 +0000333 return ABIArgInfo::getIgnore();
Daniel Dunbar99eebc62008-09-17 21:22:33 +0000334
335 // Expand structs with size <= 128-bits which consist only of
336 // basic types (int, long long, float, double, xxx*). This is
337 // non-recursive and does not ignore empty fields.
338 if (const RecordType *RT = Ty->getAsStructureType()) {
339 if (Context.getTypeSize(Ty) <= 4*32 &&
340 areAllFields32Or64BitBasicType(RT->getDecl(), Context))
341 return ABIArgInfo::getExpand();
342 }
343
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000344 return ABIArgInfo::getIndirect(0);
Daniel Dunbar22e30052008-09-11 01:48:57 +0000345 } else {
Daniel Dunbareec02622009-02-03 06:30:17 +0000346 return ABIArgInfo::getDirect();
Daniel Dunbar22e30052008-09-11 01:48:57 +0000347 }
348}
349
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000350llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
351 CodeGenFunction &CGF) const {
352 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
353 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
354
355 CGBuilderTy &Builder = CGF.Builder;
356 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
357 "ap");
358 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
359 llvm::Type *PTy =
360 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
361 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
362
Daniel Dunbarbae4b662009-02-18 22:28:45 +0000363 uint64_t Offset =
364 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000365 llvm::Value *NextAddr =
366 Builder.CreateGEP(Addr,
Daniel Dunbarbae4b662009-02-18 22:28:45 +0000367 llvm::ConstantInt::get(llvm::Type::Int32Ty, Offset),
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000368 "ap.next");
369 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
370
371 return AddrTyped;
372}
373
Daniel Dunbare09a9692009-01-24 08:32:22 +0000374namespace {
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000375/// X86_64ABIInfo - The X86_64 ABI information.
Daniel Dunbare09a9692009-01-24 08:32:22 +0000376class X86_64ABIInfo : public ABIInfo {
377 enum Class {
378 Integer = 0,
379 SSE,
380 SSEUp,
381 X87,
382 X87Up,
383 ComplexX87,
384 NoClass,
385 Memory
386 };
387
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000388 /// merge - Implement the X86_64 ABI merging algorithm.
389 ///
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000390 /// Merge an accumulating classification \arg Accum with a field
391 /// classification \arg Field.
392 ///
393 /// \param Accum - The accumulating classification. This should
394 /// always be either NoClass or the result of a previous merge
395 /// call. In addition, this should never be Memory (the caller
396 /// should just return Memory for the aggregate).
397 Class merge(Class Accum, Class Field) const;
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000398
Daniel Dunbare09a9692009-01-24 08:32:22 +0000399 /// classify - Determine the x86_64 register classes in which the
400 /// given type T should be passed.
401 ///
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000402 /// \param Lo - The classification for the parts of the type
403 /// residing in the low word of the containing object.
404 ///
405 /// \param Hi - The classification for the parts of the type
406 /// residing in the high word of the containing object.
407 ///
408 /// \param OffsetBase - The bit offset of this type in the
Daniel Dunbar2a2dce32009-01-30 22:40:15 +0000409 /// containing object. Some parameters are classified different
410 /// depending on whether they straddle an eightbyte boundary.
Daniel Dunbare09a9692009-01-24 08:32:22 +0000411 ///
412 /// If a word is unused its result will be NoClass; if a type should
413 /// be passed in Memory then at least the classification of \arg Lo
414 /// will be Memory.
415 ///
416 /// The \arg Lo class will be NoClass iff the argument is ignored.
417 ///
418 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
Daniel Dunbar92e88642009-02-17 07:55:55 +0000419 /// also be ComplexX87.
Daniel Dunbar1aa2be92009-01-30 00:47:38 +0000420 void classify(QualType T, ASTContext &Context, uint64_t OffsetBase,
Daniel Dunbare09a9692009-01-24 08:32:22 +0000421 Class &Lo, Class &Hi) const;
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000422
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000423 /// getCoerceResult - Given a source type \arg Ty and an LLVM type
424 /// to coerce to, chose the best way to pass Ty in the same place
425 /// that \arg CoerceTo would be passed, but while keeping the
426 /// emitted code as simple as possible.
427 ///
428 /// FIXME: Note, this should be cleaned up to just take an
429 /// enumeration of all the ways we might want to pass things,
430 /// instead of constructing an LLVM type. This makes this code more
431 /// explicit, and it makes it clearer that we are also doing this
432 /// for correctness in the case of passing scalar types.
433 ABIArgInfo getCoerceResult(QualType Ty,
434 const llvm::Type *CoerceTo,
435 ASTContext &Context) const;
436
Daniel Dunbar749e36b2009-02-03 06:51:18 +0000437 ABIArgInfo classifyReturnType(QualType RetTy,
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000438 ASTContext &Context) const;
439
440 ABIArgInfo classifyArgumentType(QualType Ty,
441 ASTContext &Context,
Daniel Dunbare978cb92009-02-10 17:06:09 +0000442 unsigned &neededInt,
443 unsigned &neededSSE) const;
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000444
445public:
446 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const;
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000447
448 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
449 CodeGenFunction &CGF) const;
Daniel Dunbare09a9692009-01-24 08:32:22 +0000450};
451}
452
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000453X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum,
454 Class Field) const {
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000455 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
456 // classified recursively so that always two fields are
457 // considered. The resulting class is calculated according to
458 // the classes of the fields in the eightbyte:
459 //
460 // (a) If both classes are equal, this is the resulting class.
461 //
462 // (b) If one of the classes is NO_CLASS, the resulting class is
463 // the other class.
464 //
465 // (c) If one of the classes is MEMORY, the result is the MEMORY
466 // class.
467 //
468 // (d) If one of the classes is INTEGER, the result is the
469 // INTEGER.
470 //
471 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
472 // MEMORY is used as class.
473 //
474 // (f) Otherwise class SSE is used.
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000475 assert((Accum == NoClass || Accum == Integer ||
476 Accum == SSE || Accum == SSEUp) &&
477 "Invalid accumulated classification during merge.");
478 if (Accum == Field || Field == NoClass)
479 return Accum;
480 else if (Field == Memory)
481 return Memory;
482 else if (Accum == NoClass)
483 return Field;
484 else if (Accum == Integer || Field == Integer)
485 return Integer;
486 else if (Field == X87 || Field == X87Up || Field == ComplexX87)
487 return Memory;
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000488 else
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000489 return SSE;
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000490}
491
Daniel Dunbare09a9692009-01-24 08:32:22 +0000492void X86_64ABIInfo::classify(QualType Ty,
493 ASTContext &Context,
Daniel Dunbar1aa2be92009-01-30 00:47:38 +0000494 uint64_t OffsetBase,
Daniel Dunbare09a9692009-01-24 08:32:22 +0000495 Class &Lo, Class &Hi) const {
Daniel Dunbar36b378e2009-02-02 18:06:39 +0000496 // FIXME: This code can be simplified by introducing a simple value
497 // class for Class pairs with appropriate constructor methods for
498 // the various situations.
499
Daniel Dunbard97f5952009-02-22 04:48:22 +0000500 // FIXME: Some of the split computations are wrong; unaligned
501 // vectors shouldn't be passed in registers for example, so there is
502 // no chance they can straddle an eightbyte. Verify & simplify.
503
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000504 Lo = Hi = NoClass;
505
506 Class &Current = OffsetBase < 64 ? Lo : Hi;
507 Current = Memory;
508
Daniel Dunbare09a9692009-01-24 08:32:22 +0000509 if (const BuiltinType *BT = Ty->getAsBuiltinType()) {
510 BuiltinType::Kind k = BT->getKind();
511
Daniel Dunbar1358b202009-01-26 21:26:08 +0000512 if (k == BuiltinType::Void) {
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000513 Current = NoClass;
Daniel Dunbar1358b202009-01-26 21:26:08 +0000514 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000515 Current = Integer;
Daniel Dunbare09a9692009-01-24 08:32:22 +0000516 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000517 Current = SSE;
Daniel Dunbare09a9692009-01-24 08:32:22 +0000518 } else if (k == BuiltinType::LongDouble) {
519 Lo = X87;
520 Hi = X87Up;
521 }
Daniel Dunbarcf1f3be2009-01-27 02:01:34 +0000522 // FIXME: _Decimal32 and _Decimal64 are SSE.
523 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Daniel Dunbare09a9692009-01-24 08:32:22 +0000524 // FIXME: __int128 is (Integer, Integer).
525 } else if (Ty->isPointerLikeType() || Ty->isBlockPointerType() ||
Daniel Dunbar707af272009-02-26 07:21:35 +0000526 Ty->isObjCQualifiedIdType() ||
Daniel Dunbare09a9692009-01-24 08:32:22 +0000527 Ty->isObjCQualifiedInterfaceType()) {
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000528 Current = Integer;
Daniel Dunbarcf1f3be2009-01-27 02:01:34 +0000529 } else if (const VectorType *VT = Ty->getAsVectorType()) {
Daniel Dunbar1aa2be92009-01-30 00:47:38 +0000530 uint64_t Size = Context.getTypeSize(VT);
Daniel Dunbard97f5952009-02-22 04:48:22 +0000531 if (Size == 32) {
532 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
533 // float> as integer.
534 Current = Integer;
535
536 // If this type crosses an eightbyte boundary, it should be
537 // split.
538 uint64_t EB_Real = (OffsetBase) / 64;
539 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
540 if (EB_Real != EB_Imag)
541 Hi = Lo;
542 } else if (Size == 64) {
Daniel Dunbarb341feb2009-02-22 04:16:10 +0000543 // gcc passes <1 x double> in memory. :(
544 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
Daniel Dunbarcdf91e82009-01-30 19:38:39 +0000545 return;
Daniel Dunbarb341feb2009-02-22 04:16:10 +0000546
547 // gcc passes <1 x long long> as INTEGER.
548 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong))
549 Current = Integer;
550 else
551 Current = SSE;
Daniel Dunbare413f532009-01-30 18:40:10 +0000552
553 // If this type crosses an eightbyte boundary, it should be
554 // split.
Daniel Dunbar2a2dce32009-01-30 22:40:15 +0000555 if (OffsetBase && OffsetBase != 64)
Daniel Dunbare413f532009-01-30 18:40:10 +0000556 Hi = Lo;
Daniel Dunbarcf1f3be2009-01-27 02:01:34 +0000557 } else if (Size == 128) {
558 Lo = SSE;
559 Hi = SSEUp;
560 }
Daniel Dunbare09a9692009-01-24 08:32:22 +0000561 } else if (const ComplexType *CT = Ty->getAsComplexType()) {
Daniel Dunbare60d5332009-02-14 02:45:45 +0000562 QualType ET = Context.getCanonicalType(CT->getElementType());
Daniel Dunbare09a9692009-01-24 08:32:22 +0000563
Daniel Dunbare413f532009-01-30 18:40:10 +0000564 uint64_t Size = Context.getTypeSize(Ty);
Daniel Dunbarb341feb2009-02-22 04:16:10 +0000565 if (ET->isIntegralType()) {
Daniel Dunbar28770fc2009-01-29 07:22:20 +0000566 if (Size <= 64)
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000567 Current = Integer;
Daniel Dunbar28770fc2009-01-29 07:22:20 +0000568 else if (Size <= 128)
569 Lo = Hi = Integer;
570 } else if (ET == Context.FloatTy)
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000571 Current = SSE;
Daniel Dunbare09a9692009-01-24 08:32:22 +0000572 else if (ET == Context.DoubleTy)
573 Lo = Hi = SSE;
574 else if (ET == Context.LongDoubleTy)
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000575 Current = ComplexX87;
Daniel Dunbar6a7f8b32009-01-29 09:42:07 +0000576
577 // If this complex type crosses an eightbyte boundary then it
578 // should be split.
Daniel Dunbar2a2dce32009-01-30 22:40:15 +0000579 uint64_t EB_Real = (OffsetBase) / 64;
580 uint64_t EB_Imag = (OffsetBase + Context.getTypeSize(ET)) / 64;
Daniel Dunbar6a7f8b32009-01-29 09:42:07 +0000581 if (Hi == NoClass && EB_Real != EB_Imag)
582 Hi = Lo;
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000583 } else if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
584 // Arrays are treated like structures.
585
586 uint64_t Size = Context.getTypeSize(Ty);
587
588 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
589 // than two eightbytes, ..., it has class MEMORY.
590 if (Size > 128)
591 return;
592
593 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
594 // fields, it has class MEMORY.
595 //
596 // Only need to check alignment of array base.
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000597 if (OffsetBase % Context.getTypeAlign(AT->getElementType()))
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000598 return;
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000599
600 // Otherwise implement simplified merge. We could be smarter about
601 // this, but it isn't worth it and would be harder to verify.
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000602 Current = NoClass;
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000603 uint64_t EltSize = Context.getTypeSize(AT->getElementType());
604 uint64_t ArraySize = AT->getSize().getZExtValue();
605 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
606 Class FieldLo, FieldHi;
607 classify(AT->getElementType(), Context, Offset, FieldLo, FieldHi);
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000608 Lo = merge(Lo, FieldLo);
609 Hi = merge(Hi, FieldHi);
610 if (Lo == Memory || Hi == Memory)
611 break;
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000612 }
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000613
614 // Do post merger cleanup (see below). Only case we worry about is Memory.
615 if (Hi == Memory)
616 Lo = Memory;
617 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000618 } else if (const RecordType *RT = Ty->getAsRecordType()) {
Daniel Dunbar1aa2be92009-01-30 00:47:38 +0000619 uint64_t Size = Context.getTypeSize(Ty);
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000620
621 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
622 // than two eightbytes, ..., it has class MEMORY.
623 if (Size > 128)
624 return;
625
626 const RecordDecl *RD = RT->getDecl();
627
628 // Assume variable sized types are passed in memory.
629 if (RD->hasFlexibleArrayMember())
630 return;
631
632 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
633
634 // Reset Lo class, this will be recomputed.
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000635 Current = NoClass;
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000636 unsigned idx = 0;
637 for (RecordDecl::field_iterator i = RD->field_begin(),
638 e = RD->field_end(); i != e; ++i, ++idx) {
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000639 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Daniel Dunbard6fb35c2009-02-17 02:45:44 +0000640 bool BitField = i->isBitField();
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000641
Daniel Dunbar11dc6772009-01-30 08:09:32 +0000642 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
643 // fields, it has class MEMORY.
Daniel Dunbard6fb35c2009-02-17 02:45:44 +0000644 //
645 // Note, skip this test for bitfields, see below.
646 if (!BitField && Offset % Context.getTypeAlign(i->getType())) {
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000647 Lo = Memory;
648 return;
649 }
650
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000651 // Classify this field.
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000652 //
653 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
654 // exceeds a single eightbyte, each is classified
655 // separately. Each eightbyte gets initialized to class
656 // NO_CLASS.
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000657 Class FieldLo, FieldHi;
Daniel Dunbard6fb35c2009-02-17 02:45:44 +0000658
659 // Bitfields require special handling, they do not force the
660 // structure to be passed in memory even if unaligned, and
661 // therefore they can straddle an eightbyte.
662 if (BitField) {
663 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
664 uint64_t Size =
665 i->getBitWidth()->getIntegerConstantExprValue(Context).getZExtValue();
666
667 uint64_t EB_Lo = Offset / 64;
668 uint64_t EB_Hi = (Offset + Size - 1) / 64;
669 FieldLo = FieldHi = NoClass;
670 if (EB_Lo) {
671 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
672 FieldLo = NoClass;
673 FieldHi = Integer;
674 } else {
675 FieldLo = Integer;
676 FieldHi = EB_Hi ? Integer : NoClass;
677 }
678 } else
679 classify(i->getType(), Context, Offset, FieldLo, FieldHi);
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000680 Lo = merge(Lo, FieldLo);
681 Hi = merge(Hi, FieldHi);
682 if (Lo == Memory || Hi == Memory)
683 break;
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000684 }
685
686 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
687 //
688 // (a) If one of the classes is MEMORY, the whole argument is
689 // passed in memory.
690 //
691 // (b) If SSEUP is not preceeded by SSE, it is converted to SSE.
692
693 // The first of these conditions is guaranteed by how we implement
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000694 // the merge (just bail).
695 //
696 // The second condition occurs in the case of unions; for example
697 // union { _Complex double; unsigned; }.
698 if (Hi == Memory)
699 Lo = Memory;
Daniel Dunbar51a2d192009-01-29 08:13:58 +0000700 if (Hi == SSEUp && Lo != SSE)
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000701 Hi = SSE;
Daniel Dunbare09a9692009-01-24 08:32:22 +0000702 }
703}
704
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000705ABIArgInfo X86_64ABIInfo::getCoerceResult(QualType Ty,
706 const llvm::Type *CoerceTo,
707 ASTContext &Context) const {
708 if (CoerceTo == llvm::Type::Int64Ty) {
709 // Integer and pointer types will end up in a general purpose
710 // register.
Daniel Dunbarb341feb2009-02-22 04:16:10 +0000711 if (Ty->isIntegralType() || Ty->isPointerType())
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000712 return ABIArgInfo::getDirect();
Daniel Dunbarb341feb2009-02-22 04:16:10 +0000713
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000714 } else if (CoerceTo == llvm::Type::DoubleTy) {
Daniel Dunbare60d5332009-02-14 02:45:45 +0000715 // FIXME: It would probably be better to make CGFunctionInfo only
716 // map using canonical types than to canonize here.
717 QualType CTy = Context.getCanonicalType(Ty);
718
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000719 // Float and double end up in a single SSE reg.
Daniel Dunbare60d5332009-02-14 02:45:45 +0000720 if (CTy == Context.FloatTy || CTy == Context.DoubleTy)
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000721 return ABIArgInfo::getDirect();
Daniel Dunbarb341feb2009-02-22 04:16:10 +0000722
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000723 }
724
725 return ABIArgInfo::getCoerce(CoerceTo);
726}
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000727
Daniel Dunbarb6d5c442009-01-15 18:18:40 +0000728ABIArgInfo X86_64ABIInfo::classifyReturnType(QualType RetTy,
729 ASTContext &Context) const {
Daniel Dunbare09a9692009-01-24 08:32:22 +0000730 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
731 // classification algorithm.
732 X86_64ABIInfo::Class Lo, Hi;
Daniel Dunbar6a7f8b32009-01-29 09:42:07 +0000733 classify(RetTy, Context, 0, Lo, Hi);
Daniel Dunbare09a9692009-01-24 08:32:22 +0000734
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000735 // Check some invariants.
736 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
737 assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification.");
738 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
739
Daniel Dunbare09a9692009-01-24 08:32:22 +0000740 const llvm::Type *ResType = 0;
741 switch (Lo) {
742 case NoClass:
Daniel Dunbar1358b202009-01-26 21:26:08 +0000743 return ABIArgInfo::getIgnore();
Daniel Dunbare09a9692009-01-24 08:32:22 +0000744
745 case SSEUp:
746 case X87Up:
747 assert(0 && "Invalid classification for lo word.");
748
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000749 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000750 // hidden argument.
Daniel Dunbare09a9692009-01-24 08:32:22 +0000751 case Memory:
Daniel Dunbar88dde9b2009-02-05 08:00:50 +0000752 return ABIArgInfo::getIndirect(0);
Daniel Dunbare09a9692009-01-24 08:32:22 +0000753
754 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
755 // available register of the sequence %rax, %rdx is used.
756 case Integer:
757 ResType = llvm::Type::Int64Ty; break;
758
759 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
760 // available SSE register of the sequence %xmm0, %xmm1 is used.
761 case SSE:
762 ResType = llvm::Type::DoubleTy; break;
763
764 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
765 // returned on the X87 stack in %st0 as 80-bit x87 number.
766 case X87:
767 ResType = llvm::Type::X86_FP80Ty; break;
768
Daniel Dunbar64b132f2009-01-31 00:06:58 +0000769 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
770 // part of the value is returned in %st0 and the imaginary part in
771 // %st1.
Daniel Dunbare09a9692009-01-24 08:32:22 +0000772 case ComplexX87:
Daniel Dunbar92e88642009-02-17 07:55:55 +0000773 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Daniel Dunbar4fc0d492009-02-18 03:44:19 +0000774 ResType = llvm::StructType::get(llvm::Type::X86_FP80Ty,
775 llvm::Type::X86_FP80Ty,
776 NULL);
Daniel Dunbare09a9692009-01-24 08:32:22 +0000777 break;
778 }
779
780 switch (Hi) {
Daniel Dunbar92e88642009-02-17 07:55:55 +0000781 // Memory was handled previously and X87 should
782 // never occur as a hi class.
Daniel Dunbare09a9692009-01-24 08:32:22 +0000783 case Memory:
784 case X87:
Daniel Dunbare09a9692009-01-24 08:32:22 +0000785 assert(0 && "Invalid classification for hi word.");
786
Daniel Dunbar92e88642009-02-17 07:55:55 +0000787 case ComplexX87: // Previously handled.
Daniel Dunbare09a9692009-01-24 08:32:22 +0000788 case NoClass: break;
Daniel Dunbar92e88642009-02-17 07:55:55 +0000789
Daniel Dunbare09a9692009-01-24 08:32:22 +0000790 case Integer:
Daniel Dunbar7e8a7022009-01-29 07:36:07 +0000791 ResType = llvm::StructType::get(ResType, llvm::Type::Int64Ty, NULL);
792 break;
Daniel Dunbare09a9692009-01-24 08:32:22 +0000793 case SSE:
Daniel Dunbar7e8a7022009-01-29 07:36:07 +0000794 ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL);
795 break;
Daniel Dunbare09a9692009-01-24 08:32:22 +0000796
797 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
798 // is passed in the upper half of the last used SSE register.
799 //
800 // SSEUP should always be preceeded by SSE, just widen.
801 case SSEUp:
802 assert(Lo == SSE && "Unexpected SSEUp classification.");
803 ResType = llvm::VectorType::get(llvm::Type::DoubleTy, 2);
804 break;
805
806 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
Daniel Dunbar7e8a7022009-01-29 07:36:07 +0000807 // returned together with the previous X87 value in %st0.
Daniel Dunbare09a9692009-01-24 08:32:22 +0000808 //
809 // X87UP should always be preceeded by X87, so we don't need to do
810 // anything here.
811 case X87Up:
812 assert(Lo == X87 && "Unexpected X87Up classification.");
813 break;
814 }
815
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000816 return getCoerceResult(RetTy, ResType, Context);
Daniel Dunbarb6d5c442009-01-15 18:18:40 +0000817}
818
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000819ABIArgInfo X86_64ABIInfo::classifyArgumentType(QualType Ty, ASTContext &Context,
Daniel Dunbare978cb92009-02-10 17:06:09 +0000820 unsigned &neededInt,
821 unsigned &neededSSE) const {
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000822 X86_64ABIInfo::Class Lo, Hi;
823 classify(Ty, Context, 0, Lo, Hi);
824
825 // Check some invariants.
826 // FIXME: Enforce these by construction.
827 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
828 assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification.");
829 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
830
Daniel Dunbare978cb92009-02-10 17:06:09 +0000831 neededInt = 0;
832 neededSSE = 0;
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000833 const llvm::Type *ResType = 0;
834 switch (Lo) {
835 case NoClass:
836 return ABIArgInfo::getIgnore();
837
838 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
839 // on the stack.
840 case Memory:
841
842 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
843 // COMPLEX_X87, it is passed in memory.
844 case X87:
845 case ComplexX87:
Daniel Dunbard0536ac2009-02-22 08:17:51 +0000846 return ABIArgInfo::getIndirect(0);
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000847
848 case SSEUp:
849 case X87Up:
850 assert(0 && "Invalid classification for lo word.");
851
852 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
853 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
854 // and %r9 is used.
855 case Integer:
856 ++neededInt;
857 ResType = llvm::Type::Int64Ty;
858 break;
859
860 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
861 // available SSE register is used, the registers are taken in the
862 // order from %xmm0 to %xmm7.
863 case SSE:
864 ++neededSSE;
865 ResType = llvm::Type::DoubleTy;
866 break;
Daniel Dunbareec02622009-02-03 06:30:17 +0000867 }
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000868
869 switch (Hi) {
870 // Memory was handled previously, ComplexX87 and X87 should
871 // never occur as hi classes, and X87Up must be preceed by X87,
872 // which is passed in memory.
873 case Memory:
874 case X87:
875 case X87Up:
876 case ComplexX87:
877 assert(0 && "Invalid classification for hi word.");
878
879 case NoClass: break;
880 case Integer:
881 ResType = llvm::StructType::get(ResType, llvm::Type::Int64Ty, NULL);
882 ++neededInt;
883 break;
884 case SSE:
885 ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL);
886 ++neededSSE;
887 break;
888
889 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
890 // eightbyte is passed in the upper half of the last used SSE
891 // register.
892 case SSEUp:
893 assert(Lo == SSE && "Unexpected SSEUp classification.");
894 ResType = llvm::VectorType::get(llvm::Type::DoubleTy, 2);
895 break;
896 }
897
Daniel Dunbar87c4dc92009-02-14 02:09:24 +0000898 return getCoerceResult(Ty, ResType, Context);
Daniel Dunbar015bc8e2009-02-03 20:00:13 +0000899}
900
901void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
902 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
903
904 // Keep track of the number of assigned registers.
905 unsigned freeIntRegs = 6, freeSSERegs = 8;
906
907 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
908 // get assigned (in left-to-right order) for passing as follows...
909 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Daniel Dunbare978cb92009-02-10 17:06:09 +0000910 it != ie; ++it) {
911 unsigned neededInt, neededSSE;
912 it->info = classifyArgumentType(it->type, Context, neededInt, neededSSE);
913
914 // AMD64-ABI 3.2.3p3: If there are no registers available for any
915 // eightbyte of an argument, the whole argument is passed on the
916 // stack. If registers have already been assigned for some
917 // eightbytes of such an argument, the assignments get reverted.
918 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
919 freeIntRegs -= neededInt;
920 freeSSERegs -= neededSSE;
921 } else {
Daniel Dunbard0536ac2009-02-22 08:17:51 +0000922 it->info = ABIArgInfo::getIndirect(0);
Daniel Dunbare978cb92009-02-10 17:06:09 +0000923 }
924 }
Daniel Dunbarb6d5c442009-01-15 18:18:40 +0000925}
926
Daniel Dunbar3cfcec72009-02-12 09:04:14 +0000927static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
928 QualType Ty,
929 CodeGenFunction &CGF) {
930 llvm::Value *overflow_arg_area_p =
931 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
932 llvm::Value *overflow_arg_area =
933 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
934
935 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
936 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Daniel Dunbar2ab71bd2009-02-16 23:38:56 +0000937 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
Daniel Dunbar3cfcec72009-02-12 09:04:14 +0000938 if (Align > 8) {
Daniel Dunbar2ab71bd2009-02-16 23:38:56 +0000939 // Note that we follow the ABI & gcc here, even though the type
940 // could in theory have an alignment greater than 16. This case
941 // shouldn't ever matter in practice.
Daniel Dunbar3cfcec72009-02-12 09:04:14 +0000942
Daniel Dunbar2ab71bd2009-02-16 23:38:56 +0000943 // overflow_arg_area = (overflow_arg_area + 15) & ~15;
944 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty, 15);
945 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
946 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
947 llvm::Type::Int64Ty);
948 llvm::Value *Mask = llvm::ConstantInt::get(llvm::Type::Int64Ty, ~15LL);
949 overflow_arg_area =
950 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
951 overflow_arg_area->getType(),
952 "overflow_arg_area.align");
Daniel Dunbar3cfcec72009-02-12 09:04:14 +0000953 }
954
955 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
956 const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
957 llvm::Value *Res =
958 CGF.Builder.CreateBitCast(overflow_arg_area,
959 llvm::PointerType::getUnqual(LTy));
960
961 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
962 // l->overflow_arg_area + sizeof(type).
963 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
964 // an 8 byte boundary.
965
966 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
967 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty,
968 (SizeInBytes + 7) & ~7);
969 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
970 "overflow_arg_area.next");
971 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
972
973 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
974 return Res;
975}
976
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +0000977llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
978 CodeGenFunction &CGF) const {
Daniel Dunbar3cfcec72009-02-12 09:04:14 +0000979 // Assume that va_list type is correct; should be pointer to LLVM type:
980 // struct {
981 // i32 gp_offset;
982 // i32 fp_offset;
983 // i8* overflow_arg_area;
984 // i8* reg_save_area;
985 // };
986 unsigned neededInt, neededSSE;
987 ABIArgInfo AI = classifyArgumentType(Ty, CGF.getContext(),
988 neededInt, neededSSE);
989
990 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
991 // in the registers. If not go to step 7.
992 if (!neededInt && !neededSSE)
993 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
994
995 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
996 // general purpose registers needed to pass type and num_fp to hold
997 // the number of floating point registers needed.
998
999 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
1000 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
1001 // l->fp_offset > 304 - num_fp * 16 go to step 7.
1002 //
1003 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
1004 // register save space).
1005
1006 llvm::Value *InRegs = 0;
1007 llvm::Value *gp_offset_p = 0, *gp_offset = 0;
1008 llvm::Value *fp_offset_p = 0, *fp_offset = 0;
1009 if (neededInt) {
1010 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
1011 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
1012 InRegs =
1013 CGF.Builder.CreateICmpULE(gp_offset,
1014 llvm::ConstantInt::get(llvm::Type::Int32Ty,
1015 48 - neededInt * 8),
1016 "fits_in_gp");
1017 }
1018
1019 if (neededSSE) {
1020 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
1021 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
1022 llvm::Value *FitsInFP =
1023 CGF.Builder.CreateICmpULE(fp_offset,
1024 llvm::ConstantInt::get(llvm::Type::Int32Ty,
Daniel Dunbar63118762009-02-18 22:19:44 +00001025 176 - neededSSE * 16),
Daniel Dunbar3cfcec72009-02-12 09:04:14 +00001026 "fits_in_fp");
Daniel Dunbar72198842009-02-18 22:05:01 +00001027 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
Daniel Dunbar3cfcec72009-02-12 09:04:14 +00001028 }
1029
1030 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
1031 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
1032 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
1033 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
1034
1035 // Emit code to load the value if it was passed in registers.
1036
1037 CGF.EmitBlock(InRegBlock);
1038
1039 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
1040 // an offset of l->gp_offset and/or l->fp_offset. This may require
1041 // copying to a temporary location in case the parameter is passed
1042 // in different register classes or requires an alignment greater
1043 // than 8 for general purpose registers and 16 for XMM registers.
Daniel Dunbar4fc0d492009-02-18 03:44:19 +00001044 //
1045 // FIXME: This really results in shameful code when we end up
1046 // needing to collect arguments from different places; often what
1047 // should result in a simple assembling of a structure from
1048 // scattered addresses has many more loads than necessary. Can we
1049 // clean this up?
Daniel Dunbar3cfcec72009-02-12 09:04:14 +00001050 const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1051 llvm::Value *RegAddr =
1052 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
1053 "reg_save_area");
1054 if (neededInt && neededSSE) {
Daniel Dunbara96ec382009-02-13 17:46:31 +00001055 // FIXME: Cleanup.
1056 assert(AI.isCoerce() && "Unexpected ABI info for mixed regs");
1057 const llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
1058 llvm::Value *Tmp = CGF.CreateTempAlloca(ST);
1059 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
1060 const llvm::Type *TyLo = ST->getElementType(0);
1061 const llvm::Type *TyHi = ST->getElementType(1);
1062 assert((TyLo->isFloatingPoint() ^ TyHi->isFloatingPoint()) &&
1063 "Unexpected ABI info for mixed regs");
1064 const llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
1065 const llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
1066 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1067 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1068 llvm::Value *RegLoAddr = TyLo->isFloatingPoint() ? FPAddr : GPAddr;
1069 llvm::Value *RegHiAddr = TyLo->isFloatingPoint() ? GPAddr : FPAddr;
1070 llvm::Value *V =
1071 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
1072 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1073 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
1074 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1075
1076 RegAddr = CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(LTy));
Daniel Dunbar3cfcec72009-02-12 09:04:14 +00001077 } else if (neededInt) {
1078 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1079 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1080 llvm::PointerType::getUnqual(LTy));
1081 } else {
Daniel Dunbar4fc0d492009-02-18 03:44:19 +00001082 if (neededSSE == 1) {
1083 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1084 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1085 llvm::PointerType::getUnqual(LTy));
1086 } else {
1087 assert(neededSSE == 2 && "Invalid number of needed registers!");
1088 // SSE registers are spaced 16 bytes apart in the register save
1089 // area, we need to collect the two eightbytes together.
1090 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1091 llvm::Value *RegAddrHi =
1092 CGF.Builder.CreateGEP(RegAddrLo,
1093 llvm::ConstantInt::get(llvm::Type::Int32Ty, 16));
1094 const llvm::Type *DblPtrTy =
1095 llvm::PointerType::getUnqual(llvm::Type::DoubleTy);
1096 const llvm::StructType *ST = llvm::StructType::get(llvm::Type::DoubleTy,
1097 llvm::Type::DoubleTy,
1098 NULL);
1099 llvm::Value *V, *Tmp = CGF.CreateTempAlloca(ST);
1100 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
1101 DblPtrTy));
1102 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1103 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
1104 DblPtrTy));
1105 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1106 RegAddr = CGF.Builder.CreateBitCast(Tmp,
1107 llvm::PointerType::getUnqual(LTy));
1108 }
Daniel Dunbar3cfcec72009-02-12 09:04:14 +00001109 }
1110
1111 // AMD64-ABI 3.5.7p5: Step 5. Set:
1112 // l->gp_offset = l->gp_offset + num_gp * 8
1113 // l->fp_offset = l->fp_offset + num_fp * 16.
1114 if (neededInt) {
1115 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty,
1116 neededInt * 8);
1117 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
1118 gp_offset_p);
1119 }
1120 if (neededSSE) {
1121 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty,
1122 neededSSE * 16);
1123 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
1124 fp_offset_p);
1125 }
1126 CGF.EmitBranch(ContBlock);
1127
1128 // Emit code to load the value if it was passed in memory.
1129
1130 CGF.EmitBlock(InMemBlock);
1131 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1132
1133 // Return the appropriate result.
1134
1135 CGF.EmitBlock(ContBlock);
1136 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(),
1137 "vaarg.addr");
1138 ResAddr->reserveOperandSpace(2);
1139 ResAddr->addIncoming(RegAddr, InRegBlock);
1140 ResAddr->addIncoming(MemAddr, InMemBlock);
1141
1142 return ResAddr;
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +00001143}
1144
Daniel Dunbarf98eeff2008-10-13 17:02:26 +00001145ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy,
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +00001146 ASTContext &Context) const {
Daniel Dunbareec02622009-02-03 06:30:17 +00001147 if (RetTy->isVoidType()) {
1148 return ABIArgInfo::getIgnore();
1149 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001150 return ABIArgInfo::getIndirect(0);
Daniel Dunbareec02622009-02-03 06:30:17 +00001151 } else {
1152 return ABIArgInfo::getDirect();
1153 }
Daniel Dunbarf98eeff2008-10-13 17:02:26 +00001154}
1155
1156ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty,
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +00001157 ASTContext &Context) const {
Daniel Dunbareec02622009-02-03 06:30:17 +00001158 if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001159 return ABIArgInfo::getIndirect(0);
Daniel Dunbareec02622009-02-03 06:30:17 +00001160 } else {
1161 return ABIArgInfo::getDirect();
1162 }
Daniel Dunbarf98eeff2008-10-13 17:02:26 +00001163}
1164
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +00001165llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1166 CodeGenFunction &CGF) const {
1167 return 0;
1168}
1169
Daniel Dunbarf98eeff2008-10-13 17:02:26 +00001170const ABIInfo &CodeGenTypes::getABIInfo() const {
1171 if (TheABIInfo)
1172 return *TheABIInfo;
1173
1174 // For now we just cache this in the CodeGenTypes and don't bother
1175 // to free it.
1176 const char *TargetPrefix = getContext().Target.getTargetPrefix();
1177 if (strcmp(TargetPrefix, "x86") == 0) {
Daniel Dunbarb6d5c442009-01-15 18:18:40 +00001178 switch (getContext().Target.getPointerWidth(0)) {
1179 case 32:
Daniel Dunbarf98eeff2008-10-13 17:02:26 +00001180 return *(TheABIInfo = new X86_32ABIInfo());
Daniel Dunbarb6d5c442009-01-15 18:18:40 +00001181 case 64:
Daniel Dunbar56555952009-01-30 18:47:53 +00001182 return *(TheABIInfo = new X86_64ABIInfo());
Daniel Dunbarb6d5c442009-01-15 18:18:40 +00001183 }
Daniel Dunbarf98eeff2008-10-13 17:02:26 +00001184 }
1185
1186 return *(TheABIInfo = new DefaultABIInfo);
1187}
1188
Daniel Dunbare126ab12008-09-10 02:41:04 +00001189/***/
1190
Daniel Dunbare92e0ab2009-02-03 05:31:23 +00001191CGFunctionInfo::CGFunctionInfo(QualType ResTy,
1192 const llvm::SmallVector<QualType, 16> &ArgTys) {
1193 NumArgs = ArgTys.size();
1194 Args = new ArgInfo[1 + NumArgs];
1195 Args[0].type = ResTy;
1196 for (unsigned i = 0; i < NumArgs; ++i)
1197 Args[1 + i].type = ArgTys[i];
1198}
1199
1200/***/
1201
Daniel Dunbar04d35782008-09-17 00:51:38 +00001202void CodeGenTypes::GetExpandedTypes(QualType Ty,
1203 std::vector<const llvm::Type*> &ArgTys) {
1204 const RecordType *RT = Ty->getAsStructureType();
1205 assert(RT && "Can only expand structure types.");
1206 const RecordDecl *RD = RT->getDecl();
1207 assert(!RD->hasFlexibleArrayMember() &&
1208 "Cannot expand structure with flexible array.");
1209
Douglas Gregor5d764842009-01-09 17:18:27 +00001210 for (RecordDecl::field_iterator i = RD->field_begin(),
Daniel Dunbar04d35782008-09-17 00:51:38 +00001211 e = RD->field_end(); i != e; ++i) {
1212 const FieldDecl *FD = *i;
1213 assert(!FD->isBitField() &&
1214 "Cannot expand structure with bit-field members.");
1215
1216 QualType FT = FD->getType();
1217 if (CodeGenFunction::hasAggregateLLVMType(FT)) {
1218 GetExpandedTypes(FT, ArgTys);
1219 } else {
1220 ArgTys.push_back(ConvertType(FT));
1221 }
1222 }
1223}
1224
1225llvm::Function::arg_iterator
1226CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
1227 llvm::Function::arg_iterator AI) {
1228 const RecordType *RT = Ty->getAsStructureType();
1229 assert(RT && "Can only expand structure types.");
1230
1231 RecordDecl *RD = RT->getDecl();
1232 assert(LV.isSimple() &&
1233 "Unexpected non-simple lvalue during struct expansion.");
1234 llvm::Value *Addr = LV.getAddress();
1235 for (RecordDecl::field_iterator i = RD->field_begin(),
1236 e = RD->field_end(); i != e; ++i) {
1237 FieldDecl *FD = *i;
1238 QualType FT = FD->getType();
1239
1240 // FIXME: What are the right qualifiers here?
1241 LValue LV = EmitLValueForField(Addr, FD, false, 0);
1242 if (CodeGenFunction::hasAggregateLLVMType(FT)) {
1243 AI = ExpandTypeFromArgs(FT, LV, AI);
1244 } else {
1245 EmitStoreThroughLValue(RValue::get(AI), LV, FT);
1246 ++AI;
1247 }
1248 }
1249
1250 return AI;
1251}
1252
1253void
1254CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
1255 llvm::SmallVector<llvm::Value*, 16> &Args) {
1256 const RecordType *RT = Ty->getAsStructureType();
1257 assert(RT && "Can only expand structure types.");
1258
1259 RecordDecl *RD = RT->getDecl();
1260 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
1261 llvm::Value *Addr = RV.getAggregateAddr();
1262 for (RecordDecl::field_iterator i = RD->field_begin(),
1263 e = RD->field_end(); i != e; ++i) {
1264 FieldDecl *FD = *i;
1265 QualType FT = FD->getType();
1266
1267 // FIXME: What are the right qualifiers here?
1268 LValue LV = EmitLValueForField(Addr, FD, false, 0);
1269 if (CodeGenFunction::hasAggregateLLVMType(FT)) {
1270 ExpandTypeToArgs(FT, RValue::getAggregate(LV.getAddress()), Args);
1271 } else {
1272 RValue RV = EmitLoadOfLValue(LV, FT);
1273 assert(RV.isScalar() &&
1274 "Unexpected non-scalar rvalue during struct expansion.");
1275 Args.push_back(RV.getScalarVal());
1276 }
1277 }
1278}
1279
Daniel Dunbar84379912009-02-02 19:06:38 +00001280/// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
1281/// a pointer to an object of type \arg Ty.
1282///
1283/// This safely handles the case when the src type is smaller than the
1284/// destination type; in this situation the values of bits which not
1285/// present in the src are undefined.
1286static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
1287 const llvm::Type *Ty,
1288 CodeGenFunction &CGF) {
1289 const llvm::Type *SrcTy =
1290 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
1291 uint64_t SrcSize = CGF.CGM.getTargetData().getTypePaddedSize(SrcTy);
1292 uint64_t DstSize = CGF.CGM.getTargetData().getTypePaddedSize(Ty);
1293
Daniel Dunbar77071992009-02-03 05:59:18 +00001294 // If load is legal, just bitcast the src pointer.
Daniel Dunbar84379912009-02-02 19:06:38 +00001295 if (SrcSize == DstSize) {
1296 llvm::Value *Casted =
1297 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
Daniel Dunbar3f062382009-02-07 02:46:03 +00001298 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
1299 // FIXME: Use better alignment / avoid requiring aligned load.
1300 Load->setAlignment(1);
1301 return Load;
Daniel Dunbar84379912009-02-02 19:06:38 +00001302 } else {
1303 assert(SrcSize < DstSize && "Coercion is losing source bits!");
1304
1305 // Otherwise do coercion through memory. This is stupid, but
1306 // simple.
1307 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
1308 llvm::Value *Casted =
1309 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbar3f062382009-02-07 02:46:03 +00001310 llvm::StoreInst *Store =
1311 CGF.Builder.CreateStore(CGF.Builder.CreateLoad(SrcPtr), Casted);
1312 // FIXME: Use better alignment / avoid requiring aligned store.
1313 Store->setAlignment(1);
Daniel Dunbar84379912009-02-02 19:06:38 +00001314 return CGF.Builder.CreateLoad(Tmp);
1315 }
1316}
1317
1318/// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
1319/// where the source and destination may have different types.
1320///
1321/// This safely handles the case when the src type is larger than the
1322/// destination type; the upper bits of the src will be lost.
1323static void CreateCoercedStore(llvm::Value *Src,
1324 llvm::Value *DstPtr,
1325 CodeGenFunction &CGF) {
1326 const llvm::Type *SrcTy = Src->getType();
1327 const llvm::Type *DstTy =
1328 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
1329
1330 uint64_t SrcSize = CGF.CGM.getTargetData().getTypePaddedSize(SrcTy);
1331 uint64_t DstSize = CGF.CGM.getTargetData().getTypePaddedSize(DstTy);
1332
Daniel Dunbare92e0ab2009-02-03 05:31:23 +00001333 // If store is legal, just bitcast the src pointer.
Daniel Dunbar84379912009-02-02 19:06:38 +00001334 if (SrcSize == DstSize) {
1335 llvm::Value *Casted =
1336 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
Daniel Dunbar3f062382009-02-07 02:46:03 +00001337 // FIXME: Use better alignment / avoid requiring aligned store.
1338 CGF.Builder.CreateStore(Src, Casted)->setAlignment(1);
Daniel Dunbar84379912009-02-02 19:06:38 +00001339 } else {
1340 assert(SrcSize > DstSize && "Coercion is missing bits!");
1341
1342 // Otherwise do coercion through memory. This is stupid, but
1343 // simple.
1344 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
1345 CGF.Builder.CreateStore(Src, Tmp);
1346 llvm::Value *Casted =
1347 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(DstTy));
Daniel Dunbar3f062382009-02-07 02:46:03 +00001348 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
1349 // FIXME: Use better alignment / avoid requiring aligned load.
1350 Load->setAlignment(1);
1351 CGF.Builder.CreateStore(Load, DstPtr);
Daniel Dunbar84379912009-02-02 19:06:38 +00001352 }
1353}
1354
Daniel Dunbar04d35782008-09-17 00:51:38 +00001355/***/
1356
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001357bool CodeGenModule::ReturnTypeUsesSret(const CGFunctionInfo &FI) {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001358 return FI.getReturnInfo().isIndirect();
Daniel Dunbar9fc15a82009-02-02 21:43:58 +00001359}
1360
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001361const llvm::FunctionType *
Daniel Dunbar9fc15a82009-02-02 21:43:58 +00001362CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI, bool IsVariadic) {
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001363 std::vector<const llvm::Type*> ArgTys;
1364
1365 const llvm::Type *ResultType = 0;
1366
Daniel Dunbar0b37ca82009-02-02 23:43:58 +00001367 QualType RetTy = FI.getReturnType();
Daniel Dunbar77071992009-02-03 05:59:18 +00001368 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar22e30052008-09-11 01:48:57 +00001369 switch (RetAI.getKind()) {
Daniel Dunbar22e30052008-09-11 01:48:57 +00001370 case ABIArgInfo::Expand:
1371 assert(0 && "Invalid ABI kind for return argument");
1372
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00001373 case ABIArgInfo::Direct:
1374 ResultType = ConvertType(RetTy);
1375 break;
1376
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001377 case ABIArgInfo::Indirect: {
1378 assert(!RetAI.getIndirectAlign() && "Align unused on indirect return.");
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001379 ResultType = llvm::Type::VoidTy;
Daniel Dunbara9976a22008-09-10 07:00:50 +00001380 const llvm::Type *STy = ConvertType(RetTy);
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001381 ArgTys.push_back(llvm::PointerType::get(STy, RetTy.getAddressSpace()));
1382 break;
1383 }
1384
Daniel Dunbar1358b202009-01-26 21:26:08 +00001385 case ABIArgInfo::Ignore:
1386 ResultType = llvm::Type::VoidTy;
1387 break;
1388
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001389 case ABIArgInfo::Coerce:
Daniel Dunbar73d66602008-09-10 07:04:09 +00001390 ResultType = RetAI.getCoerceToType();
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001391 break;
1392 }
1393
Daniel Dunbare92e0ab2009-02-03 05:31:23 +00001394 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1395 ie = FI.arg_end(); it != ie; ++it) {
1396 const ABIArgInfo &AI = it->info;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001397
1398 switch (AI.getKind()) {
Daniel Dunbar1358b202009-01-26 21:26:08 +00001399 case ABIArgInfo::Ignore:
1400 break;
1401
Daniel Dunbar04d35782008-09-17 00:51:38 +00001402 case ABIArgInfo::Coerce:
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001403 ArgTys.push_back(AI.getCoerceToType());
1404 break;
1405
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001406 case ABIArgInfo::Indirect: {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001407 // indirect arguments are always on the stack, which is addr space #0.
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001408 const llvm::Type *LTy = ConvertTypeForMem(it->type);
1409 ArgTys.push_back(llvm::PointerType::getUnqual(LTy));
Daniel Dunbar22e30052008-09-11 01:48:57 +00001410 break;
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001411 }
Daniel Dunbar22e30052008-09-11 01:48:57 +00001412
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00001413 case ABIArgInfo::Direct:
Daniel Dunbar6f56e452009-02-05 09:16:39 +00001414 ArgTys.push_back(ConvertType(it->type));
Daniel Dunbar22e30052008-09-11 01:48:57 +00001415 break;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001416
1417 case ABIArgInfo::Expand:
Daniel Dunbare92e0ab2009-02-03 05:31:23 +00001418 GetExpandedTypes(it->type, ArgTys);
Daniel Dunbar22e30052008-09-11 01:48:57 +00001419 break;
1420 }
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001421 }
1422
Daniel Dunbar9fc15a82009-02-02 21:43:58 +00001423 return llvm::FunctionType::get(ResultType, ArgTys, IsVariadic);
Daniel Dunbar49f5a0d2008-09-09 23:48:28 +00001424}
1425
Daniel Dunbar0b37ca82009-02-02 23:43:58 +00001426void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001427 const Decl *TargetDecl,
Devang Patela85a9ef2008-09-25 21:02:23 +00001428 AttributeListType &PAL) {
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001429 unsigned FuncAttrs = 0;
Devang Patel2bb6eb82008-09-26 22:53:57 +00001430 unsigned RetAttrs = 0;
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001431
1432 if (TargetDecl) {
1433 if (TargetDecl->getAttr<NoThrowAttr>())
Devang Patela85a9ef2008-09-25 21:02:23 +00001434 FuncAttrs |= llvm::Attribute::NoUnwind;
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001435 if (TargetDecl->getAttr<NoReturnAttr>())
Devang Patela85a9ef2008-09-25 21:02:23 +00001436 FuncAttrs |= llvm::Attribute::NoReturn;
Anders Carlssondd6791c2008-10-05 23:32:53 +00001437 if (TargetDecl->getAttr<PureAttr>())
1438 FuncAttrs |= llvm::Attribute::ReadOnly;
1439 if (TargetDecl->getAttr<ConstAttr>())
1440 FuncAttrs |= llvm::Attribute::ReadNone;
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001441 }
1442
Daniel Dunbar0b37ca82009-02-02 23:43:58 +00001443 QualType RetTy = FI.getReturnType();
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001444 unsigned Index = 1;
Daniel Dunbar77071992009-02-03 05:59:18 +00001445 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbar3ad1f072008-09-10 04:01:49 +00001446 switch (RetAI.getKind()) {
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00001447 case ABIArgInfo::Direct:
Daniel Dunbare126ab12008-09-10 02:41:04 +00001448 if (RetTy->isPromotableIntegerType()) {
1449 if (RetTy->isSignedIntegerType()) {
Devang Patel2bb6eb82008-09-26 22:53:57 +00001450 RetAttrs |= llvm::Attribute::SExt;
Daniel Dunbare126ab12008-09-10 02:41:04 +00001451 } else if (RetTy->isUnsignedIntegerType()) {
Devang Patel2bb6eb82008-09-26 22:53:57 +00001452 RetAttrs |= llvm::Attribute::ZExt;
Daniel Dunbare126ab12008-09-10 02:41:04 +00001453 }
1454 }
1455 break;
1456
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001457 case ABIArgInfo::Indirect:
Devang Patela85a9ef2008-09-25 21:02:23 +00001458 PAL.push_back(llvm::AttributeWithIndex::get(Index,
Daniel Dunbarebbb8f32009-01-31 02:19:00 +00001459 llvm::Attribute::StructRet |
1460 llvm::Attribute::NoAlias));
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001461 ++Index;
Daniel Dunbare126ab12008-09-10 02:41:04 +00001462 break;
1463
Daniel Dunbar1358b202009-01-26 21:26:08 +00001464 case ABIArgInfo::Ignore:
Daniel Dunbare126ab12008-09-10 02:41:04 +00001465 case ABIArgInfo::Coerce:
Daniel Dunbare126ab12008-09-10 02:41:04 +00001466 break;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001467
Daniel Dunbar22e30052008-09-11 01:48:57 +00001468 case ABIArgInfo::Expand:
1469 assert(0 && "Invalid ABI kind for return argument");
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001470 }
Daniel Dunbare126ab12008-09-10 02:41:04 +00001471
Devang Patel2bb6eb82008-09-26 22:53:57 +00001472 if (RetAttrs)
1473 PAL.push_back(llvm::AttributeWithIndex::get(0, RetAttrs));
Daniel Dunbare92e0ab2009-02-03 05:31:23 +00001474 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1475 ie = FI.arg_end(); it != ie; ++it) {
1476 QualType ParamType = it->type;
1477 const ABIArgInfo &AI = it->info;
Devang Patela85a9ef2008-09-25 21:02:23 +00001478 unsigned Attributes = 0;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001479
1480 switch (AI.getKind()) {
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001481 case ABIArgInfo::Coerce:
1482 break;
1483
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001484 case ABIArgInfo::Indirect:
Devang Patela85a9ef2008-09-25 21:02:23 +00001485 Attributes |= llvm::Attribute::ByVal;
Daniel Dunbarb3f651a2009-02-05 01:31:19 +00001486 Attributes |=
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001487 llvm::Attribute::constructAlignmentFromInt(AI.getIndirectAlign());
Daniel Dunbar22e30052008-09-11 01:48:57 +00001488 break;
1489
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00001490 case ABIArgInfo::Direct:
Daniel Dunbar22e30052008-09-11 01:48:57 +00001491 if (ParamType->isPromotableIntegerType()) {
1492 if (ParamType->isSignedIntegerType()) {
Devang Patela85a9ef2008-09-25 21:02:23 +00001493 Attributes |= llvm::Attribute::SExt;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001494 } else if (ParamType->isUnsignedIntegerType()) {
Devang Patela85a9ef2008-09-25 21:02:23 +00001495 Attributes |= llvm::Attribute::ZExt;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001496 }
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001497 }
Daniel Dunbar22e30052008-09-11 01:48:57 +00001498 break;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001499
Daniel Dunbar1358b202009-01-26 21:26:08 +00001500 case ABIArgInfo::Ignore:
1501 // Skip increment, no matching LLVM parameter.
1502 continue;
1503
Daniel Dunbar04d35782008-09-17 00:51:38 +00001504 case ABIArgInfo::Expand: {
1505 std::vector<const llvm::Type*> Tys;
1506 // FIXME: This is rather inefficient. Do we ever actually need
1507 // to do anything here? The result should be just reconstructed
1508 // on the other side, so extension should be a non-issue.
1509 getTypes().GetExpandedTypes(ParamType, Tys);
1510 Index += Tys.size();
1511 continue;
1512 }
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001513 }
Daniel Dunbar22e30052008-09-11 01:48:57 +00001514
Devang Patela85a9ef2008-09-25 21:02:23 +00001515 if (Attributes)
1516 PAL.push_back(llvm::AttributeWithIndex::get(Index, Attributes));
Daniel Dunbar04d35782008-09-17 00:51:38 +00001517 ++Index;
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001518 }
Devang Patel2bb6eb82008-09-26 22:53:57 +00001519 if (FuncAttrs)
1520 PAL.push_back(llvm::AttributeWithIndex::get(~0, FuncAttrs));
Daniel Dunbarbccb0682008-09-10 00:32:18 +00001521}
1522
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001523void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1524 llvm::Function *Fn,
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001525 const FunctionArgList &Args) {
Daniel Dunbar5b7ac652009-02-03 06:02:10 +00001526 // FIXME: We no longer need the types from FunctionArgList; lift up
1527 // and simplify.
1528
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001529 // Emit allocs for param decls. Give the LLVM Argument nodes names.
1530 llvm::Function::arg_iterator AI = Fn->arg_begin();
1531
1532 // Name the struct return argument.
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001533 if (CGM.ReturnTypeUsesSret(FI)) {
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001534 AI->setName("agg.result");
1535 ++AI;
1536 }
Daniel Dunbar77071992009-02-03 05:59:18 +00001537
Daniel Dunbar14c884a2009-02-04 21:17:21 +00001538 assert(FI.arg_size() == Args.size() &&
1539 "Mismatch between function signature & arguments.");
Daniel Dunbar77071992009-02-03 05:59:18 +00001540 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001541 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
Daniel Dunbar77071992009-02-03 05:59:18 +00001542 i != e; ++i, ++info_it) {
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001543 const VarDecl *Arg = i->first;
Daniel Dunbar77071992009-02-03 05:59:18 +00001544 QualType Ty = info_it->type;
1545 const ABIArgInfo &ArgI = info_it->info;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001546
1547 switch (ArgI.getKind()) {
Daniel Dunbar6f56e452009-02-05 09:16:39 +00001548 case ABIArgInfo::Indirect: {
1549 llvm::Value* V = AI;
1550 if (hasAggregateLLVMType(Ty)) {
1551 // Do nothing, aggregates and complex variables are accessed by
1552 // reference.
1553 } else {
1554 // Load scalar value from indirect argument.
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001555 V = EmitLoadOfScalar(V, false, Ty);
Daniel Dunbar6f56e452009-02-05 09:16:39 +00001556 if (!getContext().typesAreCompatible(Ty, Arg->getType())) {
1557 // This must be a promotion, for something like
1558 // "void a(x) short x; {..."
1559 V = EmitScalarConversion(V, Ty, Arg->getType());
1560 }
1561 }
1562 EmitParmDecl(*Arg, V);
1563 break;
1564 }
1565
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00001566 case ABIArgInfo::Direct: {
Daniel Dunbar22e30052008-09-11 01:48:57 +00001567 assert(AI != Fn->arg_end() && "Argument mismatch!");
1568 llvm::Value* V = AI;
Daniel Dunbarcc811502009-02-05 11:13:54 +00001569 if (hasAggregateLLVMType(Ty)) {
1570 // Create a temporary alloca to hold the argument; the rest of
1571 // codegen expects to access aggregates & complex values by
1572 // reference.
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001573 V = CreateTempAlloca(ConvertTypeForMem(Ty));
Daniel Dunbarcc811502009-02-05 11:13:54 +00001574 Builder.CreateStore(AI, V);
1575 } else {
1576 if (!getContext().typesAreCompatible(Ty, Arg->getType())) {
1577 // This must be a promotion, for something like
1578 // "void a(x) short x; {..."
1579 V = EmitScalarConversion(V, Ty, Arg->getType());
1580 }
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001581 }
Daniel Dunbar22e30052008-09-11 01:48:57 +00001582 EmitParmDecl(*Arg, V);
1583 break;
1584 }
Daniel Dunbar04d35782008-09-17 00:51:38 +00001585
1586 case ABIArgInfo::Expand: {
Daniel Dunbar77071992009-02-03 05:59:18 +00001587 // If this structure was expanded into multiple arguments then
Daniel Dunbar04d35782008-09-17 00:51:38 +00001588 // we need to create a temporary and reconstruct it from the
1589 // arguments.
Chris Lattner6c5ec622008-11-24 04:00:27 +00001590 std::string Name = Arg->getNameAsString();
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001591 llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(Ty),
Daniel Dunbar04d35782008-09-17 00:51:38 +00001592 (Name + ".addr").c_str());
1593 // FIXME: What are the right qualifiers here?
1594 llvm::Function::arg_iterator End =
1595 ExpandTypeFromArgs(Ty, LValue::MakeAddr(Temp,0), AI);
1596 EmitParmDecl(*Arg, Temp);
Daniel Dunbar22e30052008-09-11 01:48:57 +00001597
Daniel Dunbar04d35782008-09-17 00:51:38 +00001598 // Name the arguments used in expansion and increment AI.
1599 unsigned Index = 0;
1600 for (; AI != End; ++AI, ++Index)
1601 AI->setName(Name + "." + llvm::utostr(Index));
1602 continue;
1603 }
Daniel Dunbar1358b202009-01-26 21:26:08 +00001604
1605 case ABIArgInfo::Ignore:
Daniel Dunbar94b4fec2009-02-10 00:06:49 +00001606 // Initialize the local variable appropriately.
1607 if (hasAggregateLLVMType(Ty)) {
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001608 EmitParmDecl(*Arg, CreateTempAlloca(ConvertTypeForMem(Ty)));
Daniel Dunbar94b4fec2009-02-10 00:06:49 +00001609 } else {
1610 EmitParmDecl(*Arg, llvm::UndefValue::get(ConvertType(Arg->getType())));
1611 }
1612
Daniel Dunbar015bc8e2009-02-03 20:00:13 +00001613 // Skip increment, no matching LLVM parameter.
1614 continue;
Daniel Dunbar1358b202009-01-26 21:26:08 +00001615
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001616 case ABIArgInfo::Coerce: {
1617 assert(AI != Fn->arg_end() && "Argument mismatch!");
1618 // FIXME: This is very wasteful; EmitParmDecl is just going to
1619 // drop the result in a new alloca anyway, so we could just
1620 // store into that directly if we broke the abstraction down
1621 // more.
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001622 llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(Ty), "coerce");
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001623 CreateCoercedStore(AI, V, *this);
1624 // Match to what EmitParmDecl is expecting for this type.
Daniel Dunbar99473cd2009-02-04 07:22:24 +00001625 if (!CodeGenFunction::hasAggregateLLVMType(Ty)) {
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001626 V = EmitLoadOfScalar(V, false, Ty);
Daniel Dunbar99473cd2009-02-04 07:22:24 +00001627 if (!getContext().typesAreCompatible(Ty, Arg->getType())) {
1628 // This must be a promotion, for something like
1629 // "void a(x) short x; {..."
1630 V = EmitScalarConversion(V, Ty, Arg->getType());
1631 }
1632 }
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001633 EmitParmDecl(*Arg, V);
1634 break;
1635 }
Daniel Dunbar22e30052008-09-11 01:48:57 +00001636 }
Daniel Dunbar04d35782008-09-17 00:51:38 +00001637
1638 ++AI;
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001639 }
1640 assert(AI == Fn->arg_end() && "Argument mismatch!");
1641}
1642
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001643void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001644 llvm::Value *ReturnValue) {
Daniel Dunbare126ab12008-09-10 02:41:04 +00001645 llvm::Value *RV = 0;
1646
1647 // Functions with no result always return void.
1648 if (ReturnValue) {
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001649 QualType RetTy = FI.getReturnType();
Daniel Dunbar77071992009-02-03 05:59:18 +00001650 const ABIArgInfo &RetAI = FI.getReturnInfo();
Daniel Dunbare126ab12008-09-10 02:41:04 +00001651
1652 switch (RetAI.getKind()) {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001653 case ABIArgInfo::Indirect:
Daniel Dunbar17d35372008-12-18 04:52:14 +00001654 if (RetTy->isAnyComplexType()) {
Daniel Dunbar17d35372008-12-18 04:52:14 +00001655 ComplexPairTy RT = LoadComplexFromAddr(ReturnValue, false);
1656 StoreComplexToAddr(RT, CurFn->arg_begin(), false);
1657 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1658 EmitAggregateCopy(CurFn->arg_begin(), ReturnValue, RetTy);
1659 } else {
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001660 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue), CurFn->arg_begin(),
1661 false);
Daniel Dunbar17d35372008-12-18 04:52:14 +00001662 }
Daniel Dunbare126ab12008-09-10 02:41:04 +00001663 break;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001664
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00001665 case ABIArgInfo::Direct:
Daniel Dunbarcc811502009-02-05 11:13:54 +00001666 // The internal return value temp always will have
1667 // pointer-to-return-type type.
Daniel Dunbare126ab12008-09-10 02:41:04 +00001668 RV = Builder.CreateLoad(ReturnValue);
1669 break;
1670
Daniel Dunbar1358b202009-01-26 21:26:08 +00001671 case ABIArgInfo::Ignore:
1672 break;
1673
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001674 case ABIArgInfo::Coerce:
Daniel Dunbar708d8a82009-01-27 01:36:03 +00001675 RV = CreateCoercedLoad(ReturnValue, RetAI.getCoerceToType(), *this);
Daniel Dunbar22e30052008-09-11 01:48:57 +00001676 break;
Daniel Dunbar22e30052008-09-11 01:48:57 +00001677
Daniel Dunbar22e30052008-09-11 01:48:57 +00001678 case ABIArgInfo::Expand:
1679 assert(0 && "Invalid ABI kind for return argument");
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001680 }
1681 }
Daniel Dunbare126ab12008-09-10 02:41:04 +00001682
1683 if (RV) {
1684 Builder.CreateRet(RV);
1685 } else {
1686 Builder.CreateRetVoid();
1687 }
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001688}
1689
Daniel Dunbar6ee022b2009-02-02 22:03:45 +00001690RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
1691 llvm::Value *Callee,
Daniel Dunbar191eb9e2009-02-20 18:06:48 +00001692 const CallArgList &CallArgs,
1693 const Decl *TargetDecl) {
Daniel Dunbar5b7ac652009-02-03 06:02:10 +00001694 // FIXME: We no longer need the types from CallArgs; lift up and
1695 // simplify.
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001696 llvm::SmallVector<llvm::Value*, 16> Args;
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001697
1698 // Handle struct-return functions by passing a pointer to the
1699 // location that we would like to return into.
Daniel Dunbar9fc15a82009-02-02 21:43:58 +00001700 QualType RetTy = CallInfo.getReturnType();
Daniel Dunbar77071992009-02-03 05:59:18 +00001701 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
Daniel Dunbar32cae462009-02-05 09:24:53 +00001702 if (CGM.ReturnTypeUsesSret(CallInfo)) {
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001703 // Create a temporary alloca to hold the result of the call. :(
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001704 Args.push_back(CreateTempAlloca(ConvertTypeForMem(RetTy)));
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001705 }
1706
Daniel Dunbar14c884a2009-02-04 21:17:21 +00001707 assert(CallInfo.arg_size() == CallArgs.size() &&
1708 "Mismatch between function signature & arguments.");
Daniel Dunbar77071992009-02-03 05:59:18 +00001709 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001710 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
Daniel Dunbar77071992009-02-03 05:59:18 +00001711 I != E; ++I, ++info_it) {
1712 const ABIArgInfo &ArgInfo = info_it->info;
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001713 RValue RV = I->first;
Daniel Dunbar04d35782008-09-17 00:51:38 +00001714
1715 switch (ArgInfo.getKind()) {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001716 case ABIArgInfo::Indirect:
Daniel Dunbar6f56e452009-02-05 09:16:39 +00001717 if (RV.isScalar() || RV.isComplex()) {
1718 // Make a temporary alloca to pass the argument.
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001719 Args.push_back(CreateTempAlloca(ConvertTypeForMem(I->second)));
Daniel Dunbar6f56e452009-02-05 09:16:39 +00001720 if (RV.isScalar())
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001721 EmitStoreOfScalar(RV.getScalarVal(), Args.back(), false);
Daniel Dunbar6f56e452009-02-05 09:16:39 +00001722 else
1723 StoreComplexToAddr(RV.getComplexVal(), Args.back(), false);
1724 } else {
1725 Args.push_back(RV.getAggregateAddr());
1726 }
1727 break;
1728
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00001729 case ABIArgInfo::Direct:
Daniel Dunbar04d35782008-09-17 00:51:38 +00001730 if (RV.isScalar()) {
1731 Args.push_back(RV.getScalarVal());
1732 } else if (RV.isComplex()) {
Daniel Dunbarcc811502009-02-05 11:13:54 +00001733 llvm::Value *Tmp = llvm::UndefValue::get(ConvertType(I->second));
1734 Tmp = Builder.CreateInsertValue(Tmp, RV.getComplexVal().first, 0);
1735 Tmp = Builder.CreateInsertValue(Tmp, RV.getComplexVal().second, 1);
1736 Args.push_back(Tmp);
Daniel Dunbar04d35782008-09-17 00:51:38 +00001737 } else {
Daniel Dunbarcc811502009-02-05 11:13:54 +00001738 Args.push_back(Builder.CreateLoad(RV.getAggregateAddr()));
Daniel Dunbar04d35782008-09-17 00:51:38 +00001739 }
1740 break;
1741
Daniel Dunbar1358b202009-01-26 21:26:08 +00001742 case ABIArgInfo::Ignore:
1743 break;
1744
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001745 case ABIArgInfo::Coerce: {
1746 // FIXME: Avoid the conversion through memory if possible.
1747 llvm::Value *SrcPtr;
1748 if (RV.isScalar()) {
Daniel Dunbar4ce351b2009-02-03 23:04:57 +00001749 SrcPtr = CreateTempAlloca(ConvertTypeForMem(I->second), "coerce");
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001750 EmitStoreOfScalar(RV.getScalarVal(), SrcPtr, false);
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001751 } else if (RV.isComplex()) {
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001752 SrcPtr = CreateTempAlloca(ConvertTypeForMem(I->second), "coerce");
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001753 StoreComplexToAddr(RV.getComplexVal(), SrcPtr, false);
1754 } else
1755 SrcPtr = RV.getAggregateAddr();
1756 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
1757 *this));
1758 break;
1759 }
1760
Daniel Dunbar04d35782008-09-17 00:51:38 +00001761 case ABIArgInfo::Expand:
1762 ExpandTypeToArgs(I->second, RV, Args);
1763 break;
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001764 }
1765 }
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001766
Daniel Dunbar0a067402009-02-23 17:26:39 +00001767 llvm::BasicBlock *InvokeDest = getInvokeDest();
Devang Patela85a9ef2008-09-25 21:02:23 +00001768 CodeGen::AttributeListType AttributeList;
Daniel Dunbar191eb9e2009-02-20 18:06:48 +00001769 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList);
Daniel Dunbar0a067402009-02-23 17:26:39 +00001770 llvm::AttrListPtr Attrs = llvm::AttrListPtr::get(AttributeList.begin(),
1771 AttributeList.end());
Daniel Dunbarebbb8f32009-01-31 02:19:00 +00001772
Daniel Dunbar0a067402009-02-23 17:26:39 +00001773 llvm::Instruction *CI;
1774 if (!InvokeDest || Attrs.getFnAttributes() & (llvm::Attribute::NoUnwind ||
1775 llvm::Attribute::NoReturn)) {
1776 llvm::CallInst *CallInstr =
1777 Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
1778 CI = CallInstr;
Daniel Dunbaraf438dc2009-02-20 18:54:31 +00001779
Daniel Dunbar0a067402009-02-23 17:26:39 +00001780 CallInstr->setAttributes(Attrs);
1781 if (const llvm::Function *F = dyn_cast<llvm::Function>(Callee))
1782 CallInstr->setCallingConv(F->getCallingConv());
Daniel Dunbaraf438dc2009-02-20 18:54:31 +00001783
Daniel Dunbar0a067402009-02-23 17:26:39 +00001784 // If the call doesn't return, finish the basic block and clear the
1785 // insertion point; this allows the rest of IRgen to discard
1786 // unreachable code.
1787 if (CallInstr->doesNotReturn()) {
1788 Builder.CreateUnreachable();
1789 Builder.ClearInsertionPoint();
1790
Daniel Dunbar5f5ff8c2009-02-25 20:59:29 +00001791 // FIXME: For now, emit a dummy basic block because expr
1792 // emitters in generally are not ready to handle emitting
1793 // expressions at unreachable points.
1794 EnsureInsertPoint();
1795
Daniel Dunbar0a067402009-02-23 17:26:39 +00001796 // Return a reasonable RValue.
1797 return GetUndefRValue(RetTy);
1798 }
1799 } else {
1800 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
1801 llvm::InvokeInst *InvokeInstr =
1802 Builder.CreateInvoke(Callee, Cont, InvokeDest,
1803 &Args[0], &Args[0]+Args.size());
1804 CI = InvokeInstr;
1805
1806 InvokeInstr->setAttributes(Attrs);
1807 if (const llvm::Function *F = dyn_cast<llvm::Function>(Callee))
1808 InvokeInstr->setCallingConv(F->getCallingConv());
1809
1810 EmitBlock(Cont);
Daniel Dunbaraf438dc2009-02-20 18:54:31 +00001811 }
1812
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001813 if (CI->getType() != llvm::Type::VoidTy)
1814 CI->setName("call");
Daniel Dunbare126ab12008-09-10 02:41:04 +00001815
1816 switch (RetAI.getKind()) {
Daniel Dunbar88dde9b2009-02-05 08:00:50 +00001817 case ABIArgInfo::Indirect:
Daniel Dunbare126ab12008-09-10 02:41:04 +00001818 if (RetTy->isAnyComplexType())
Daniel Dunbar04d35782008-09-17 00:51:38 +00001819 return RValue::getComplex(LoadComplexFromAddr(Args[0], false));
Daniel Dunbar17d35372008-12-18 04:52:14 +00001820 else if (CodeGenFunction::hasAggregateLLVMType(RetTy))
Daniel Dunbar04d35782008-09-17 00:51:38 +00001821 return RValue::getAggregate(Args[0]);
Daniel Dunbar17d35372008-12-18 04:52:14 +00001822 else
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001823 return RValue::get(EmitLoadOfScalar(Args[0], false, RetTy));
Daniel Dunbar22e30052008-09-11 01:48:57 +00001824
Daniel Dunbarb1a60c02009-02-03 06:17:37 +00001825 case ABIArgInfo::Direct:
Daniel Dunbarcc811502009-02-05 11:13:54 +00001826 if (RetTy->isAnyComplexType()) {
1827 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
1828 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
1829 return RValue::getComplex(std::make_pair(Real, Imag));
1830 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001831 llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(RetTy), "agg.tmp");
Daniel Dunbarcc811502009-02-05 11:13:54 +00001832 Builder.CreateStore(CI, V);
1833 return RValue::getAggregate(V);
1834 } else
1835 return RValue::get(CI);
Daniel Dunbare126ab12008-09-10 02:41:04 +00001836
Daniel Dunbar1358b202009-01-26 21:26:08 +00001837 case ABIArgInfo::Ignore:
Daniel Dunbareec02622009-02-03 06:30:17 +00001838 // If we are ignoring an argument that had a result, make sure to
1839 // construct the appropriate return value for our caller.
Daniel Dunbar900c85a2009-02-05 07:09:07 +00001840 return GetUndefRValue(RetTy);
Daniel Dunbar1358b202009-01-26 21:26:08 +00001841
Daniel Dunbar73d66602008-09-10 07:04:09 +00001842 case ABIArgInfo::Coerce: {
Daniel Dunbar33fa5812009-02-03 19:12:28 +00001843 // FIXME: Avoid the conversion through memory if possible.
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001844 llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(RetTy), "coerce");
Daniel Dunbar708d8a82009-01-27 01:36:03 +00001845 CreateCoercedStore(CI, V, *this);
Anders Carlssonfccf7472008-11-25 22:21:48 +00001846 if (RetTy->isAnyComplexType())
1847 return RValue::getComplex(LoadComplexFromAddr(V, false));
Daniel Dunbar1358b202009-01-26 21:26:08 +00001848 else if (CodeGenFunction::hasAggregateLLVMType(RetTy))
Anders Carlssonfccf7472008-11-25 22:21:48 +00001849 return RValue::getAggregate(V);
Daniel Dunbar1358b202009-01-26 21:26:08 +00001850 else
Daniel Dunbar8559b5d2009-02-10 01:51:39 +00001851 return RValue::get(EmitLoadOfScalar(V, false, RetTy));
Daniel Dunbar73d66602008-09-10 07:04:09 +00001852 }
Daniel Dunbar22e30052008-09-11 01:48:57 +00001853
Daniel Dunbar22e30052008-09-11 01:48:57 +00001854 case ABIArgInfo::Expand:
1855 assert(0 && "Invalid ABI kind for return argument");
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001856 }
Daniel Dunbare126ab12008-09-10 02:41:04 +00001857
1858 assert(0 && "Unhandled ABIArgInfo::Kind");
1859 return RValue::get(0);
Daniel Dunbarfc1a9c42008-09-09 23:27:19 +00001860}
Daniel Dunbar7fbcf9c2009-02-10 20:44:09 +00001861
1862/* VarArg handling */
1863
1864llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
1865 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
1866}