1 //===----- 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 "ABIInfo.h"
17 #include "CodeGenFunction.h"
18 #include "CodeGenModule.h"
19 #include "clang/Basic/TargetInfo.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/Frontend/CodeGenOptions.h"
24 #include "llvm/Attributes.h"
25 #include "llvm/Support/CallSite.h"
26 #include "llvm/Target/TargetData.h"
27 using namespace clang;
28 using namespace CodeGen;
29 
30 /***/
31 
32 static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
33   switch (CC) {
34   default: return llvm::CallingConv::C;
35   case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
36   case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
37   case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
38   }
39 }
40 
41 /// Derives the 'this' type for codegen purposes, i.e. ignoring method
42 /// qualification.
43 /// FIXME: address space qualification?
44 static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
45   QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
46   return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
47 }
48 
49 /// Returns the canonical formal type of the given C++ method.
50 static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
51   return MD->getType()->getCanonicalTypeUnqualified()
52            .getAs<FunctionProtoType>();
53 }
54 
55 /// Returns the "extra-canonicalized" return type, which discards
56 /// qualifiers on the return type.  Codegen doesn't care about them,
57 /// and it makes ABI code a little easier to be able to assume that
58 /// all parameter and return types are top-level unqualified.
59 static CanQualType GetReturnType(QualType RetTy) {
60   return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
61 }
62 
63 const CGFunctionInfo &
64 CodeGenTypes::getFunctionInfo(CanQual<FunctionNoProtoType> FTNP,
65                               bool IsRecursive) {
66   return getFunctionInfo(FTNP->getResultType().getUnqualifiedType(),
67                          llvm::SmallVector<CanQualType, 16>(),
68                          FTNP->getExtInfo(), IsRecursive);
69 }
70 
71 /// \param Args - contains any initial parameters besides those
72 ///   in the formal type
73 static const CGFunctionInfo &getFunctionInfo(CodeGenTypes &CGT,
74                                   llvm::SmallVectorImpl<CanQualType> &ArgTys,
75                                              CanQual<FunctionProtoType> FTP,
76                                              bool IsRecursive = false) {
77   // FIXME: Kill copy.
78   for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
79     ArgTys.push_back(FTP->getArgType(i));
80   CanQualType ResTy = FTP->getResultType().getUnqualifiedType();
81   return CGT.getFunctionInfo(ResTy, ArgTys, FTP->getExtInfo(), IsRecursive);
82 }
83 
84 const CGFunctionInfo &
85 CodeGenTypes::getFunctionInfo(CanQual<FunctionProtoType> FTP,
86                               bool IsRecursive) {
87   llvm::SmallVector<CanQualType, 16> ArgTys;
88   return ::getFunctionInfo(*this, ArgTys, FTP, IsRecursive);
89 }
90 
91 static CallingConv getCallingConventionForDecl(const Decl *D) {
92   // Set the appropriate calling convention for the Function.
93   if (D->hasAttr<StdCallAttr>())
94     return CC_X86StdCall;
95 
96   if (D->hasAttr<FastCallAttr>())
97     return CC_X86FastCall;
98 
99   if (D->hasAttr<ThisCallAttr>())
100     return CC_X86ThisCall;
101 
102   return CC_C;
103 }
104 
105 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXRecordDecl *RD,
106                                                  const FunctionProtoType *FTP) {
107   llvm::SmallVector<CanQualType, 16> ArgTys;
108 
109   // Add the 'this' pointer.
110   ArgTys.push_back(GetThisType(Context, RD));
111 
112   return ::getFunctionInfo(*this, ArgTys,
113               FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
114 }
115 
116 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXMethodDecl *MD) {
117   llvm::SmallVector<CanQualType, 16> ArgTys;
118 
119   // Add the 'this' pointer unless this is a static method.
120   if (MD->isInstance())
121     ArgTys.push_back(GetThisType(Context, MD->getParent()));
122 
123   return ::getFunctionInfo(*this, ArgTys, GetFormalType(MD));
124 }
125 
126 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXConstructorDecl *D,
127                                                     CXXCtorType Type) {
128   llvm::SmallVector<CanQualType, 16> ArgTys;
129 
130   // Add the 'this' pointer.
131   ArgTys.push_back(GetThisType(Context, D->getParent()));
132 
133   // Check if we need to add a VTT parameter (which has type void **).
134   if (Type == Ctor_Base && D->getParent()->getNumVBases() != 0)
135     ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
136 
137   return ::getFunctionInfo(*this, ArgTys, GetFormalType(D));
138 }
139 
140 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXDestructorDecl *D,
141                                                     CXXDtorType Type) {
142   llvm::SmallVector<CanQualType, 16> ArgTys;
143 
144   // Add the 'this' pointer.
145   ArgTys.push_back(GetThisType(Context, D->getParent()));
146 
147   // Check if we need to add a VTT parameter (which has type void **).
148   if (Type == Dtor_Base && D->getParent()->getNumVBases() != 0)
149     ArgTys.push_back(Context.getPointerType(Context.VoidPtrTy));
150 
151   return ::getFunctionInfo(*this, ArgTys, GetFormalType(D));
152 }
153 
154 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionDecl *FD) {
155   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
156     if (MD->isInstance())
157       return getFunctionInfo(MD);
158 
159   CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
160   assert(isa<FunctionType>(FTy));
161   if (isa<FunctionNoProtoType>(FTy))
162     return getFunctionInfo(FTy.getAs<FunctionNoProtoType>());
163   assert(isa<FunctionProtoType>(FTy));
164   return getFunctionInfo(FTy.getAs<FunctionProtoType>());
165 }
166 
167 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const ObjCMethodDecl *MD) {
168   llvm::SmallVector<CanQualType, 16> ArgTys;
169   ArgTys.push_back(Context.getCanonicalParamType(MD->getSelfDecl()->getType()));
170   ArgTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
171   // FIXME: Kill copy?
172   for (ObjCMethodDecl::param_iterator i = MD->param_begin(),
173          e = MD->param_end(); i != e; ++i) {
174     ArgTys.push_back(Context.getCanonicalParamType((*i)->getType()));
175   }
176   return getFunctionInfo(GetReturnType(MD->getResultType()),
177                          ArgTys,
178                          FunctionType::ExtInfo(
179                              /*NoReturn*/ false,
180                              /*RegParm*/ 0,
181                              getCallingConventionForDecl(MD)));
182 }
183 
184 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(GlobalDecl GD) {
185   // FIXME: Do we need to handle ObjCMethodDecl?
186   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
187 
188   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
189     return getFunctionInfo(CD, GD.getCtorType());
190 
191   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
192     return getFunctionInfo(DD, GD.getDtorType());
193 
194   return getFunctionInfo(FD);
195 }
196 
197 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
198                                                     const CallArgList &Args,
199                                             const FunctionType::ExtInfo &Info) {
200   // FIXME: Kill copy.
201   llvm::SmallVector<CanQualType, 16> ArgTys;
202   for (CallArgList::const_iterator i = Args.begin(), e = Args.end();
203        i != e; ++i)
204     ArgTys.push_back(Context.getCanonicalParamType(i->second));
205   return getFunctionInfo(GetReturnType(ResTy), ArgTys, Info);
206 }
207 
208 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
209                                                     const FunctionArgList &Args,
210                                             const FunctionType::ExtInfo &Info) {
211   // FIXME: Kill copy.
212   llvm::SmallVector<CanQualType, 16> ArgTys;
213   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
214        i != e; ++i)
215     ArgTys.push_back(Context.getCanonicalParamType(i->second));
216   return getFunctionInfo(GetReturnType(ResTy), ArgTys, Info);
217 }
218 
219 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(CanQualType ResTy,
220                            const llvm::SmallVectorImpl<CanQualType> &ArgTys,
221                                             const FunctionType::ExtInfo &Info,
222                                                     bool IsRecursive) {
223 #ifndef NDEBUG
224   for (llvm::SmallVectorImpl<CanQualType>::const_iterator
225          I = ArgTys.begin(), E = ArgTys.end(); I != E; ++I)
226     assert(I->isCanonicalAsParam());
227 #endif
228 
229   unsigned CC = ClangCallConvToLLVMCallConv(Info.getCC());
230 
231   // Lookup or create unique function info.
232   llvm::FoldingSetNodeID ID;
233   CGFunctionInfo::Profile(ID, Info, ResTy,
234                           ArgTys.begin(), ArgTys.end());
235 
236   void *InsertPos = 0;
237   CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, InsertPos);
238   if (FI)
239     return *FI;
240 
241   // Construct the function info.
242   FI = new CGFunctionInfo(CC, Info.getNoReturn(), Info.getRegParm(), ResTy,
243                           ArgTys.data(), ArgTys.size());
244   FunctionInfos.InsertNode(FI, InsertPos);
245 
246   // ABI lowering wants to know what our preferred type for the argument is in
247   // various situations, pass it in.
248   llvm::SmallVector<const llvm::Type *, 8> PreferredArgTypes;
249   for (llvm::SmallVectorImpl<CanQualType>::const_iterator
250        I = ArgTys.begin(), E = ArgTys.end(); I != E; ++I) {
251     // If this is being called from the guts of the ConvertType loop, make sure
252     // to call ConvertTypeRecursive so we don't get into issues with cyclic
253     // pointer type structures.
254     PreferredArgTypes.push_back(ConvertTypeRecursive(*I));
255   }
256 
257   // Compute ABI information.
258   getABIInfo().computeInfo(*FI, getContext(), TheModule.getContext(),
259                            PreferredArgTypes.data(), PreferredArgTypes.size());
260 
261   // If this is a top-level call and ConvertTypeRecursive hit unresolved pointer
262   // types, resolve them now.  These pointers may point to this function, which
263   // we *just* filled in the FunctionInfo for.
264   if (!IsRecursive && !PointersToResolve.empty()) {
265     // Use PATypeHolder's so that our preferred types don't dangle under
266     // refinement.
267     llvm::SmallVector<llvm::PATypeHolder, 8> Handles(PreferredArgTypes.begin(),
268                                                      PreferredArgTypes.end());
269     HandleLateResolvedPointers();
270     PreferredArgTypes.clear();
271     PreferredArgTypes.append(Handles.begin(), Handles.end());
272   }
273 
274 
275   return *FI;
276 }
277 
278 CGFunctionInfo::CGFunctionInfo(unsigned _CallingConvention,
279                                bool _NoReturn, unsigned _RegParm,
280                                CanQualType ResTy,
281                                const CanQualType *ArgTys,
282                                unsigned NumArgTys)
283   : CallingConvention(_CallingConvention),
284     EffectiveCallingConvention(_CallingConvention),
285     NoReturn(_NoReturn), RegParm(_RegParm)
286 {
287   NumArgs = NumArgTys;
288 
289   // FIXME: Coallocate with the CGFunctionInfo object.
290   Args = new ArgInfo[1 + NumArgTys];
291   Args[0].type = ResTy;
292   for (unsigned i = 0; i != NumArgTys; ++i)
293     Args[1 + i].type = ArgTys[i];
294 }
295 
296 /***/
297 
298 void CodeGenTypes::GetExpandedTypes(QualType Ty,
299                                     std::vector<const llvm::Type*> &ArgTys,
300                                     bool IsRecursive) {
301   const RecordType *RT = Ty->getAsStructureType();
302   assert(RT && "Can only expand structure types.");
303   const RecordDecl *RD = RT->getDecl();
304   assert(!RD->hasFlexibleArrayMember() &&
305          "Cannot expand structure with flexible array.");
306 
307   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
308          i != e; ++i) {
309     const FieldDecl *FD = *i;
310     assert(!FD->isBitField() &&
311            "Cannot expand structure with bit-field members.");
312 
313     QualType FT = FD->getType();
314     if (CodeGenFunction::hasAggregateLLVMType(FT)) {
315       GetExpandedTypes(FT, ArgTys, IsRecursive);
316     } else {
317       ArgTys.push_back(ConvertType(FT, IsRecursive));
318     }
319   }
320 }
321 
322 llvm::Function::arg_iterator
323 CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
324                                     llvm::Function::arg_iterator AI) {
325   const RecordType *RT = Ty->getAsStructureType();
326   assert(RT && "Can only expand structure types.");
327 
328   RecordDecl *RD = RT->getDecl();
329   assert(LV.isSimple() &&
330          "Unexpected non-simple lvalue during struct expansion.");
331   llvm::Value *Addr = LV.getAddress();
332   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
333          i != e; ++i) {
334     FieldDecl *FD = *i;
335     QualType FT = FD->getType();
336 
337     // FIXME: What are the right qualifiers here?
338     LValue LV = EmitLValueForField(Addr, FD, 0);
339     if (CodeGenFunction::hasAggregateLLVMType(FT)) {
340       AI = ExpandTypeFromArgs(FT, LV, AI);
341     } else {
342       EmitStoreThroughLValue(RValue::get(AI), LV, FT);
343       ++AI;
344     }
345   }
346 
347   return AI;
348 }
349 
350 void
351 CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
352                                   llvm::SmallVector<llvm::Value*, 16> &Args) {
353   const RecordType *RT = Ty->getAsStructureType();
354   assert(RT && "Can only expand structure types.");
355 
356   RecordDecl *RD = RT->getDecl();
357   assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
358   llvm::Value *Addr = RV.getAggregateAddr();
359   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
360          i != e; ++i) {
361     FieldDecl *FD = *i;
362     QualType FT = FD->getType();
363 
364     // FIXME: What are the right qualifiers here?
365     LValue LV = EmitLValueForField(Addr, FD, 0);
366     if (CodeGenFunction::hasAggregateLLVMType(FT)) {
367       ExpandTypeToArgs(FT, RValue::getAggregate(LV.getAddress()), Args);
368     } else {
369       RValue RV = EmitLoadOfLValue(LV, FT);
370       assert(RV.isScalar() &&
371              "Unexpected non-scalar rvalue during struct expansion.");
372       Args.push_back(RV.getScalarVal());
373     }
374   }
375 }
376 
377 /// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
378 /// accessing some number of bytes out of it, try to gep into the struct to get
379 /// at its inner goodness.  Dive as deep as possible without entering an element
380 /// with an in-memory size smaller than DstSize.
381 static llvm::Value *
382 EnterStructPointerForCoercedAccess(llvm::Value *SrcPtr,
383                                    const llvm::StructType *SrcSTy,
384                                    uint64_t DstSize, CodeGenFunction &CGF) {
385   // We can't dive into a zero-element struct.
386   if (SrcSTy->getNumElements() == 0) return SrcPtr;
387 
388   const llvm::Type *FirstElt = SrcSTy->getElementType(0);
389 
390   // If the first elt is at least as large as what we're looking for, or if the
391   // first element is the same size as the whole struct, we can enter it.
392   uint64_t FirstEltSize =
393     CGF.CGM.getTargetData().getTypeAllocSize(FirstElt);
394   if (FirstEltSize < DstSize &&
395       FirstEltSize < CGF.CGM.getTargetData().getTypeAllocSize(SrcSTy))
396     return SrcPtr;
397 
398   // GEP into the first element.
399   SrcPtr = CGF.Builder.CreateConstGEP2_32(SrcPtr, 0, 0, "coerce.dive");
400 
401   // If the first element is a struct, recurse.
402   const llvm::Type *SrcTy =
403     cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
404   if (const llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
405     return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
406 
407   return SrcPtr;
408 }
409 
410 /// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
411 /// are either integers or pointers.  This does a truncation of the value if it
412 /// is too large or a zero extension if it is too small.
413 static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
414                                              const llvm::Type *Ty,
415                                              CodeGenFunction &CGF) {
416   if (Val->getType() == Ty)
417     return Val;
418 
419   if (isa<llvm::PointerType>(Val->getType())) {
420     // If this is Pointer->Pointer avoid conversion to and from int.
421     if (isa<llvm::PointerType>(Ty))
422       return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
423 
424     // Convert the pointer to an integer so we can play with its width.
425     Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
426   }
427 
428   const llvm::Type *DestIntTy = Ty;
429   if (isa<llvm::PointerType>(DestIntTy))
430     DestIntTy = CGF.IntPtrTy;
431 
432   if (Val->getType() != DestIntTy)
433     Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
434 
435   if (isa<llvm::PointerType>(Ty))
436     Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
437   return Val;
438 }
439 
440 
441 
442 /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
443 /// a pointer to an object of type \arg Ty.
444 ///
445 /// This safely handles the case when the src type is smaller than the
446 /// destination type; in this situation the values of bits which not
447 /// present in the src are undefined.
448 static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
449                                       const llvm::Type *Ty,
450                                       CodeGenFunction &CGF) {
451   const llvm::Type *SrcTy =
452     cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
453 
454   // If SrcTy and Ty are the same, just do a load.
455   if (SrcTy == Ty)
456     return CGF.Builder.CreateLoad(SrcPtr);
457 
458   uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(Ty);
459 
460   if (const llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
461     SrcPtr = EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
462     SrcTy = cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
463   }
464 
465   uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy);
466 
467   // If the source and destination are integer or pointer types, just do an
468   // extension or truncation to the desired type.
469   if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
470       (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
471     llvm::LoadInst *Load = CGF.Builder.CreateLoad(SrcPtr);
472     return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
473   }
474 
475   // If load is legal, just bitcast the src pointer.
476   if (SrcSize >= DstSize) {
477     // Generally SrcSize is never greater than DstSize, since this means we are
478     // losing bits. However, this can happen in cases where the structure has
479     // additional padding, for example due to a user specified alignment.
480     //
481     // FIXME: Assert that we aren't truncating non-padding bits when have access
482     // to that information.
483     llvm::Value *Casted =
484       CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
485     llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
486     // FIXME: Use better alignment / avoid requiring aligned load.
487     Load->setAlignment(1);
488     return Load;
489   }
490 
491   // Otherwise do coercion through memory. This is stupid, but
492   // simple.
493   llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
494   llvm::Value *Casted =
495     CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(SrcTy));
496   llvm::StoreInst *Store =
497     CGF.Builder.CreateStore(CGF.Builder.CreateLoad(SrcPtr), Casted);
498   // FIXME: Use better alignment / avoid requiring aligned store.
499   Store->setAlignment(1);
500   return CGF.Builder.CreateLoad(Tmp);
501 }
502 
503 /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
504 /// where the source and destination may have different types.
505 ///
506 /// This safely handles the case when the src type is larger than the
507 /// destination type; the upper bits of the src will be lost.
508 static void CreateCoercedStore(llvm::Value *Src,
509                                llvm::Value *DstPtr,
510                                bool DstIsVolatile,
511                                CodeGenFunction &CGF) {
512   const llvm::Type *SrcTy = Src->getType();
513   const llvm::Type *DstTy =
514     cast<llvm::PointerType>(DstPtr->getType())->getElementType();
515   if (SrcTy == DstTy) {
516     CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
517     return;
518   }
519 
520   uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy);
521 
522   if (const llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
523     DstPtr = EnterStructPointerForCoercedAccess(DstPtr, DstSTy, SrcSize, CGF);
524     DstTy = cast<llvm::PointerType>(DstPtr->getType())->getElementType();
525   }
526 
527   // If the source and destination are integer or pointer types, just do an
528   // extension or truncation to the desired type.
529   if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
530       (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
531     Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
532     CGF.Builder.CreateStore(Src, DstPtr, DstIsVolatile);
533     return;
534   }
535 
536   uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(DstTy);
537 
538   // If store is legal, just bitcast the src pointer.
539   if (SrcSize <= DstSize) {
540     llvm::Value *Casted =
541       CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
542     // FIXME: Use better alignment / avoid requiring aligned store.
543     CGF.Builder.CreateStore(Src, Casted, DstIsVolatile)->setAlignment(1);
544   } else {
545     // Otherwise do coercion through memory. This is stupid, but
546     // simple.
547 
548     // Generally SrcSize is never greater than DstSize, since this means we are
549     // losing bits. However, this can happen in cases where the structure has
550     // additional padding, for example due to a user specified alignment.
551     //
552     // FIXME: Assert that we aren't truncating non-padding bits when have access
553     // to that information.
554     llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
555     CGF.Builder.CreateStore(Src, Tmp);
556     llvm::Value *Casted =
557       CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(DstTy));
558     llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
559     // FIXME: Use better alignment / avoid requiring aligned load.
560     Load->setAlignment(1);
561     CGF.Builder.CreateStore(Load, DstPtr, DstIsVolatile);
562   }
563 }
564 
565 /***/
566 
567 bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
568   return FI.getReturnInfo().isIndirect();
569 }
570 
571 bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
572   if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
573     switch (BT->getKind()) {
574     default:
575       return false;
576     case BuiltinType::Float:
577       return getContext().Target.useObjCFPRetForRealType(TargetInfo::Float);
578     case BuiltinType::Double:
579       return getContext().Target.useObjCFPRetForRealType(TargetInfo::Double);
580     case BuiltinType::LongDouble:
581       return getContext().Target.useObjCFPRetForRealType(
582         TargetInfo::LongDouble);
583     }
584   }
585 
586   return false;
587 }
588 
589 const llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
590   const CGFunctionInfo &FI = getFunctionInfo(GD);
591 
592   // For definition purposes, don't consider a K&R function variadic.
593   bool Variadic = false;
594   if (const FunctionProtoType *FPT =
595         cast<FunctionDecl>(GD.getDecl())->getType()->getAs<FunctionProtoType>())
596     Variadic = FPT->isVariadic();
597 
598   return GetFunctionType(FI, Variadic, false);
599 }
600 
601 const llvm::FunctionType *
602 CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI, bool IsVariadic,
603                               bool IsRecursive) {
604   std::vector<const llvm::Type*> ArgTys;
605 
606   const llvm::Type *ResultType = 0;
607 
608   QualType RetTy = FI.getReturnType();
609   const ABIArgInfo &RetAI = FI.getReturnInfo();
610   switch (RetAI.getKind()) {
611   case ABIArgInfo::Expand:
612     assert(0 && "Invalid ABI kind for return argument");
613 
614   case ABIArgInfo::Extend:
615   case ABIArgInfo::Direct:
616     ResultType = ConvertType(RetTy, IsRecursive);
617     break;
618 
619   case ABIArgInfo::Indirect: {
620     assert(!RetAI.getIndirectAlign() && "Align unused on indirect return.");
621     ResultType = llvm::Type::getVoidTy(getLLVMContext());
622     const llvm::Type *STy = ConvertType(RetTy, IsRecursive);
623     ArgTys.push_back(llvm::PointerType::get(STy, RetTy.getAddressSpace()));
624     break;
625   }
626 
627   case ABIArgInfo::Ignore:
628     ResultType = llvm::Type::getVoidTy(getLLVMContext());
629     break;
630 
631   case ABIArgInfo::Coerce:
632     ResultType = RetAI.getCoerceToType();
633     break;
634   }
635 
636   for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
637          ie = FI.arg_end(); it != ie; ++it) {
638     const ABIArgInfo &AI = it->info;
639 
640     switch (AI.getKind()) {
641     case ABIArgInfo::Ignore:
642       break;
643 
644     case ABIArgInfo::Coerce: {
645       // If the coerce-to type is a first class aggregate, flatten it.  Either
646       // way is semantically identical, but fast-isel and the optimizer
647       // generally likes scalar values better than FCAs.
648       const llvm::Type *ArgTy = AI.getCoerceToType();
649       if (const llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgTy)) {
650         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
651           ArgTys.push_back(STy->getElementType(i));
652       } else {
653         ArgTys.push_back(ArgTy);
654       }
655       break;
656     }
657 
658     case ABIArgInfo::Indirect: {
659       // indirect arguments are always on the stack, which is addr space #0.
660       const llvm::Type *LTy = ConvertTypeForMem(it->type, IsRecursive);
661       ArgTys.push_back(llvm::PointerType::getUnqual(LTy));
662       break;
663     }
664 
665     case ABIArgInfo::Extend:
666     case ABIArgInfo::Direct:
667       ArgTys.push_back(ConvertType(it->type, IsRecursive));
668       break;
669 
670     case ABIArgInfo::Expand:
671       GetExpandedTypes(it->type, ArgTys, IsRecursive);
672       break;
673     }
674   }
675 
676   return llvm::FunctionType::get(ResultType, ArgTys, IsVariadic);
677 }
678 
679 const llvm::Type *
680 CodeGenTypes::GetFunctionTypeForVTable(const CXXMethodDecl *MD) {
681   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
682 
683   if (!VerifyFuncTypeComplete(FPT))
684     return GetFunctionType(getFunctionInfo(MD), FPT->isVariadic(), false);
685 
686   return llvm::OpaqueType::get(getLLVMContext());
687 }
688 
689 void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
690                                            const Decl *TargetDecl,
691                                            AttributeListType &PAL,
692                                            unsigned &CallingConv) {
693   unsigned FuncAttrs = 0;
694   unsigned RetAttrs = 0;
695 
696   CallingConv = FI.getEffectiveCallingConvention();
697 
698   if (FI.isNoReturn())
699     FuncAttrs |= llvm::Attribute::NoReturn;
700 
701   // FIXME: handle sseregparm someday...
702   if (TargetDecl) {
703     if (TargetDecl->hasAttr<NoThrowAttr>())
704       FuncAttrs |= llvm::Attribute::NoUnwind;
705     else if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
706       const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
707       if (FPT && FPT->hasEmptyExceptionSpec())
708         FuncAttrs |= llvm::Attribute::NoUnwind;
709     }
710 
711     if (TargetDecl->hasAttr<NoReturnAttr>())
712       FuncAttrs |= llvm::Attribute::NoReturn;
713     if (TargetDecl->hasAttr<ConstAttr>())
714       FuncAttrs |= llvm::Attribute::ReadNone;
715     else if (TargetDecl->hasAttr<PureAttr>())
716       FuncAttrs |= llvm::Attribute::ReadOnly;
717     if (TargetDecl->hasAttr<MallocAttr>())
718       RetAttrs |= llvm::Attribute::NoAlias;
719   }
720 
721   if (CodeGenOpts.OptimizeSize)
722     FuncAttrs |= llvm::Attribute::OptimizeForSize;
723   if (CodeGenOpts.DisableRedZone)
724     FuncAttrs |= llvm::Attribute::NoRedZone;
725   if (CodeGenOpts.NoImplicitFloat)
726     FuncAttrs |= llvm::Attribute::NoImplicitFloat;
727 
728   QualType RetTy = FI.getReturnType();
729   unsigned Index = 1;
730   const ABIArgInfo &RetAI = FI.getReturnInfo();
731   switch (RetAI.getKind()) {
732   case ABIArgInfo::Extend:
733    if (RetTy->isSignedIntegerType()) {
734      RetAttrs |= llvm::Attribute::SExt;
735    } else if (RetTy->isUnsignedIntegerType()) {
736      RetAttrs |= llvm::Attribute::ZExt;
737    }
738    // FALLTHROUGH
739   case ABIArgInfo::Direct:
740     break;
741 
742   case ABIArgInfo::Indirect:
743     PAL.push_back(llvm::AttributeWithIndex::get(Index,
744                                                 llvm::Attribute::StructRet));
745     ++Index;
746     // sret disables readnone and readonly
747     FuncAttrs &= ~(llvm::Attribute::ReadOnly |
748                    llvm::Attribute::ReadNone);
749     break;
750 
751   case ABIArgInfo::Ignore:
752   case ABIArgInfo::Coerce:
753     break;
754 
755   case ABIArgInfo::Expand:
756     assert(0 && "Invalid ABI kind for return argument");
757   }
758 
759   if (RetAttrs)
760     PAL.push_back(llvm::AttributeWithIndex::get(0, RetAttrs));
761 
762   // FIXME: we need to honour command line settings also...
763   // FIXME: RegParm should be reduced in case of nested functions and/or global
764   // register variable.
765   signed RegParm = FI.getRegParm();
766 
767   unsigned PointerWidth = getContext().Target.getPointerWidth(0);
768   for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
769          ie = FI.arg_end(); it != ie; ++it) {
770     QualType ParamType = it->type;
771     const ABIArgInfo &AI = it->info;
772     unsigned Attributes = 0;
773 
774     // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
775     // have the corresponding parameter variable.  It doesn't make
776     // sense to do it here because parameters are so fucked up.
777 
778     switch (AI.getKind()) {
779     case ABIArgInfo::Coerce:
780       if (const llvm::StructType *STy =
781           dyn_cast<llvm::StructType>(AI.getCoerceToType()))
782         Index += STy->getNumElements();
783       else
784         ++Index;
785       continue;  // Skip index increment.
786 
787     case ABIArgInfo::Indirect:
788       if (AI.getIndirectByVal())
789         Attributes |= llvm::Attribute::ByVal;
790 
791       Attributes |=
792         llvm::Attribute::constructAlignmentFromInt(AI.getIndirectAlign());
793       // byval disables readnone and readonly.
794       FuncAttrs &= ~(llvm::Attribute::ReadOnly |
795                      llvm::Attribute::ReadNone);
796       break;
797 
798     case ABIArgInfo::Extend:
799      if (ParamType->isSignedIntegerType()) {
800        Attributes |= llvm::Attribute::SExt;
801      } else if (ParamType->isUnsignedIntegerType()) {
802        Attributes |= llvm::Attribute::ZExt;
803      }
804      // FALLS THROUGH
805     case ABIArgInfo::Direct:
806       if (RegParm > 0 &&
807           (ParamType->isIntegerType() || ParamType->isPointerType())) {
808         RegParm -=
809           (Context.getTypeSize(ParamType) + PointerWidth - 1) / PointerWidth;
810         if (RegParm >= 0)
811           Attributes |= llvm::Attribute::InReg;
812       }
813       // FIXME: handle sseregparm someday...
814       break;
815 
816     case ABIArgInfo::Ignore:
817       // Skip increment, no matching LLVM parameter.
818       continue;
819 
820     case ABIArgInfo::Expand: {
821       std::vector<const llvm::Type*> Tys;
822       // FIXME: This is rather inefficient. Do we ever actually need to do
823       // anything here? The result should be just reconstructed on the other
824       // side, so extension should be a non-issue.
825       getTypes().GetExpandedTypes(ParamType, Tys, false);
826       Index += Tys.size();
827       continue;
828     }
829     }
830 
831     if (Attributes)
832       PAL.push_back(llvm::AttributeWithIndex::get(Index, Attributes));
833     ++Index;
834   }
835   if (FuncAttrs)
836     PAL.push_back(llvm::AttributeWithIndex::get(~0, FuncAttrs));
837 }
838 
839 void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
840                                          llvm::Function *Fn,
841                                          const FunctionArgList &Args) {
842   // If this is an implicit-return-zero function, go ahead and
843   // initialize the return value.  TODO: it might be nice to have
844   // a more general mechanism for this that didn't require synthesized
845   // return statements.
846   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
847     if (FD->hasImplicitReturnZero()) {
848       QualType RetTy = FD->getResultType().getUnqualifiedType();
849       const llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
850       llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
851       Builder.CreateStore(Zero, ReturnValue);
852     }
853   }
854 
855   // FIXME: We no longer need the types from FunctionArgList; lift up and
856   // simplify.
857 
858   // Emit allocs for param decls.  Give the LLVM Argument nodes names.
859   llvm::Function::arg_iterator AI = Fn->arg_begin();
860 
861   // Name the struct return argument.
862   if (CGM.ReturnTypeUsesSRet(FI)) {
863     AI->setName("agg.result");
864     ++AI;
865   }
866 
867   assert(FI.arg_size() == Args.size() &&
868          "Mismatch between function signature & arguments.");
869   CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
870   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
871        i != e; ++i, ++info_it) {
872     const VarDecl *Arg = i->first;
873     QualType Ty = info_it->type;
874     const ABIArgInfo &ArgI = info_it->info;
875 
876     switch (ArgI.getKind()) {
877     case ABIArgInfo::Indirect: {
878       llvm::Value *V = AI;
879       if (hasAggregateLLVMType(Ty)) {
880         // Do nothing, aggregates and complex variables are accessed by
881         // reference.
882       } else {
883         // Load scalar value from indirect argument.
884         V = EmitLoadOfScalar(V, false, Ty);
885         if (!getContext().typesAreCompatible(Ty, Arg->getType())) {
886           // This must be a promotion, for something like
887           // "void a(x) short x; {..."
888           V = EmitScalarConversion(V, Ty, Arg->getType());
889         }
890       }
891       EmitParmDecl(*Arg, V);
892       break;
893     }
894 
895     case ABIArgInfo::Extend:
896     case ABIArgInfo::Direct: {
897       assert(AI != Fn->arg_end() && "Argument mismatch!");
898       llvm::Value *V = AI;
899       if (hasAggregateLLVMType(Ty)) {
900         // Create a temporary alloca to hold the argument; the rest of
901         // codegen expects to access aggregates & complex values by
902         // reference.
903         V = CreateMemTemp(Ty);
904         Builder.CreateStore(AI, V);
905       } else {
906         if (Arg->getType().isRestrictQualified())
907           AI->addAttr(llvm::Attribute::NoAlias);
908 
909         if (!getContext().typesAreCompatible(Ty, Arg->getType())) {
910           // This must be a promotion, for something like
911           // "void a(x) short x; {..."
912           V = EmitScalarConversion(V, Ty, Arg->getType());
913         }
914       }
915       EmitParmDecl(*Arg, V);
916       break;
917     }
918 
919     case ABIArgInfo::Expand: {
920       // If this structure was expanded into multiple arguments then
921       // we need to create a temporary and reconstruct it from the
922       // arguments.
923       llvm::Value *Temp = CreateMemTemp(Ty, Arg->getName() + ".addr");
924       // FIXME: What are the right qualifiers here?
925       llvm::Function::arg_iterator End =
926         ExpandTypeFromArgs(Ty, LValue::MakeAddr(Temp, Qualifiers()), AI);
927       EmitParmDecl(*Arg, Temp);
928 
929       // Name the arguments used in expansion and increment AI.
930       unsigned Index = 0;
931       for (; AI != End; ++AI, ++Index)
932         AI->setName(Arg->getName() + "." + llvm::Twine(Index));
933       continue;
934     }
935 
936     case ABIArgInfo::Ignore:
937       // Initialize the local variable appropriately.
938       if (hasAggregateLLVMType(Ty)) {
939         EmitParmDecl(*Arg, CreateMemTemp(Ty));
940       } else {
941         EmitParmDecl(*Arg, llvm::UndefValue::get(ConvertType(Arg->getType())));
942       }
943 
944       // Skip increment, no matching LLVM parameter.
945       continue;
946 
947     case ABIArgInfo::Coerce: {
948       // FIXME: This is very wasteful; EmitParmDecl is just going to drop the
949       // result in a new alloca anyway, so we could just store into that
950       // directly if we broke the abstraction down more.
951       llvm::AllocaInst *Alloca = CreateMemTemp(Ty, "coerce");
952       Alloca->setAlignment(getContext().getDeclAlign(Arg).getQuantity());
953       llvm::Value *V = Alloca;
954 
955       // If the coerce-to type is a first class aggregate, we flatten it and
956       // pass the elements. Either way is semantically identical, but fast-isel
957       // and the optimizer generally likes scalar values better than FCAs.
958       if (const llvm::StructType *STy =
959             dyn_cast<llvm::StructType>(ArgI.getCoerceToType())) {
960         llvm::Value *Ptr = V;
961         Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
962 
963         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
964           assert(AI != Fn->arg_end() && "Argument mismatch!");
965           AI->setName(Arg->getName() + ".coerce" + llvm::Twine(i));
966           llvm::Value *EltPtr = Builder.CreateConstGEP2_32(Ptr, 0, i);
967           Builder.CreateStore(AI++, EltPtr);
968         }
969       } else {
970         // Simple case, just do a coerced store of the argument into the alloca.
971         assert(AI != Fn->arg_end() && "Argument mismatch!");
972         AI->setName(Arg->getName() + ".coerce");
973         CreateCoercedStore(AI++, V, /*DestIsVolatile=*/false, *this);
974       }
975 
976 
977       // Match to what EmitParmDecl is expecting for this type.
978       if (!CodeGenFunction::hasAggregateLLVMType(Ty)) {
979         V = EmitLoadOfScalar(V, false, Ty);
980         if (!getContext().typesAreCompatible(Ty, Arg->getType())) {
981           // This must be a promotion, for something like
982           // "void a(x) short x; {..."
983           V = EmitScalarConversion(V, Ty, Arg->getType());
984         }
985       }
986       EmitParmDecl(*Arg, V);
987       continue;  // Skip ++AI increment, already done.
988     }
989     }
990 
991     ++AI;
992   }
993   assert(AI == Fn->arg_end() && "Argument mismatch!");
994 }
995 
996 void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI) {
997   // Functions with no result always return void.
998   if (ReturnValue == 0) {
999     Builder.CreateRetVoid();
1000     return;
1001   }
1002 
1003   llvm::MDNode *RetDbgInfo = 0;
1004   llvm::Value *RV = 0;
1005   QualType RetTy = FI.getReturnType();
1006   const ABIArgInfo &RetAI = FI.getReturnInfo();
1007 
1008   switch (RetAI.getKind()) {
1009   case ABIArgInfo::Indirect:
1010     if (RetTy->isAnyComplexType()) {
1011       ComplexPairTy RT = LoadComplexFromAddr(ReturnValue, false);
1012       StoreComplexToAddr(RT, CurFn->arg_begin(), false);
1013     } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1014       // Do nothing; aggregrates get evaluated directly into the destination.
1015     } else {
1016       EmitStoreOfScalar(Builder.CreateLoad(ReturnValue), CurFn->arg_begin(),
1017                         false, RetTy);
1018     }
1019     break;
1020 
1021   case ABIArgInfo::Extend:
1022   case ABIArgInfo::Direct: {
1023     // The internal return value temp always will have pointer-to-return-type
1024     // type, just do a load.
1025 
1026     // If the instruction right before the insertion point is a store to the
1027     // return value, we can elide the load, zap the store, and usually zap the
1028     // alloca.
1029     llvm::BasicBlock *InsertBB = Builder.GetInsertBlock();
1030     llvm::StoreInst *SI = 0;
1031     if (InsertBB->empty() ||
1032         !(SI = dyn_cast<llvm::StoreInst>(&InsertBB->back())) ||
1033         SI->getPointerOperand() != ReturnValue || SI->isVolatile()) {
1034       RV = Builder.CreateLoad(ReturnValue);
1035     } else {
1036       // Get the stored value and nuke the now-dead store.
1037       RetDbgInfo = SI->getDbgMetadata();
1038       RV = SI->getValueOperand();
1039       SI->eraseFromParent();
1040 
1041       // If that was the only use of the return value, nuke it as well now.
1042       if (ReturnValue->use_empty() && isa<llvm::AllocaInst>(ReturnValue)) {
1043         cast<llvm::AllocaInst>(ReturnValue)->eraseFromParent();
1044         ReturnValue = 0;
1045       }
1046     }
1047     break;
1048   }
1049   case ABIArgInfo::Ignore:
1050     break;
1051 
1052   case ABIArgInfo::Coerce:
1053     RV = CreateCoercedLoad(ReturnValue, RetAI.getCoerceToType(), *this);
1054     break;
1055 
1056   case ABIArgInfo::Expand:
1057     assert(0 && "Invalid ABI kind for return argument");
1058   }
1059 
1060   llvm::Instruction *Ret = RV ? Builder.CreateRet(RV) : Builder.CreateRetVoid();
1061   if (RetDbgInfo)
1062     Ret->setDbgMetadata(RetDbgInfo);
1063 }
1064 
1065 RValue CodeGenFunction::EmitDelegateCallArg(const VarDecl *Param) {
1066   // StartFunction converted the ABI-lowered parameter(s) into a
1067   // local alloca.  We need to turn that into an r-value suitable
1068   // for EmitCall.
1069   llvm::Value *Local = GetAddrOfLocalVar(Param);
1070 
1071   QualType ArgType = Param->getType();
1072 
1073   // For the most part, we just need to load the alloca, except:
1074   // 1) aggregate r-values are actually pointers to temporaries, and
1075   // 2) references to aggregates are pointers directly to the aggregate.
1076   // I don't know why references to non-aggregates are different here.
1077   if (const ReferenceType *RefType = ArgType->getAs<ReferenceType>()) {
1078     if (hasAggregateLLVMType(RefType->getPointeeType()))
1079       return RValue::getAggregate(Local);
1080 
1081     // Locals which are references to scalars are represented
1082     // with allocas holding the pointer.
1083     return RValue::get(Builder.CreateLoad(Local));
1084   }
1085 
1086   if (ArgType->isAnyComplexType())
1087     return RValue::getComplex(LoadComplexFromAddr(Local, /*volatile*/ false));
1088 
1089   if (hasAggregateLLVMType(ArgType))
1090     return RValue::getAggregate(Local);
1091 
1092   return RValue::get(EmitLoadOfScalar(Local, false, ArgType));
1093 }
1094 
1095 RValue CodeGenFunction::EmitCallArg(const Expr *E, QualType ArgType) {
1096   if (ArgType->isReferenceType())
1097     return EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
1098 
1099   return EmitAnyExprToTemp(E);
1100 }
1101 
1102 /// Emits a call or invoke instruction to the given function, depending
1103 /// on the current state of the EH stack.
1104 llvm::CallSite
1105 CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
1106                                   llvm::Value * const *ArgBegin,
1107                                   llvm::Value * const *ArgEnd,
1108                                   const llvm::Twine &Name) {
1109   llvm::BasicBlock *InvokeDest = getInvokeDest();
1110   if (!InvokeDest)
1111     return Builder.CreateCall(Callee, ArgBegin, ArgEnd, Name);
1112 
1113   llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
1114   llvm::InvokeInst *Invoke = Builder.CreateInvoke(Callee, ContBB, InvokeDest,
1115                                                   ArgBegin, ArgEnd, Name);
1116   EmitBlock(ContBB);
1117   return Invoke;
1118 }
1119 
1120 RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
1121                                  llvm::Value *Callee,
1122                                  ReturnValueSlot ReturnValue,
1123                                  const CallArgList &CallArgs,
1124                                  const Decl *TargetDecl,
1125                                  llvm::Instruction **callOrInvoke) {
1126   // FIXME: We no longer need the types from CallArgs; lift up and simplify.
1127   llvm::SmallVector<llvm::Value*, 16> Args;
1128 
1129   // Handle struct-return functions by passing a pointer to the
1130   // location that we would like to return into.
1131   QualType RetTy = CallInfo.getReturnType();
1132   const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
1133 
1134 
1135   // If the call returns a temporary with struct return, create a temporary
1136   // alloca to hold the result, unless one is given to us.
1137   if (CGM.ReturnTypeUsesSRet(CallInfo)) {
1138     llvm::Value *Value = ReturnValue.getValue();
1139     if (!Value)
1140       Value = CreateMemTemp(RetTy);
1141     Args.push_back(Value);
1142   }
1143 
1144   assert(CallInfo.arg_size() == CallArgs.size() &&
1145          "Mismatch between function signature & arguments.");
1146   CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
1147   for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
1148        I != E; ++I, ++info_it) {
1149     const ABIArgInfo &ArgInfo = info_it->info;
1150     RValue RV = I->first;
1151 
1152     switch (ArgInfo.getKind()) {
1153     case ABIArgInfo::Indirect:
1154       if (RV.isScalar() || RV.isComplex()) {
1155         // Make a temporary alloca to pass the argument.
1156         Args.push_back(CreateMemTemp(I->second));
1157         if (RV.isScalar())
1158           EmitStoreOfScalar(RV.getScalarVal(), Args.back(), false, I->second);
1159         else
1160           StoreComplexToAddr(RV.getComplexVal(), Args.back(), false);
1161       } else {
1162         Args.push_back(RV.getAggregateAddr());
1163       }
1164       break;
1165 
1166     case ABIArgInfo::Extend:
1167     case ABIArgInfo::Direct:
1168       if (RV.isScalar()) {
1169         Args.push_back(RV.getScalarVal());
1170       } else if (RV.isComplex()) {
1171         llvm::Value *Tmp = llvm::UndefValue::get(ConvertType(I->second));
1172         Tmp = Builder.CreateInsertValue(Tmp, RV.getComplexVal().first, 0);
1173         Tmp = Builder.CreateInsertValue(Tmp, RV.getComplexVal().second, 1);
1174         Args.push_back(Tmp);
1175       } else {
1176         Args.push_back(Builder.CreateLoad(RV.getAggregateAddr()));
1177       }
1178       break;
1179 
1180     case ABIArgInfo::Ignore:
1181       break;
1182 
1183     case ABIArgInfo::Coerce: {
1184       // FIXME: Avoid the conversion through memory if possible.
1185       llvm::Value *SrcPtr;
1186       if (RV.isScalar()) {
1187         SrcPtr = CreateMemTemp(I->second, "coerce");
1188         EmitStoreOfScalar(RV.getScalarVal(), SrcPtr, false, I->second);
1189       } else if (RV.isComplex()) {
1190         SrcPtr = CreateMemTemp(I->second, "coerce");
1191         StoreComplexToAddr(RV.getComplexVal(), SrcPtr, false);
1192       } else
1193         SrcPtr = RV.getAggregateAddr();
1194 
1195       // If the coerce-to type is a first class aggregate, we flatten it and
1196       // pass the elements. Either way is semantically identical, but fast-isel
1197       // and the optimizer generally likes scalar values better than FCAs.
1198       if (const llvm::StructType *STy =
1199             dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType())) {
1200         SrcPtr = Builder.CreateBitCast(SrcPtr,
1201                                        llvm::PointerType::getUnqual(STy));
1202         for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1203           llvm::Value *EltPtr = Builder.CreateConstGEP2_32(SrcPtr, 0, i);
1204           Args.push_back(Builder.CreateLoad(EltPtr));
1205         }
1206       } else {
1207         // In the simple case, just pass the coerced loaded value.
1208         Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
1209                                          *this));
1210       }
1211 
1212       break;
1213     }
1214 
1215     case ABIArgInfo::Expand:
1216       ExpandTypeToArgs(I->second, RV, Args);
1217       break;
1218     }
1219   }
1220 
1221   // If the callee is a bitcast of a function to a varargs pointer to function
1222   // type, check to see if we can remove the bitcast.  This handles some cases
1223   // with unprototyped functions.
1224   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
1225     if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
1226       const llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
1227       const llvm::FunctionType *CurFT =
1228         cast<llvm::FunctionType>(CurPT->getElementType());
1229       const llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
1230 
1231       if (CE->getOpcode() == llvm::Instruction::BitCast &&
1232           ActualFT->getReturnType() == CurFT->getReturnType() &&
1233           ActualFT->getNumParams() == CurFT->getNumParams() &&
1234           ActualFT->getNumParams() == Args.size()) {
1235         bool ArgsMatch = true;
1236         for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
1237           if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
1238             ArgsMatch = false;
1239             break;
1240           }
1241 
1242         // Strip the cast if we can get away with it.  This is a nice cleanup,
1243         // but also allows us to inline the function at -O0 if it is marked
1244         // always_inline.
1245         if (ArgsMatch)
1246           Callee = CalleeF;
1247       }
1248     }
1249 
1250 
1251   unsigned CallingConv;
1252   CodeGen::AttributeListType AttributeList;
1253   CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList, CallingConv);
1254   llvm::AttrListPtr Attrs = llvm::AttrListPtr::get(AttributeList.begin(),
1255                                                    AttributeList.end());
1256 
1257   llvm::BasicBlock *InvokeDest = 0;
1258   if (!(Attrs.getFnAttributes() & llvm::Attribute::NoUnwind))
1259     InvokeDest = getInvokeDest();
1260 
1261   llvm::CallSite CS;
1262   if (!InvokeDest) {
1263     CS = Builder.CreateCall(Callee, Args.data(), Args.data()+Args.size());
1264   } else {
1265     llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
1266     CS = Builder.CreateInvoke(Callee, Cont, InvokeDest,
1267                               Args.data(), Args.data()+Args.size());
1268     EmitBlock(Cont);
1269   }
1270   if (callOrInvoke)
1271     *callOrInvoke = CS.getInstruction();
1272 
1273   CS.setAttributes(Attrs);
1274   CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
1275 
1276   // If the call doesn't return, finish the basic block and clear the
1277   // insertion point; this allows the rest of IRgen to discard
1278   // unreachable code.
1279   if (CS.doesNotReturn()) {
1280     Builder.CreateUnreachable();
1281     Builder.ClearInsertionPoint();
1282 
1283     // FIXME: For now, emit a dummy basic block because expr emitters in
1284     // generally are not ready to handle emitting expressions at unreachable
1285     // points.
1286     EnsureInsertPoint();
1287 
1288     // Return a reasonable RValue.
1289     return GetUndefRValue(RetTy);
1290   }
1291 
1292   llvm::Instruction *CI = CS.getInstruction();
1293   if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
1294     CI->setName("call");
1295 
1296   switch (RetAI.getKind()) {
1297   case ABIArgInfo::Indirect:
1298     if (RetTy->isAnyComplexType())
1299       return RValue::getComplex(LoadComplexFromAddr(Args[0], false));
1300     if (CodeGenFunction::hasAggregateLLVMType(RetTy))
1301       return RValue::getAggregate(Args[0]);
1302     return RValue::get(EmitLoadOfScalar(Args[0], false, RetTy));
1303 
1304   case ABIArgInfo::Extend:
1305   case ABIArgInfo::Direct:
1306     if (RetTy->isAnyComplexType()) {
1307       llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
1308       llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
1309       return RValue::getComplex(std::make_pair(Real, Imag));
1310     }
1311     if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1312       llvm::Value *DestPtr = ReturnValue.getValue();
1313       bool DestIsVolatile = ReturnValue.isVolatile();
1314 
1315       if (!DestPtr) {
1316         DestPtr = CreateMemTemp(RetTy, "agg.tmp");
1317         DestIsVolatile = false;
1318       }
1319       Builder.CreateStore(CI, DestPtr, DestIsVolatile);
1320       return RValue::getAggregate(DestPtr);
1321     }
1322     return RValue::get(CI);
1323 
1324   case ABIArgInfo::Ignore:
1325     // If we are ignoring an argument that had a result, make sure to
1326     // construct the appropriate return value for our caller.
1327     return GetUndefRValue(RetTy);
1328 
1329   case ABIArgInfo::Coerce: {
1330     llvm::Value *DestPtr = ReturnValue.getValue();
1331     bool DestIsVolatile = ReturnValue.isVolatile();
1332 
1333     if (!DestPtr) {
1334       DestPtr = CreateMemTemp(RetTy, "coerce");
1335       DestIsVolatile = false;
1336     }
1337 
1338     CreateCoercedStore(CI, DestPtr, DestIsVolatile, *this);
1339     if (RetTy->isAnyComplexType())
1340       return RValue::getComplex(LoadComplexFromAddr(DestPtr, false));
1341     if (CodeGenFunction::hasAggregateLLVMType(RetTy))
1342       return RValue::getAggregate(DestPtr);
1343     return RValue::get(EmitLoadOfScalar(DestPtr, false, RetTy));
1344   }
1345 
1346   case ABIArgInfo::Expand:
1347     assert(0 && "Invalid ABI kind for return argument");
1348   }
1349 
1350   assert(0 && "Unhandled ABIArgInfo::Kind");
1351   return RValue::get(0);
1352 }
1353 
1354 /* VarArg handling */
1355 
1356 llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
1357   return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
1358 }
1359