1 //===----- CGCall.h - Encapsulate calling convention details ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // These classes wrap the information about a call or function
11 // definition used to handle ABI compliancy.
13 //===----------------------------------------------------------------------===//
16 #include "CodeGenFunction.h"
17 #include "CodeGenModule.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Attributes.h"
26 #include "llvm/Support/CallSite.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Target/TargetData.h"
32 using namespace clang;
33 using namespace CodeGen;
37 // FIXME: Use iterator and sidestep silly type array creation.
40 CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionNoProtoType *FTNP) {
41 return getFunctionInfo(FTNP->getResultType(),
42 llvm::SmallVector<QualType, 16>());
46 CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionProtoType *FTP) {
47 llvm::SmallVector<QualType, 16> ArgTys;
49 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
50 ArgTys.push_back(FTP->getArgType(i));
51 return getFunctionInfo(FTP->getResultType(), ArgTys);
54 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXMethodDecl *MD) {
55 llvm::SmallVector<QualType, 16> ArgTys;
56 // Add the 'this' pointer unless this is a static method.
58 ArgTys.push_back(MD->getThisType(Context));
60 const FunctionProtoType *FTP = MD->getType()->getAsFunctionProtoType();
61 for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
62 ArgTys.push_back(FTP->getArgType(i));
63 return getFunctionInfo(FTP->getResultType(), ArgTys);
66 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionDecl *FD) {
67 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
69 return getFunctionInfo(MD);
71 const FunctionType *FTy = FD->getType()->getAsFunctionType();
72 if (const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FTy))
73 return getFunctionInfo(FTP);
74 return getFunctionInfo(cast<FunctionNoProtoType>(FTy));
77 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const ObjCMethodDecl *MD) {
78 llvm::SmallVector<QualType, 16> ArgTys;
79 ArgTys.push_back(MD->getSelfDecl()->getType());
80 ArgTys.push_back(Context.getObjCSelType());
82 for (ObjCMethodDecl::param_iterator i = MD->param_begin(),
83 e = MD->param_end(); i != e; ++i)
84 ArgTys.push_back((*i)->getType());
85 return getFunctionInfo(MD->getResultType(), ArgTys);
88 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
89 const CallArgList &Args) {
91 llvm::SmallVector<QualType, 16> ArgTys;
92 for (CallArgList::const_iterator i = Args.begin(), e = Args.end();
94 ArgTys.push_back(i->second);
95 return getFunctionInfo(ResTy, ArgTys);
98 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
99 const FunctionArgList &Args) {
101 llvm::SmallVector<QualType, 16> ArgTys;
102 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
104 ArgTys.push_back(i->second);
105 return getFunctionInfo(ResTy, ArgTys);
108 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
109 const llvm::SmallVector<QualType, 16> &ArgTys) {
110 // Lookup or create unique function info.
111 llvm::FoldingSetNodeID ID;
112 CGFunctionInfo::Profile(ID, ResTy, ArgTys.begin(), ArgTys.end());
115 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, InsertPos);
119 // Construct the function info.
120 FI = new CGFunctionInfo(ResTy, ArgTys);
121 FunctionInfos.InsertNode(FI, InsertPos);
123 // Compute ABI information.
124 getABIInfo().computeInfo(*FI, getContext());
131 ABIInfo::~ABIInfo() {}
133 void ABIArgInfo::dump() const {
134 fprintf(stderr, "(ABIArgInfo Kind=");
137 fprintf(stderr, "Direct");
140 fprintf(stderr, "Ignore");
143 fprintf(stderr, "Coerce Type=");
144 getCoerceToType()->print(llvm::errs());
147 fprintf(stderr, "Indirect Align=%d", getIndirectAlign());
150 fprintf(stderr, "Expand");
153 fprintf(stderr, ")\n");
158 static bool isEmptyRecord(ASTContext &Context, QualType T);
160 /// isEmptyField - Return true iff a the field is "empty", that is it
161 /// is an unnamed bit-field or an (array of) empty record(s).
162 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD) {
163 if (FD->isUnnamedBitfield())
166 QualType FT = FD->getType();
167 // Constant arrays of empty records count as empty, strip them off.
168 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT))
169 FT = AT->getElementType();
171 return isEmptyRecord(Context, FT);
174 /// isEmptyRecord - Return true iff a structure contains only empty
175 /// fields. Note that a structure with a flexible array member is not
176 /// considered empty.
177 static bool isEmptyRecord(ASTContext &Context, QualType T) {
178 const RecordType *RT = T->getAsRecordType();
181 const RecordDecl *RD = RT->getDecl();
182 if (RD->hasFlexibleArrayMember())
184 for (RecordDecl::field_iterator i = RD->field_begin(Context),
185 e = RD->field_end(Context); i != e; ++i)
186 if (!isEmptyField(Context, *i))
191 /// isSingleElementStruct - Determine if a structure is a "single
192 /// element struct", i.e. it has exactly one non-empty field or
193 /// exactly one field which is itself a single element
194 /// struct. Structures with flexible array members are never
195 /// considered single element structs.
197 /// \return The field declaration for the single non-empty field, if
199 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
200 const RecordType *RT = T->getAsStructureType();
204 const RecordDecl *RD = RT->getDecl();
205 if (RD->hasFlexibleArrayMember())
208 const Type *Found = 0;
209 for (RecordDecl::field_iterator i = RD->field_begin(Context),
210 e = RD->field_end(Context); i != e; ++i) {
211 const FieldDecl *FD = *i;
212 QualType FT = FD->getType();
214 // Ignore empty fields.
215 if (isEmptyField(Context, FD))
218 // If we already found an element then this isn't a single-element
223 // Treat single element arrays as the element.
224 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
225 if (AT->getSize().getZExtValue() != 1)
227 FT = AT->getElementType();
230 if (!CodeGenFunction::hasAggregateLLVMType(FT)) {
231 Found = FT.getTypePtr();
233 Found = isSingleElementStruct(FT, Context);
242 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
243 if (!Ty->getAsBuiltinType() && !Ty->isPointerType())
246 uint64_t Size = Context.getTypeSize(Ty);
247 return Size == 32 || Size == 64;
250 static bool areAllFields32Or64BitBasicType(const RecordDecl *RD,
251 ASTContext &Context) {
252 for (RecordDecl::field_iterator i = RD->field_begin(Context),
253 e = RD->field_end(Context); i != e; ++i) {
254 const FieldDecl *FD = *i;
256 if (!is32Or64BitBasicType(FD->getType(), Context))
259 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
260 // how to expand them yet, and the predicate for telling if a bitfield still
261 // counts as "basic" is more complicated than what we were doing previously.
262 if (FD->isBitField())
270 /// DefaultABIInfo - The default implementation for ABI specific
271 /// details. This implementation provides information which results in
272 /// self-consistent and sensible LLVM IR generation, but does not
273 /// conform to any particular ABI.
274 class DefaultABIInfo : public ABIInfo {
275 ABIArgInfo classifyReturnType(QualType RetTy,
276 ASTContext &Context) const;
278 ABIArgInfo classifyArgumentType(QualType RetTy,
279 ASTContext &Context) const;
281 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
282 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
283 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
285 it->info = classifyArgumentType(it->type, Context);
288 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
289 CodeGenFunction &CGF) const;
292 /// X86_32ABIInfo - The X86-32 ABI information.
293 class X86_32ABIInfo : public ABIInfo {
297 static bool isRegisterSize(unsigned Size) {
298 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
301 static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context);
304 ABIArgInfo classifyReturnType(QualType RetTy,
305 ASTContext &Context) const;
307 ABIArgInfo classifyArgumentType(QualType RetTy,
308 ASTContext &Context) const;
310 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
311 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
312 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
314 it->info = classifyArgumentType(it->type, Context);
317 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
318 CodeGenFunction &CGF) const;
320 X86_32ABIInfo(ASTContext &Context, bool d)
321 : ABIInfo(), Context(Context), IsDarwin(d) {}
326 /// shouldReturnTypeInRegister - Determine if the given type should be
327 /// passed in a register (for the Darwin ABI).
328 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
329 ASTContext &Context) {
330 uint64_t Size = Context.getTypeSize(Ty);
332 // Type must be register sized.
333 if (!isRegisterSize(Size))
336 if (Ty->isVectorType()) {
337 // 64- and 128- bit vectors inside structures are not returned in
339 if (Size == 64 || Size == 128)
345 // If this is a builtin, pointer, or complex type, it is ok.
346 if (Ty->getAsBuiltinType() || Ty->isPointerType() || Ty->isAnyComplexType())
349 // Arrays are treated like records.
350 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
351 return shouldReturnTypeInRegister(AT->getElementType(), Context);
353 // Otherwise, it must be a record type.
354 const RecordType *RT = Ty->getAsRecordType();
355 if (!RT) return false;
357 // Structure types are passed in register if all fields would be
358 // passed in a register.
359 for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(Context),
360 e = RT->getDecl()->field_end(Context); i != e; ++i) {
361 const FieldDecl *FD = *i;
363 // Empty fields are ignored.
364 if (isEmptyField(Context, FD))
367 // Check fields recursively.
368 if (!shouldReturnTypeInRegister(FD->getType(), Context))
375 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
376 ASTContext &Context) const {
377 if (RetTy->isVoidType()) {
378 return ABIArgInfo::getIgnore();
379 } else if (const VectorType *VT = RetTy->getAsVectorType()) {
380 // On Darwin, some vectors are returned in registers.
382 uint64_t Size = Context.getTypeSize(RetTy);
384 // 128-bit vectors are a special case; they are returned in
385 // registers and we need to make sure to pick a type the LLVM
386 // backend will like.
388 return ABIArgInfo::getCoerce(llvm::VectorType::get(llvm::Type::Int64Ty,
391 // Always return in register if it fits in a general purpose
392 // register, or if it is 64 bits and has a single element.
393 if ((Size == 8 || Size == 16 || Size == 32) ||
394 (Size == 64 && VT->getNumElements() == 1))
395 return ABIArgInfo::getCoerce(llvm::IntegerType::get(Size));
397 return ABIArgInfo::getIndirect(0);
400 return ABIArgInfo::getDirect();
401 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
402 // Structures with flexible arrays are always indirect.
403 if (const RecordType *RT = RetTy->getAsStructureType())
404 if (RT->getDecl()->hasFlexibleArrayMember())
405 return ABIArgInfo::getIndirect(0);
407 // Outside of Darwin, structs and unions are always indirect.
408 if (!IsDarwin && !RetTy->isAnyComplexType())
409 return ABIArgInfo::getIndirect(0);
411 // Classify "single element" structs as their element type.
412 if (const Type *SeltTy = isSingleElementStruct(RetTy, Context)) {
413 if (const BuiltinType *BT = SeltTy->getAsBuiltinType()) {
414 if (BT->isIntegerType()) {
415 // We need to use the size of the structure, padding
416 // bit-fields can adjust that to be larger than the single
418 uint64_t Size = Context.getTypeSize(RetTy);
419 return ABIArgInfo::getCoerce(llvm::IntegerType::get((unsigned) Size));
420 } else if (BT->getKind() == BuiltinType::Float) {
421 assert(Context.getTypeSize(RetTy) == Context.getTypeSize(SeltTy) &&
422 "Unexpect single element structure size!");
423 return ABIArgInfo::getCoerce(llvm::Type::FloatTy);
424 } else if (BT->getKind() == BuiltinType::Double) {
425 assert(Context.getTypeSize(RetTy) == Context.getTypeSize(SeltTy) &&
426 "Unexpect single element structure size!");
427 return ABIArgInfo::getCoerce(llvm::Type::DoubleTy);
429 } else if (SeltTy->isPointerType()) {
430 // FIXME: It would be really nice if this could come out as the proper
433 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
434 return ABIArgInfo::getCoerce(PtrTy);
435 } else if (SeltTy->isVectorType()) {
436 // 64- and 128-bit vectors are never returned in a
437 // register when inside a structure.
438 uint64_t Size = Context.getTypeSize(RetTy);
439 if (Size == 64 || Size == 128)
440 return ABIArgInfo::getIndirect(0);
442 return classifyReturnType(QualType(SeltTy, 0), Context);
446 // Small structures which are register sized are generally returned
448 if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, Context)) {
449 uint64_t Size = Context.getTypeSize(RetTy);
450 return ABIArgInfo::getCoerce(llvm::IntegerType::get(Size));
453 return ABIArgInfo::getIndirect(0);
455 return ABIArgInfo::getDirect();
459 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
460 ASTContext &Context) const {
461 // FIXME: Set alignment on indirect arguments.
462 if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
463 // Structures with flexible arrays are always indirect.
464 if (const RecordType *RT = Ty->getAsStructureType())
465 if (RT->getDecl()->hasFlexibleArrayMember())
466 return ABIArgInfo::getIndirect(0);
468 // Ignore empty structs.
469 uint64_t Size = Context.getTypeSize(Ty);
470 if (Ty->isStructureType() && Size == 0)
471 return ABIArgInfo::getIgnore();
473 // Expand structs with size <= 128-bits which consist only of
474 // basic types (int, long long, float, double, xxx*). This is
475 // non-recursive and does not ignore empty fields.
476 if (const RecordType *RT = Ty->getAsStructureType()) {
477 if (Context.getTypeSize(Ty) <= 4*32 &&
478 areAllFields32Or64BitBasicType(RT->getDecl(), Context))
479 return ABIArgInfo::getExpand();
482 return ABIArgInfo::getIndirect(0);
484 return ABIArgInfo::getDirect();
488 llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
489 CodeGenFunction &CGF) const {
490 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
491 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
493 CGBuilderTy &Builder = CGF.Builder;
494 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
496 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
498 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
499 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
502 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
503 llvm::Value *NextAddr =
504 Builder.CreateGEP(Addr,
505 llvm::ConstantInt::get(llvm::Type::Int32Ty, Offset),
507 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
513 /// X86_64ABIInfo - The X86_64 ABI information.
514 class X86_64ABIInfo : public ABIInfo {
526 /// merge - Implement the X86_64 ABI merging algorithm.
528 /// Merge an accumulating classification \arg Accum with a field
529 /// classification \arg Field.
531 /// \param Accum - The accumulating classification. This should
532 /// always be either NoClass or the result of a previous merge
533 /// call. In addition, this should never be Memory (the caller
534 /// should just return Memory for the aggregate).
535 Class merge(Class Accum, Class Field) const;
537 /// classify - Determine the x86_64 register classes in which the
538 /// given type T should be passed.
540 /// \param Lo - The classification for the parts of the type
541 /// residing in the low word of the containing object.
543 /// \param Hi - The classification for the parts of the type
544 /// residing in the high word of the containing object.
546 /// \param OffsetBase - The bit offset of this type in the
547 /// containing object. Some parameters are classified different
548 /// depending on whether they straddle an eightbyte boundary.
550 /// If a word is unused its result will be NoClass; if a type should
551 /// be passed in Memory then at least the classification of \arg Lo
554 /// The \arg Lo class will be NoClass iff the argument is ignored.
556 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
557 /// also be ComplexX87.
558 void classify(QualType T, ASTContext &Context, uint64_t OffsetBase,
559 Class &Lo, Class &Hi) const;
561 /// getCoerceResult - Given a source type \arg Ty and an LLVM type
562 /// to coerce to, chose the best way to pass Ty in the same place
563 /// that \arg CoerceTo would be passed, but while keeping the
564 /// emitted code as simple as possible.
566 /// FIXME: Note, this should be cleaned up to just take an enumeration of all
567 /// the ways we might want to pass things, instead of constructing an LLVM
568 /// type. This makes this code more explicit, and it makes it clearer that we
569 /// are also doing this for correctness in the case of passing scalar types.
570 ABIArgInfo getCoerceResult(QualType Ty,
571 const llvm::Type *CoerceTo,
572 ASTContext &Context) const;
574 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
575 /// such that the argument will be passed in memory.
576 ABIArgInfo getIndirectResult(QualType Ty,
577 ASTContext &Context) const;
579 ABIArgInfo classifyReturnType(QualType RetTy,
580 ASTContext &Context) const;
582 ABIArgInfo classifyArgumentType(QualType Ty,
585 unsigned &neededSSE) const;
588 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const;
590 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
591 CodeGenFunction &CGF) const;
595 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum,
597 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
598 // classified recursively so that always two fields are
599 // considered. The resulting class is calculated according to
600 // the classes of the fields in the eightbyte:
602 // (a) If both classes are equal, this is the resulting class.
604 // (b) If one of the classes is NO_CLASS, the resulting class is
607 // (c) If one of the classes is MEMORY, the result is the MEMORY
610 // (d) If one of the classes is INTEGER, the result is the
613 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
614 // MEMORY is used as class.
616 // (f) Otherwise class SSE is used.
618 // Accum should never be memory (we should have returned) or
619 // ComplexX87 (because this cannot be passed in a structure).
620 assert((Accum != Memory && Accum != ComplexX87) &&
621 "Invalid accumulated classification during merge.");
622 if (Accum == Field || Field == NoClass)
624 else if (Field == Memory)
626 else if (Accum == NoClass)
628 else if (Accum == Integer || Field == Integer)
630 else if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
631 Accum == X87 || Accum == X87Up)
637 void X86_64ABIInfo::classify(QualType Ty,
640 Class &Lo, Class &Hi) const {
641 // FIXME: This code can be simplified by introducing a simple value class for
642 // Class pairs with appropriate constructor methods for the various
645 // FIXME: Some of the split computations are wrong; unaligned vectors
646 // shouldn't be passed in registers for example, so there is no chance they
647 // can straddle an eightbyte. Verify & simplify.
651 Class &Current = OffsetBase < 64 ? Lo : Hi;
654 if (const BuiltinType *BT = Ty->getAsBuiltinType()) {
655 BuiltinType::Kind k = BT->getKind();
657 if (k == BuiltinType::Void) {
659 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
662 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
664 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
666 } else if (k == BuiltinType::LongDouble) {
670 // FIXME: _Decimal32 and _Decimal64 are SSE.
671 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
672 } else if (const EnumType *ET = Ty->getAsEnumType()) {
673 // Classify the underlying integer type.
674 classify(ET->getDecl()->getIntegerType(), Context, OffsetBase, Lo, Hi);
675 } else if (Ty->hasPointerRepresentation()) {
677 } else if (const VectorType *VT = Ty->getAsVectorType()) {
678 uint64_t Size = Context.getTypeSize(VT);
680 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
681 // float> as integer.
684 // If this type crosses an eightbyte boundary, it should be
686 uint64_t EB_Real = (OffsetBase) / 64;
687 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
688 if (EB_Real != EB_Imag)
690 } else if (Size == 64) {
691 // gcc passes <1 x double> in memory. :(
692 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
695 // gcc passes <1 x long long> as INTEGER.
696 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong))
701 // If this type crosses an eightbyte boundary, it should be
703 if (OffsetBase && OffsetBase != 64)
705 } else if (Size == 128) {
709 } else if (const ComplexType *CT = Ty->getAsComplexType()) {
710 QualType ET = Context.getCanonicalType(CT->getElementType());
712 uint64_t Size = Context.getTypeSize(Ty);
713 if (ET->isIntegralType()) {
716 else if (Size <= 128)
718 } else if (ET == Context.FloatTy)
720 else if (ET == Context.DoubleTy)
722 else if (ET == Context.LongDoubleTy)
723 Current = ComplexX87;
725 // If this complex type crosses an eightbyte boundary then it
727 uint64_t EB_Real = (OffsetBase) / 64;
728 uint64_t EB_Imag = (OffsetBase + Context.getTypeSize(ET)) / 64;
729 if (Hi == NoClass && EB_Real != EB_Imag)
731 } else if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
732 // Arrays are treated like structures.
734 uint64_t Size = Context.getTypeSize(Ty);
736 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
737 // than two eightbytes, ..., it has class MEMORY.
741 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
742 // fields, it has class MEMORY.
744 // Only need to check alignment of array base.
745 if (OffsetBase % Context.getTypeAlign(AT->getElementType()))
748 // Otherwise implement simplified merge. We could be smarter about
749 // this, but it isn't worth it and would be harder to verify.
751 uint64_t EltSize = Context.getTypeSize(AT->getElementType());
752 uint64_t ArraySize = AT->getSize().getZExtValue();
753 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
754 Class FieldLo, FieldHi;
755 classify(AT->getElementType(), Context, Offset, FieldLo, FieldHi);
756 Lo = merge(Lo, FieldLo);
757 Hi = merge(Hi, FieldHi);
758 if (Lo == Memory || Hi == Memory)
762 // Do post merger cleanup (see below). Only case we worry about is Memory.
765 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
766 } else if (const RecordType *RT = Ty->getAsRecordType()) {
767 uint64_t Size = Context.getTypeSize(Ty);
769 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
770 // than two eightbytes, ..., it has class MEMORY.
774 const RecordDecl *RD = RT->getDecl();
776 // Assume variable sized types are passed in memory.
777 if (RD->hasFlexibleArrayMember())
780 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
782 // Reset Lo class, this will be recomputed.
785 for (RecordDecl::field_iterator i = RD->field_begin(Context),
786 e = RD->field_end(Context); i != e; ++i, ++idx) {
787 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
788 bool BitField = i->isBitField();
790 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
791 // fields, it has class MEMORY.
793 // Note, skip this test for bit-fields, see below.
794 if (!BitField && Offset % Context.getTypeAlign(i->getType())) {
799 // Classify this field.
801 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
802 // exceeds a single eightbyte, each is classified
803 // separately. Each eightbyte gets initialized to class
805 Class FieldLo, FieldHi;
807 // Bit-fields require special handling, they do not force the
808 // structure to be passed in memory even if unaligned, and
809 // therefore they can straddle an eightbyte.
811 // Ignore padding bit-fields.
812 if (i->isUnnamedBitfield())
815 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
816 uint64_t Size = i->getBitWidth()->EvaluateAsInt(Context).getZExtValue();
818 uint64_t EB_Lo = Offset / 64;
819 uint64_t EB_Hi = (Offset + Size - 1) / 64;
820 FieldLo = FieldHi = NoClass;
822 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
827 FieldHi = EB_Hi ? Integer : NoClass;
830 classify(i->getType(), Context, Offset, FieldLo, FieldHi);
831 Lo = merge(Lo, FieldLo);
832 Hi = merge(Hi, FieldHi);
833 if (Lo == Memory || Hi == Memory)
837 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
839 // (a) If one of the classes is MEMORY, the whole argument is
842 // (b) If SSEUP is not preceeded by SSE, it is converted to SSE.
844 // The first of these conditions is guaranteed by how we implement
845 // the merge (just bail).
847 // The second condition occurs in the case of unions; for example
848 // union { _Complex double; unsigned; }.
851 if (Hi == SSEUp && Lo != SSE)
856 ABIArgInfo X86_64ABIInfo::getCoerceResult(QualType Ty,
857 const llvm::Type *CoerceTo,
858 ASTContext &Context) const {
859 if (CoerceTo == llvm::Type::Int64Ty) {
860 // Integer and pointer types will end up in a general purpose
862 if (Ty->isIntegralType() || Ty->isPointerType())
863 return ABIArgInfo::getDirect();
865 } else if (CoerceTo == llvm::Type::DoubleTy) {
866 // FIXME: It would probably be better to make CGFunctionInfo only map using
867 // canonical types than to canonize here.
868 QualType CTy = Context.getCanonicalType(Ty);
870 // Float and double end up in a single SSE reg.
871 if (CTy == Context.FloatTy || CTy == Context.DoubleTy)
872 return ABIArgInfo::getDirect();
876 return ABIArgInfo::getCoerce(CoerceTo);
879 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
880 ASTContext &Context) const {
881 // If this is a scalar LLVM value then assume LLVM will pass it in the right
883 if (!CodeGenFunction::hasAggregateLLVMType(Ty))
884 return ABIArgInfo::getDirect();
886 // FIXME: Set alignment correctly.
887 return ABIArgInfo::getIndirect(0);
890 ABIArgInfo X86_64ABIInfo::classifyReturnType(QualType RetTy,
891 ASTContext &Context) const {
892 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
893 // classification algorithm.
894 X86_64ABIInfo::Class Lo, Hi;
895 classify(RetTy, Context, 0, Lo, Hi);
897 // Check some invariants.
898 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
899 assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification.");
900 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
902 const llvm::Type *ResType = 0;
905 return ABIArgInfo::getIgnore();
909 assert(0 && "Invalid classification for lo word.");
911 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
914 return getIndirectResult(RetTy, Context);
916 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
917 // available register of the sequence %rax, %rdx is used.
919 ResType = llvm::Type::Int64Ty; break;
921 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
922 // available SSE register of the sequence %xmm0, %xmm1 is used.
924 ResType = llvm::Type::DoubleTy; break;
926 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
927 // returned on the X87 stack in %st0 as 80-bit x87 number.
929 ResType = llvm::Type::X86_FP80Ty; break;
931 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
932 // part of the value is returned in %st0 and the imaginary part in
935 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
936 ResType = llvm::StructType::get(llvm::Type::X86_FP80Ty,
937 llvm::Type::X86_FP80Ty,
943 // Memory was handled previously and X87 should
944 // never occur as a hi class.
947 assert(0 && "Invalid classification for hi word.");
949 case ComplexX87: // Previously handled.
953 ResType = llvm::StructType::get(ResType, llvm::Type::Int64Ty, NULL);
956 ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL);
959 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
960 // is passed in the upper half of the last used SSE register.
962 // SSEUP should always be preceeded by SSE, just widen.
964 assert(Lo == SSE && "Unexpected SSEUp classification.");
965 ResType = llvm::VectorType::get(llvm::Type::DoubleTy, 2);
968 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
969 // returned together with the previous X87 value in %st0.
971 // If X87Up is preceeded by X87, we don't need to do
972 // anything. However, in some cases with unions it may not be
973 // preceeded by X87. In such situations we follow gcc and pass the
974 // extra bits in an SSE reg.
976 ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL);
980 return getCoerceResult(RetTy, ResType, Context);
983 ABIArgInfo X86_64ABIInfo::classifyArgumentType(QualType Ty, ASTContext &Context,
985 unsigned &neededSSE) const {
986 X86_64ABIInfo::Class Lo, Hi;
987 classify(Ty, Context, 0, Lo, Hi);
989 // Check some invariants.
990 // FIXME: Enforce these by construction.
991 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
992 assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification.");
993 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
997 const llvm::Type *ResType = 0;
1000 return ABIArgInfo::getIgnore();
1002 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
1006 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
1007 // COMPLEX_X87, it is passed in memory.
1010 return getIndirectResult(Ty, Context);
1014 assert(0 && "Invalid classification for lo word.");
1016 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
1017 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
1021 ResType = llvm::Type::Int64Ty;
1024 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
1025 // available SSE register is used, the registers are taken in the
1026 // order from %xmm0 to %xmm7.
1029 ResType = llvm::Type::DoubleTy;
1034 // Memory was handled previously, ComplexX87 and X87 should
1035 // never occur as hi classes, and X87Up must be preceed by X87,
1036 // which is passed in memory.
1040 assert(0 && "Invalid classification for hi word.");
1043 case NoClass: break;
1045 ResType = llvm::StructType::get(ResType, llvm::Type::Int64Ty, NULL);
1049 // X87Up generally doesn't occur here (long double is passed in
1050 // memory), except in situations involving unions.
1053 ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL);
1057 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
1058 // eightbyte is passed in the upper half of the last used SSE
1061 assert(Lo == SSE && "Unexpected SSEUp classification.");
1062 ResType = llvm::VectorType::get(llvm::Type::DoubleTy, 2);
1066 return getCoerceResult(Ty, ResType, Context);
1069 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
1070 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
1072 // Keep track of the number of assigned registers.
1073 unsigned freeIntRegs = 6, freeSSERegs = 8;
1075 // If the return value is indirect, then the hidden argument is consuming one
1076 // integer register.
1077 if (FI.getReturnInfo().isIndirect())
1080 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
1081 // get assigned (in left-to-right order) for passing as follows...
1082 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1084 unsigned neededInt, neededSSE;
1085 it->info = classifyArgumentType(it->type, Context, neededInt, neededSSE);
1087 // AMD64-ABI 3.2.3p3: If there are no registers available for any
1088 // eightbyte of an argument, the whole argument is passed on the
1089 // stack. If registers have already been assigned for some
1090 // eightbytes of such an argument, the assignments get reverted.
1091 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
1092 freeIntRegs -= neededInt;
1093 freeSSERegs -= neededSSE;
1095 it->info = getIndirectResult(it->type, Context);
1100 static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
1102 CodeGenFunction &CGF) {
1103 llvm::Value *overflow_arg_area_p =
1104 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
1105 llvm::Value *overflow_arg_area =
1106 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
1108 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
1109 // byte boundary if alignment needed by type exceeds 8 byte boundary.
1110 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
1112 // Note that we follow the ABI & gcc here, even though the type
1113 // could in theory have an alignment greater than 16. This case
1114 // shouldn't ever matter in practice.
1116 // overflow_arg_area = (overflow_arg_area + 15) & ~15;
1117 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty, 15);
1118 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
1119 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
1120 llvm::Type::Int64Ty);
1121 llvm::Value *Mask = llvm::ConstantInt::get(llvm::Type::Int64Ty, ~15LL);
1123 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1124 overflow_arg_area->getType(),
1125 "overflow_arg_area.align");
1128 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
1129 const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1131 CGF.Builder.CreateBitCast(overflow_arg_area,
1132 llvm::PointerType::getUnqual(LTy));
1134 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
1135 // l->overflow_arg_area + sizeof(type).
1136 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
1137 // an 8 byte boundary.
1139 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
1140 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty,
1141 (SizeInBytes + 7) & ~7);
1142 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
1143 "overflow_arg_area.next");
1144 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
1146 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
1150 llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1151 CodeGenFunction &CGF) const {
1152 // Assume that va_list type is correct; should be pointer to LLVM type:
1156 // i8* overflow_arg_area;
1157 // i8* reg_save_area;
1159 unsigned neededInt, neededSSE;
1160 ABIArgInfo AI = classifyArgumentType(Ty, CGF.getContext(),
1161 neededInt, neededSSE);
1163 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
1164 // in the registers. If not go to step 7.
1165 if (!neededInt && !neededSSE)
1166 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1168 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
1169 // general purpose registers needed to pass type and num_fp to hold
1170 // the number of floating point registers needed.
1172 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
1173 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
1174 // l->fp_offset > 304 - num_fp * 16 go to step 7.
1176 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
1177 // register save space).
1179 llvm::Value *InRegs = 0;
1180 llvm::Value *gp_offset_p = 0, *gp_offset = 0;
1181 llvm::Value *fp_offset_p = 0, *fp_offset = 0;
1183 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
1184 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
1186 CGF.Builder.CreateICmpULE(gp_offset,
1187 llvm::ConstantInt::get(llvm::Type::Int32Ty,
1188 48 - neededInt * 8),
1193 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
1194 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
1195 llvm::Value *FitsInFP =
1196 CGF.Builder.CreateICmpULE(fp_offset,
1197 llvm::ConstantInt::get(llvm::Type::Int32Ty,
1198 176 - neededSSE * 16),
1200 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
1203 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
1204 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
1205 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
1206 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
1208 // Emit code to load the value if it was passed in registers.
1210 CGF.EmitBlock(InRegBlock);
1212 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
1213 // an offset of l->gp_offset and/or l->fp_offset. This may require
1214 // copying to a temporary location in case the parameter is passed
1215 // in different register classes or requires an alignment greater
1216 // than 8 for general purpose registers and 16 for XMM registers.
1218 // FIXME: This really results in shameful code when we end up needing to
1219 // collect arguments from different places; often what should result in a
1220 // simple assembling of a structure from scattered addresses has many more
1221 // loads than necessary. Can we clean this up?
1222 const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1223 llvm::Value *RegAddr =
1224 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
1226 if (neededInt && neededSSE) {
1228 assert(AI.isCoerce() && "Unexpected ABI info for mixed regs");
1229 const llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
1230 llvm::Value *Tmp = CGF.CreateTempAlloca(ST);
1231 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
1232 const llvm::Type *TyLo = ST->getElementType(0);
1233 const llvm::Type *TyHi = ST->getElementType(1);
1234 assert((TyLo->isFloatingPoint() ^ TyHi->isFloatingPoint()) &&
1235 "Unexpected ABI info for mixed regs");
1236 const llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
1237 const llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
1238 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1239 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1240 llvm::Value *RegLoAddr = TyLo->isFloatingPoint() ? FPAddr : GPAddr;
1241 llvm::Value *RegHiAddr = TyLo->isFloatingPoint() ? GPAddr : FPAddr;
1243 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
1244 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1245 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
1246 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1248 RegAddr = CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(LTy));
1249 } else if (neededInt) {
1250 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1251 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1252 llvm::PointerType::getUnqual(LTy));
1254 if (neededSSE == 1) {
1255 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1256 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1257 llvm::PointerType::getUnqual(LTy));
1259 assert(neededSSE == 2 && "Invalid number of needed registers!");
1260 // SSE registers are spaced 16 bytes apart in the register save
1261 // area, we need to collect the two eightbytes together.
1262 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1263 llvm::Value *RegAddrHi =
1264 CGF.Builder.CreateGEP(RegAddrLo,
1265 llvm::ConstantInt::get(llvm::Type::Int32Ty, 16));
1266 const llvm::Type *DblPtrTy =
1267 llvm::PointerType::getUnqual(llvm::Type::DoubleTy);
1268 const llvm::StructType *ST = llvm::StructType::get(llvm::Type::DoubleTy,
1269 llvm::Type::DoubleTy,
1271 llvm::Value *V, *Tmp = CGF.CreateTempAlloca(ST);
1272 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
1274 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1275 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
1277 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1278 RegAddr = CGF.Builder.CreateBitCast(Tmp,
1279 llvm::PointerType::getUnqual(LTy));
1283 // AMD64-ABI 3.5.7p5: Step 5. Set:
1284 // l->gp_offset = l->gp_offset + num_gp * 8
1285 // l->fp_offset = l->fp_offset + num_fp * 16.
1287 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty,
1289 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
1293 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty,
1295 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
1298 CGF.EmitBranch(ContBlock);
1300 // Emit code to load the value if it was passed in memory.
1302 CGF.EmitBlock(InMemBlock);
1303 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1305 // Return the appropriate result.
1307 CGF.EmitBlock(ContBlock);
1308 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(),
1310 ResAddr->reserveOperandSpace(2);
1311 ResAddr->addIncoming(RegAddr, InRegBlock);
1312 ResAddr->addIncoming(MemAddr, InMemBlock);
1317 // ABI Info for PIC16
1318 class PIC16ABIInfo : public ABIInfo {
1319 ABIArgInfo classifyReturnType(QualType RetTy,
1320 ASTContext &Context) const;
1322 ABIArgInfo classifyArgumentType(QualType RetTy,
1323 ASTContext &Context) const;
1325 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
1326 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
1327 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1329 it->info = classifyArgumentType(it->type, Context);
1332 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1333 CodeGenFunction &CGF) const;
1337 ABIArgInfo PIC16ABIInfo::classifyReturnType(QualType RetTy,
1338 ASTContext &Context) const {
1339 if (RetTy->isVoidType()) {
1340 return ABIArgInfo::getIgnore();
1342 return ABIArgInfo::getDirect();
1346 ABIArgInfo PIC16ABIInfo::classifyArgumentType(QualType Ty,
1347 ASTContext &Context) const {
1348 return ABIArgInfo::getDirect();
1351 llvm::Value *PIC16ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1352 CodeGenFunction &CGF) const {
1356 class ARMABIInfo : public ABIInfo {
1357 ABIArgInfo classifyReturnType(QualType RetTy,
1358 ASTContext &Context) const;
1360 ABIArgInfo classifyArgumentType(QualType RetTy,
1361 ASTContext &Context) const;
1363 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const;
1365 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1366 CodeGenFunction &CGF) const;
1369 void ARMABIInfo::computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
1370 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
1371 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1373 it->info = classifyArgumentType(it->type, Context);
1377 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
1378 ASTContext &Context) const {
1379 if (!CodeGenFunction::hasAggregateLLVMType(Ty)) {
1380 return ABIArgInfo::getDirect();
1382 // FIXME: This is kind of nasty... but there isn't much choice because the ARM
1383 // backend doesn't support byval.
1384 // FIXME: This doesn't handle alignment > 64 bits.
1385 const llvm::Type* ElemTy;
1387 if (Context.getTypeAlign(Ty) > 32) {
1388 ElemTy = llvm::Type::Int64Ty;
1389 SizeRegs = (Context.getTypeSize(Ty) + 63) / 64;
1391 ElemTy = llvm::Type::Int32Ty;
1392 SizeRegs = (Context.getTypeSize(Ty) + 31) / 32;
1394 std::vector<const llvm::Type*> LLVMFields;
1395 LLVMFields.push_back(llvm::ArrayType::get(ElemTy, SizeRegs));
1396 const llvm::Type* STy = llvm::StructType::get(LLVMFields, true);
1397 return ABIArgInfo::getCoerce(STy);
1400 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
1401 ASTContext &Context) const {
1402 if (RetTy->isVoidType()) {
1403 return ABIArgInfo::getIgnore();
1404 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1405 // Aggregates <= 4 bytes are returned in r0; other aggregates
1406 // are returned indirectly.
1407 uint64_t Size = Context.getTypeSize(RetTy);
1409 return ABIArgInfo::getCoerce(llvm::Type::Int32Ty);
1410 return ABIArgInfo::getIndirect(0);
1412 return ABIArgInfo::getDirect();
1416 llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1417 CodeGenFunction &CGF) const {
1418 // FIXME: Need to handle alignment
1419 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1420 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
1422 CGBuilderTy &Builder = CGF.Builder;
1423 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1425 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
1427 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
1428 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1431 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
1432 llvm::Value *NextAddr =
1433 Builder.CreateGEP(Addr,
1434 llvm::ConstantInt::get(llvm::Type::Int32Ty, Offset),
1436 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1441 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy,
1442 ASTContext &Context) const {
1443 if (RetTy->isVoidType()) {
1444 return ABIArgInfo::getIgnore();
1445 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1446 return ABIArgInfo::getIndirect(0);
1448 return ABIArgInfo::getDirect();
1452 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty,
1453 ASTContext &Context) const {
1454 if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
1455 return ABIArgInfo::getIndirect(0);
1457 return ABIArgInfo::getDirect();
1461 llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1462 CodeGenFunction &CGF) const {
1466 const ABIInfo &CodeGenTypes::getABIInfo() const {
1470 // For now we just cache this in the CodeGenTypes and don't bother
1472 const char *TargetPrefix = getContext().Target.getTargetPrefix();
1473 if (strcmp(TargetPrefix, "x86") == 0) {
1474 bool IsDarwin = strstr(getContext().Target.getTargetTriple(), "darwin");
1475 switch (getContext().Target.getPointerWidth(0)) {
1477 return *(TheABIInfo = new X86_32ABIInfo(Context, IsDarwin));
1479 return *(TheABIInfo = new X86_64ABIInfo());
1481 } else if (strcmp(TargetPrefix, "arm") == 0) {
1482 // FIXME: Support for OABI?
1483 return *(TheABIInfo = new ARMABIInfo());
1484 } else if (strcmp(TargetPrefix, "pic16") == 0) {
1485 return *(TheABIInfo = new PIC16ABIInfo());
1488 return *(TheABIInfo = new DefaultABIInfo);
1493 CGFunctionInfo::CGFunctionInfo(QualType ResTy,
1494 const llvm::SmallVector<QualType, 16> &ArgTys) {
1495 NumArgs = ArgTys.size();
1496 Args = new ArgInfo[1 + NumArgs];
1497 Args[0].type = ResTy;
1498 for (unsigned i = 0; i < NumArgs; ++i)
1499 Args[1 + i].type = ArgTys[i];
1504 void CodeGenTypes::GetExpandedTypes(QualType Ty,
1505 std::vector<const llvm::Type*> &ArgTys) {
1506 const RecordType *RT = Ty->getAsStructureType();
1507 assert(RT && "Can only expand structure types.");
1508 const RecordDecl *RD = RT->getDecl();
1509 assert(!RD->hasFlexibleArrayMember() &&
1510 "Cannot expand structure with flexible array.");
1512 for (RecordDecl::field_iterator i = RD->field_begin(Context),
1513 e = RD->field_end(Context); i != e; ++i) {
1514 const FieldDecl *FD = *i;
1515 assert(!FD->isBitField() &&
1516 "Cannot expand structure with bit-field members.");
1518 QualType FT = FD->getType();
1519 if (CodeGenFunction::hasAggregateLLVMType(FT)) {
1520 GetExpandedTypes(FT, ArgTys);
1522 ArgTys.push_back(ConvertType(FT));
1527 llvm::Function::arg_iterator
1528 CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
1529 llvm::Function::arg_iterator AI) {
1530 const RecordType *RT = Ty->getAsStructureType();
1531 assert(RT && "Can only expand structure types.");
1533 RecordDecl *RD = RT->getDecl();
1534 assert(LV.isSimple() &&
1535 "Unexpected non-simple lvalue during struct expansion.");
1536 llvm::Value *Addr = LV.getAddress();
1537 for (RecordDecl::field_iterator i = RD->field_begin(getContext()),
1538 e = RD->field_end(getContext()); i != e; ++i) {
1540 QualType FT = FD->getType();
1542 // FIXME: What are the right qualifiers here?
1543 LValue LV = EmitLValueForField(Addr, FD, false, 0);
1544 if (CodeGenFunction::hasAggregateLLVMType(FT)) {
1545 AI = ExpandTypeFromArgs(FT, LV, AI);
1547 EmitStoreThroughLValue(RValue::get(AI), LV, FT);
1556 CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
1557 llvm::SmallVector<llvm::Value*, 16> &Args) {
1558 const RecordType *RT = Ty->getAsStructureType();
1559 assert(RT && "Can only expand structure types.");
1561 RecordDecl *RD = RT->getDecl();
1562 assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
1563 llvm::Value *Addr = RV.getAggregateAddr();
1564 for (RecordDecl::field_iterator i = RD->field_begin(getContext()),
1565 e = RD->field_end(getContext()); i != e; ++i) {
1567 QualType FT = FD->getType();
1569 // FIXME: What are the right qualifiers here?
1570 LValue LV = EmitLValueForField(Addr, FD, false, 0);
1571 if (CodeGenFunction::hasAggregateLLVMType(FT)) {
1572 ExpandTypeToArgs(FT, RValue::getAggregate(LV.getAddress()), Args);
1574 RValue RV = EmitLoadOfLValue(LV, FT);
1575 assert(RV.isScalar() &&
1576 "Unexpected non-scalar rvalue during struct expansion.");
1577 Args.push_back(RV.getScalarVal());
1582 /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
1583 /// a pointer to an object of type \arg Ty.
1585 /// This safely handles the case when the src type is smaller than the
1586 /// destination type; in this situation the values of bits which not
1587 /// present in the src are undefined.
1588 static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
1589 const llvm::Type *Ty,
1590 CodeGenFunction &CGF) {
1591 const llvm::Type *SrcTy =
1592 cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
1593 uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy);
1594 uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(Ty);
1596 // If load is legal, just bitcast the src pointer.
1597 if (SrcSize >= DstSize) {
1598 // Generally SrcSize is never greater than DstSize, since this means we are
1599 // losing bits. However, this can happen in cases where the structure has
1600 // additional padding, for example due to a user specified alignment.
1602 // FIXME: Assert that we aren't truncating non-padding bits when have access
1603 // to that information.
1604 llvm::Value *Casted =
1605 CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
1606 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
1607 // FIXME: Use better alignment / avoid requiring aligned load.
1608 Load->setAlignment(1);
1611 // Otherwise do coercion through memory. This is stupid, but
1613 llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
1614 llvm::Value *Casted =
1615 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(SrcTy));
1616 llvm::StoreInst *Store =
1617 CGF.Builder.CreateStore(CGF.Builder.CreateLoad(SrcPtr), Casted);
1618 // FIXME: Use better alignment / avoid requiring aligned store.
1619 Store->setAlignment(1);
1620 return CGF.Builder.CreateLoad(Tmp);
1624 /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
1625 /// where the source and destination may have different types.
1627 /// This safely handles the case when the src type is larger than the
1628 /// destination type; the upper bits of the src will be lost.
1629 static void CreateCoercedStore(llvm::Value *Src,
1630 llvm::Value *DstPtr,
1631 CodeGenFunction &CGF) {
1632 const llvm::Type *SrcTy = Src->getType();
1633 const llvm::Type *DstTy =
1634 cast<llvm::PointerType>(DstPtr->getType())->getElementType();
1636 uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy);
1637 uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(DstTy);
1639 // If store is legal, just bitcast the src pointer.
1640 if (SrcSize >= DstSize) {
1641 // Generally SrcSize is never greater than DstSize, since this means we are
1642 // losing bits. However, this can happen in cases where the structure has
1643 // additional padding, for example due to a user specified alignment.
1645 // FIXME: Assert that we aren't truncating non-padding bits when have access
1646 // to that information.
1647 llvm::Value *Casted =
1648 CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
1649 // FIXME: Use better alignment / avoid requiring aligned store.
1650 CGF.Builder.CreateStore(Src, Casted)->setAlignment(1);
1652 // Otherwise do coercion through memory. This is stupid, but
1654 llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
1655 CGF.Builder.CreateStore(Src, Tmp);
1656 llvm::Value *Casted =
1657 CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(DstTy));
1658 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
1659 // FIXME: Use better alignment / avoid requiring aligned load.
1660 Load->setAlignment(1);
1661 CGF.Builder.CreateStore(Load, DstPtr);
1667 bool CodeGenModule::ReturnTypeUsesSret(const CGFunctionInfo &FI) {
1668 return FI.getReturnInfo().isIndirect();
1671 const llvm::FunctionType *
1672 CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI, bool IsVariadic) {
1673 std::vector<const llvm::Type*> ArgTys;
1675 const llvm::Type *ResultType = 0;
1677 QualType RetTy = FI.getReturnType();
1678 const ABIArgInfo &RetAI = FI.getReturnInfo();
1679 switch (RetAI.getKind()) {
1680 case ABIArgInfo::Expand:
1681 assert(0 && "Invalid ABI kind for return argument");
1683 case ABIArgInfo::Direct:
1684 ResultType = ConvertType(RetTy);
1687 case ABIArgInfo::Indirect: {
1688 assert(!RetAI.getIndirectAlign() && "Align unused on indirect return.");
1689 ResultType = llvm::Type::VoidTy;
1690 const llvm::Type *STy = ConvertType(RetTy);
1691 ArgTys.push_back(llvm::PointerType::get(STy, RetTy.getAddressSpace()));
1695 case ABIArgInfo::Ignore:
1696 ResultType = llvm::Type::VoidTy;
1699 case ABIArgInfo::Coerce:
1700 ResultType = RetAI.getCoerceToType();
1704 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1705 ie = FI.arg_end(); it != ie; ++it) {
1706 const ABIArgInfo &AI = it->info;
1708 switch (AI.getKind()) {
1709 case ABIArgInfo::Ignore:
1712 case ABIArgInfo::Coerce:
1713 ArgTys.push_back(AI.getCoerceToType());
1716 case ABIArgInfo::Indirect: {
1717 // indirect arguments are always on the stack, which is addr space #0.
1718 const llvm::Type *LTy = ConvertTypeForMem(it->type);
1719 ArgTys.push_back(llvm::PointerType::getUnqual(LTy));
1723 case ABIArgInfo::Direct:
1724 ArgTys.push_back(ConvertType(it->type));
1727 case ABIArgInfo::Expand:
1728 GetExpandedTypes(it->type, ArgTys);
1733 return llvm::FunctionType::get(ResultType, ArgTys, IsVariadic);
1736 void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
1737 const Decl *TargetDecl,
1738 AttributeListType &PAL) {
1739 unsigned FuncAttrs = 0;
1740 unsigned RetAttrs = 0;
1742 // FIXME: handle sseregparm someday...
1744 if (TargetDecl->hasAttr<NoThrowAttr>())
1745 FuncAttrs |= llvm::Attribute::NoUnwind;
1746 if (TargetDecl->hasAttr<NoReturnAttr>())
1747 FuncAttrs |= llvm::Attribute::NoReturn;
1748 if (TargetDecl->hasAttr<ConstAttr>())
1749 FuncAttrs |= llvm::Attribute::ReadNone;
1750 else if (TargetDecl->hasAttr<PureAttr>())
1751 FuncAttrs |= llvm::Attribute::ReadOnly;
1754 QualType RetTy = FI.getReturnType();
1756 const ABIArgInfo &RetAI = FI.getReturnInfo();
1757 switch (RetAI.getKind()) {
1758 case ABIArgInfo::Direct:
1759 if (RetTy->isPromotableIntegerType()) {
1760 if (RetTy->isSignedIntegerType()) {
1761 RetAttrs |= llvm::Attribute::SExt;
1762 } else if (RetTy->isUnsignedIntegerType()) {
1763 RetAttrs |= llvm::Attribute::ZExt;
1768 case ABIArgInfo::Indirect:
1769 PAL.push_back(llvm::AttributeWithIndex::get(Index,
1770 llvm::Attribute::StructRet |
1771 llvm::Attribute::NoAlias));
1773 // sret disables readnone and readonly
1774 FuncAttrs &= ~(llvm::Attribute::ReadOnly |
1775 llvm::Attribute::ReadNone);
1778 case ABIArgInfo::Ignore:
1779 case ABIArgInfo::Coerce:
1782 case ABIArgInfo::Expand:
1783 assert(0 && "Invalid ABI kind for return argument");
1787 PAL.push_back(llvm::AttributeWithIndex::get(0, RetAttrs));
1789 // FIXME: we need to honour command line settings also...
1790 // FIXME: RegParm should be reduced in case of nested functions and/or global
1791 // register variable.
1794 if (const RegparmAttr *RegParmAttr = TargetDecl->getAttr<RegparmAttr>())
1795 RegParm = RegParmAttr->getNumParams();
1797 unsigned PointerWidth = getContext().Target.getPointerWidth(0);
1798 for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
1799 ie = FI.arg_end(); it != ie; ++it) {
1800 QualType ParamType = it->type;
1801 const ABIArgInfo &AI = it->info;
1802 unsigned Attributes = 0;
1804 switch (AI.getKind()) {
1805 case ABIArgInfo::Coerce:
1808 case ABIArgInfo::Indirect:
1809 Attributes |= llvm::Attribute::ByVal;
1811 llvm::Attribute::constructAlignmentFromInt(AI.getIndirectAlign());
1812 // byval disables readnone and readonly.
1813 FuncAttrs &= ~(llvm::Attribute::ReadOnly |
1814 llvm::Attribute::ReadNone);
1817 case ABIArgInfo::Direct:
1818 if (ParamType->isPromotableIntegerType()) {
1819 if (ParamType->isSignedIntegerType()) {
1820 Attributes |= llvm::Attribute::SExt;
1821 } else if (ParamType->isUnsignedIntegerType()) {
1822 Attributes |= llvm::Attribute::ZExt;
1826 (ParamType->isIntegerType() || ParamType->isPointerType())) {
1828 (Context.getTypeSize(ParamType) + PointerWidth - 1) / PointerWidth;
1830 Attributes |= llvm::Attribute::InReg;
1832 // FIXME: handle sseregparm someday...
1835 case ABIArgInfo::Ignore:
1836 // Skip increment, no matching LLVM parameter.
1839 case ABIArgInfo::Expand: {
1840 std::vector<const llvm::Type*> Tys;
1841 // FIXME: This is rather inefficient. Do we ever actually need to do
1842 // anything here? The result should be just reconstructed on the other
1843 // side, so extension should be a non-issue.
1844 getTypes().GetExpandedTypes(ParamType, Tys);
1845 Index += Tys.size();
1851 PAL.push_back(llvm::AttributeWithIndex::get(Index, Attributes));
1855 PAL.push_back(llvm::AttributeWithIndex::get(~0, FuncAttrs));
1858 void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
1860 const FunctionArgList &Args) {
1861 // FIXME: We no longer need the types from FunctionArgList; lift up and
1864 // Emit allocs for param decls. Give the LLVM Argument nodes names.
1865 llvm::Function::arg_iterator AI = Fn->arg_begin();
1867 // Name the struct return argument.
1868 if (CGM.ReturnTypeUsesSret(FI)) {
1869 AI->setName("agg.result");
1873 assert(FI.arg_size() == Args.size() &&
1874 "Mismatch between function signature & arguments.");
1875 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
1876 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
1877 i != e; ++i, ++info_it) {
1878 const VarDecl *Arg = i->first;
1879 QualType Ty = info_it->type;
1880 const ABIArgInfo &ArgI = info_it->info;
1882 switch (ArgI.getKind()) {
1883 case ABIArgInfo::Indirect: {
1884 llvm::Value* V = AI;
1885 if (hasAggregateLLVMType(Ty)) {
1886 // Do nothing, aggregates and complex variables are accessed by
1889 // Load scalar value from indirect argument.
1890 V = EmitLoadOfScalar(V, false, Ty);
1891 if (!getContext().typesAreCompatible(Ty, Arg->getType())) {
1892 // This must be a promotion, for something like
1893 // "void a(x) short x; {..."
1894 V = EmitScalarConversion(V, Ty, Arg->getType());
1897 EmitParmDecl(*Arg, V);
1901 case ABIArgInfo::Direct: {
1902 assert(AI != Fn->arg_end() && "Argument mismatch!");
1903 llvm::Value* V = AI;
1904 if (hasAggregateLLVMType(Ty)) {
1905 // Create a temporary alloca to hold the argument; the rest of
1906 // codegen expects to access aggregates & complex values by
1908 V = CreateTempAlloca(ConvertTypeForMem(Ty));
1909 Builder.CreateStore(AI, V);
1911 if (!getContext().typesAreCompatible(Ty, Arg->getType())) {
1912 // This must be a promotion, for something like
1913 // "void a(x) short x; {..."
1914 V = EmitScalarConversion(V, Ty, Arg->getType());
1917 EmitParmDecl(*Arg, V);
1921 case ABIArgInfo::Expand: {
1922 // If this structure was expanded into multiple arguments then
1923 // we need to create a temporary and reconstruct it from the
1925 std::string Name = Arg->getNameAsString();
1926 llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(Ty),
1927 (Name + ".addr").c_str());
1928 // FIXME: What are the right qualifiers here?
1929 llvm::Function::arg_iterator End =
1930 ExpandTypeFromArgs(Ty, LValue::MakeAddr(Temp,0), AI);
1931 EmitParmDecl(*Arg, Temp);
1933 // Name the arguments used in expansion and increment AI.
1935 for (; AI != End; ++AI, ++Index)
1936 AI->setName(Name + "." + llvm::utostr(Index));
1940 case ABIArgInfo::Ignore:
1941 // Initialize the local variable appropriately.
1942 if (hasAggregateLLVMType(Ty)) {
1943 EmitParmDecl(*Arg, CreateTempAlloca(ConvertTypeForMem(Ty)));
1945 EmitParmDecl(*Arg, llvm::UndefValue::get(ConvertType(Arg->getType())));
1948 // Skip increment, no matching LLVM parameter.
1951 case ABIArgInfo::Coerce: {
1952 assert(AI != Fn->arg_end() && "Argument mismatch!");
1953 // FIXME: This is very wasteful; EmitParmDecl is just going to drop the
1954 // result in a new alloca anyway, so we could just store into that
1955 // directly if we broke the abstraction down more.
1956 llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(Ty), "coerce");
1957 CreateCoercedStore(AI, V, *this);
1958 // Match to what EmitParmDecl is expecting for this type.
1959 if (!CodeGenFunction::hasAggregateLLVMType(Ty)) {
1960 V = EmitLoadOfScalar(V, false, Ty);
1961 if (!getContext().typesAreCompatible(Ty, Arg->getType())) {
1962 // This must be a promotion, for something like
1963 // "void a(x) short x; {..."
1964 V = EmitScalarConversion(V, Ty, Arg->getType());
1967 EmitParmDecl(*Arg, V);
1974 assert(AI == Fn->arg_end() && "Argument mismatch!");
1977 void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
1978 llvm::Value *ReturnValue) {
1979 llvm::Value *RV = 0;
1981 // Functions with no result always return void.
1983 QualType RetTy = FI.getReturnType();
1984 const ABIArgInfo &RetAI = FI.getReturnInfo();
1986 switch (RetAI.getKind()) {
1987 case ABIArgInfo::Indirect:
1988 if (RetTy->isAnyComplexType()) {
1989 ComplexPairTy RT = LoadComplexFromAddr(ReturnValue, false);
1990 StoreComplexToAddr(RT, CurFn->arg_begin(), false);
1991 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1992 EmitAggregateCopy(CurFn->arg_begin(), ReturnValue, RetTy);
1994 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue), CurFn->arg_begin(),
1999 case ABIArgInfo::Direct:
2000 // The internal return value temp always will have
2001 // pointer-to-return-type type.
2002 RV = Builder.CreateLoad(ReturnValue);
2005 case ABIArgInfo::Ignore:
2008 case ABIArgInfo::Coerce:
2009 RV = CreateCoercedLoad(ReturnValue, RetAI.getCoerceToType(), *this);
2012 case ABIArgInfo::Expand:
2013 assert(0 && "Invalid ABI kind for return argument");
2018 Builder.CreateRet(RV);
2020 Builder.CreateRetVoid();
2024 RValue CodeGenFunction::EmitCallArg(const Expr *E, QualType ArgType) {
2025 if (ArgType->isReferenceType())
2026 return EmitReferenceBindingToExpr(E, ArgType);
2028 return EmitAnyExprToTemp(E);
2031 RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
2032 llvm::Value *Callee,
2033 const CallArgList &CallArgs,
2034 const Decl *TargetDecl) {
2035 // FIXME: We no longer need the types from CallArgs; lift up and simplify.
2036 llvm::SmallVector<llvm::Value*, 16> Args;
2038 // Handle struct-return functions by passing a pointer to the
2039 // location that we would like to return into.
2040 QualType RetTy = CallInfo.getReturnType();
2041 const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
2042 if (CGM.ReturnTypeUsesSret(CallInfo)) {
2043 // Create a temporary alloca to hold the result of the call. :(
2044 Args.push_back(CreateTempAlloca(ConvertTypeForMem(RetTy)));
2047 assert(CallInfo.arg_size() == CallArgs.size() &&
2048 "Mismatch between function signature & arguments.");
2049 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
2050 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
2051 I != E; ++I, ++info_it) {
2052 const ABIArgInfo &ArgInfo = info_it->info;
2053 RValue RV = I->first;
2055 switch (ArgInfo.getKind()) {
2056 case ABIArgInfo::Indirect:
2057 if (RV.isScalar() || RV.isComplex()) {
2058 // Make a temporary alloca to pass the argument.
2059 Args.push_back(CreateTempAlloca(ConvertTypeForMem(I->second)));
2061 EmitStoreOfScalar(RV.getScalarVal(), Args.back(), false, I->second);
2063 StoreComplexToAddr(RV.getComplexVal(), Args.back(), false);
2065 Args.push_back(RV.getAggregateAddr());
2069 case ABIArgInfo::Direct:
2070 if (RV.isScalar()) {
2071 Args.push_back(RV.getScalarVal());
2072 } else if (RV.isComplex()) {
2073 llvm::Value *Tmp = llvm::UndefValue::get(ConvertType(I->second));
2074 Tmp = Builder.CreateInsertValue(Tmp, RV.getComplexVal().first, 0);
2075 Tmp = Builder.CreateInsertValue(Tmp, RV.getComplexVal().second, 1);
2076 Args.push_back(Tmp);
2078 Args.push_back(Builder.CreateLoad(RV.getAggregateAddr()));
2082 case ABIArgInfo::Ignore:
2085 case ABIArgInfo::Coerce: {
2086 // FIXME: Avoid the conversion through memory if possible.
2087 llvm::Value *SrcPtr;
2088 if (RV.isScalar()) {
2089 SrcPtr = CreateTempAlloca(ConvertTypeForMem(I->second), "coerce");
2090 EmitStoreOfScalar(RV.getScalarVal(), SrcPtr, false, I->second);
2091 } else if (RV.isComplex()) {
2092 SrcPtr = CreateTempAlloca(ConvertTypeForMem(I->second), "coerce");
2093 StoreComplexToAddr(RV.getComplexVal(), SrcPtr, false);
2095 SrcPtr = RV.getAggregateAddr();
2096 Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
2101 case ABIArgInfo::Expand:
2102 ExpandTypeToArgs(I->second, RV, Args);
2107 llvm::BasicBlock *InvokeDest = getInvokeDest();
2108 CodeGen::AttributeListType AttributeList;
2109 CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList);
2110 llvm::AttrListPtr Attrs = llvm::AttrListPtr::get(AttributeList.begin(),
2111 AttributeList.end());
2114 if (!InvokeDest || (Attrs.getFnAttributes() & llvm::Attribute::NoUnwind)) {
2115 CS = Builder.CreateCall(Callee, Args.data(), Args.data()+Args.size());
2117 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
2118 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest,
2119 Args.data(), Args.data()+Args.size());
2123 CS.setAttributes(Attrs);
2124 if (const llvm::Function *F = dyn_cast<llvm::Function>(Callee->stripPointerCasts()))
2125 CS.setCallingConv(F->getCallingConv());
2127 // If the call doesn't return, finish the basic block and clear the
2128 // insertion point; this allows the rest of IRgen to discard
2129 // unreachable code.
2130 if (CS.doesNotReturn()) {
2131 Builder.CreateUnreachable();
2132 Builder.ClearInsertionPoint();
2134 // FIXME: For now, emit a dummy basic block because expr emitters in
2135 // generally are not ready to handle emitting expressions at unreachable
2137 EnsureInsertPoint();
2139 // Return a reasonable RValue.
2140 return GetUndefRValue(RetTy);
2143 llvm::Instruction *CI = CS.getInstruction();
2144 if (Builder.isNamePreserving() && CI->getType() != llvm::Type::VoidTy)
2145 CI->setName("call");
2147 switch (RetAI.getKind()) {
2148 case ABIArgInfo::Indirect:
2149 if (RetTy->isAnyComplexType())
2150 return RValue::getComplex(LoadComplexFromAddr(Args[0], false));
2151 if (CodeGenFunction::hasAggregateLLVMType(RetTy))
2152 return RValue::getAggregate(Args[0]);
2153 return RValue::get(EmitLoadOfScalar(Args[0], false, RetTy));
2155 case ABIArgInfo::Direct:
2156 if (RetTy->isAnyComplexType()) {
2157 llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
2158 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
2159 return RValue::getComplex(std::make_pair(Real, Imag));
2161 if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
2162 llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(RetTy), "agg.tmp");
2163 Builder.CreateStore(CI, V);
2164 return RValue::getAggregate(V);
2166 return RValue::get(CI);
2168 case ABIArgInfo::Ignore:
2169 // If we are ignoring an argument that had a result, make sure to
2170 // construct the appropriate return value for our caller.
2171 return GetUndefRValue(RetTy);
2173 case ABIArgInfo::Coerce: {
2174 // FIXME: Avoid the conversion through memory if possible.
2175 llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(RetTy), "coerce");
2176 CreateCoercedStore(CI, V, *this);
2177 if (RetTy->isAnyComplexType())
2178 return RValue::getComplex(LoadComplexFromAddr(V, false));
2179 if (CodeGenFunction::hasAggregateLLVMType(RetTy))
2180 return RValue::getAggregate(V);
2181 return RValue::get(EmitLoadOfScalar(V, false, RetTy));
2184 case ABIArgInfo::Expand:
2185 assert(0 && "Invalid ABI kind for return argument");
2188 assert(0 && "Unhandled ABIArgInfo::Kind");
2189 return RValue::get(0);
2192 /* VarArg handling */
2194 llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
2195 return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);