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 "CodeGenFunction.h"
17 #include "CodeGenModule.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/Frontend/CompileOptions.h"
23 #include "llvm/Attributes.h"
24 #include "llvm/Support/CallSite.h"
25 #include "llvm/Target/TargetData.h"
26 
27 #include "ABIInfo.h"
28 
29 using namespace clang;
30 using namespace CodeGen;
31 
32 /***/
33 
34 // FIXME: Use iterator and sidestep silly type array creation.
35 
36 const
37 CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionNoProtoType *FTNP) {
38   // FIXME: Set calling convention correctly, it needs to be associated with the
39   // type somehow.
40   return getFunctionInfo(FTNP->getResultType(),
41                          llvm::SmallVector<QualType, 16>(), 0);
42 }
43 
44 const
45 CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionProtoType *FTP) {
46   llvm::SmallVector<QualType, 16> ArgTys;
47   // FIXME: Kill copy.
48   for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
49     ArgTys.push_back(FTP->getArgType(i));
50   // FIXME: Set calling convention correctly, it needs to be associated with the
51   // type somehow.
52   return getFunctionInfo(FTP->getResultType(), ArgTys, 0);
53 }
54 
55 static unsigned getCallingConventionForDecl(const Decl *D) {
56   // Set the appropriate calling convention for the Function.
57   if (D->hasAttr<StdCallAttr>())
58     return llvm::CallingConv::X86_StdCall;
59 
60   if (D->hasAttr<FastCallAttr>())
61     return llvm::CallingConv::X86_FastCall;
62 
63   return llvm::CallingConv::C;
64 }
65 
66 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const CXXMethodDecl *MD) {
67   llvm::SmallVector<QualType, 16> ArgTys;
68   // Add the 'this' pointer unless this is a static method.
69   if (MD->isInstance())
70     ArgTys.push_back(MD->getThisType(Context));
71 
72   const FunctionProtoType *FTP = MD->getType()->getAsFunctionProtoType();
73   for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
74     ArgTys.push_back(FTP->getArgType(i));
75   return getFunctionInfo(FTP->getResultType(), ArgTys,
76                          getCallingConventionForDecl(MD));
77 }
78 
79 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const FunctionDecl *FD) {
80   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
81     if (MD->isInstance())
82       return getFunctionInfo(MD);
83 
84   unsigned CallingConvention = getCallingConventionForDecl(FD);
85   const FunctionType *FTy = FD->getType()->getAsFunctionType();
86   if (const FunctionNoProtoType *FNTP = dyn_cast<FunctionNoProtoType>(FTy))
87     return getFunctionInfo(FNTP->getResultType(),
88                            llvm::SmallVector<QualType, 16>(),
89                            CallingConvention);
90 
91   const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
92   llvm::SmallVector<QualType, 16> ArgTys;
93   // FIXME: Kill copy.
94   for (unsigned i = 0, e = FPT->getNumArgs(); i != e; ++i)
95     ArgTys.push_back(FPT->getArgType(i));
96   return getFunctionInfo(FPT->getResultType(), ArgTys, CallingConvention);
97 }
98 
99 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(const ObjCMethodDecl *MD) {
100   llvm::SmallVector<QualType, 16> ArgTys;
101   ArgTys.push_back(MD->getSelfDecl()->getType());
102   ArgTys.push_back(Context.getObjCSelType());
103   // FIXME: Kill copy?
104   for (ObjCMethodDecl::param_iterator i = MD->param_begin(),
105          e = MD->param_end(); i != e; ++i)
106     ArgTys.push_back((*i)->getType());
107   return getFunctionInfo(MD->getResultType(), ArgTys,
108                          getCallingConventionForDecl(MD));
109 }
110 
111 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
112                                                     const CallArgList &Args,
113                                                     unsigned CallingConvention){
114   // FIXME: Kill copy.
115   llvm::SmallVector<QualType, 16> ArgTys;
116   for (CallArgList::const_iterator i = Args.begin(), e = Args.end();
117        i != e; ++i)
118     ArgTys.push_back(i->second);
119   return getFunctionInfo(ResTy, ArgTys, CallingConvention);
120 }
121 
122 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
123                                                     const FunctionArgList &Args,
124                                                     unsigned CallingConvention){
125   // FIXME: Kill copy.
126   llvm::SmallVector<QualType, 16> ArgTys;
127   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
128        i != e; ++i)
129     ArgTys.push_back(i->second);
130   return getFunctionInfo(ResTy, ArgTys, CallingConvention);
131 }
132 
133 const CGFunctionInfo &CodeGenTypes::getFunctionInfo(QualType ResTy,
134                                   const llvm::SmallVector<QualType, 16> &ArgTys,
135                                                     unsigned CallingConvention){
136   // Lookup or create unique function info.
137   llvm::FoldingSetNodeID ID;
138   CGFunctionInfo::Profile(ID, CallingConvention, ResTy,
139                           ArgTys.begin(), ArgTys.end());
140 
141   void *InsertPos = 0;
142   CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, InsertPos);
143   if (FI)
144     return *FI;
145 
146   // Construct the function info.
147   FI = new CGFunctionInfo(CallingConvention, ResTy, ArgTys);
148   FunctionInfos.InsertNode(FI, InsertPos);
149 
150   // Compute ABI information.
151   getABIInfo().computeInfo(*FI, getContext(), TheModule.getContext());
152 
153   return *FI;
154 }
155 
156 CGFunctionInfo::CGFunctionInfo(unsigned _CallingConvention,
157                                QualType ResTy,
158                                const llvm::SmallVector<QualType, 16> &ArgTys)
159   : CallingConvention(_CallingConvention),
160     EffectiveCallingConvention(_CallingConvention)
161 {
162   NumArgs = ArgTys.size();
163   Args = new ArgInfo[1 + NumArgs];
164   Args[0].type = ResTy;
165   for (unsigned i = 0; i < NumArgs; ++i)
166     Args[1 + i].type = ArgTys[i];
167 }
168 
169 /***/
170 
171 void CodeGenTypes::GetExpandedTypes(QualType Ty,
172                                     std::vector<const llvm::Type*> &ArgTys) {
173   const RecordType *RT = Ty->getAsStructureType();
174   assert(RT && "Can only expand structure types.");
175   const RecordDecl *RD = RT->getDecl();
176   assert(!RD->hasFlexibleArrayMember() &&
177          "Cannot expand structure with flexible array.");
178 
179   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
180          i != e; ++i) {
181     const FieldDecl *FD = *i;
182     assert(!FD->isBitField() &&
183            "Cannot expand structure with bit-field members.");
184 
185     QualType FT = FD->getType();
186     if (CodeGenFunction::hasAggregateLLVMType(FT)) {
187       GetExpandedTypes(FT, ArgTys);
188     } else {
189       ArgTys.push_back(ConvertType(FT));
190     }
191   }
192 }
193 
194 llvm::Function::arg_iterator
195 CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
196                                     llvm::Function::arg_iterator AI) {
197   const RecordType *RT = Ty->getAsStructureType();
198   assert(RT && "Can only expand structure types.");
199 
200   RecordDecl *RD = RT->getDecl();
201   assert(LV.isSimple() &&
202          "Unexpected non-simple lvalue during struct expansion.");
203   llvm::Value *Addr = LV.getAddress();
204   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
205          i != e; ++i) {
206     FieldDecl *FD = *i;
207     QualType FT = FD->getType();
208 
209     // FIXME: What are the right qualifiers here?
210     LValue LV = EmitLValueForField(Addr, FD, false, 0);
211     if (CodeGenFunction::hasAggregateLLVMType(FT)) {
212       AI = ExpandTypeFromArgs(FT, LV, AI);
213     } else {
214       EmitStoreThroughLValue(RValue::get(AI), LV, FT);
215       ++AI;
216     }
217   }
218 
219   return AI;
220 }
221 
222 void
223 CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
224                                   llvm::SmallVector<llvm::Value*, 16> &Args) {
225   const RecordType *RT = Ty->getAsStructureType();
226   assert(RT && "Can only expand structure types.");
227 
228   RecordDecl *RD = RT->getDecl();
229   assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
230   llvm::Value *Addr = RV.getAggregateAddr();
231   for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
232          i != e; ++i) {
233     FieldDecl *FD = *i;
234     QualType FT = FD->getType();
235 
236     // FIXME: What are the right qualifiers here?
237     LValue LV = EmitLValueForField(Addr, FD, false, 0);
238     if (CodeGenFunction::hasAggregateLLVMType(FT)) {
239       ExpandTypeToArgs(FT, RValue::getAggregate(LV.getAddress()), Args);
240     } else {
241       RValue RV = EmitLoadOfLValue(LV, FT);
242       assert(RV.isScalar() &&
243              "Unexpected non-scalar rvalue during struct expansion.");
244       Args.push_back(RV.getScalarVal());
245     }
246   }
247 }
248 
249 /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
250 /// a pointer to an object of type \arg Ty.
251 ///
252 /// This safely handles the case when the src type is smaller than the
253 /// destination type; in this situation the values of bits which not
254 /// present in the src are undefined.
255 static llvm::Value *CreateCoercedLoad(llvm::Value *SrcPtr,
256                                       const llvm::Type *Ty,
257                                       CodeGenFunction &CGF) {
258   const llvm::Type *SrcTy =
259     cast<llvm::PointerType>(SrcPtr->getType())->getElementType();
260   uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy);
261   uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(Ty);
262 
263   // If load is legal, just bitcast the src pointer.
264   if (SrcSize >= DstSize) {
265     // Generally SrcSize is never greater than DstSize, since this means we are
266     // losing bits. However, this can happen in cases where the structure has
267     // additional padding, for example due to a user specified alignment.
268     //
269     // FIXME: Assert that we aren't truncating non-padding bits when have access
270     // to that information.
271     llvm::Value *Casted =
272       CGF.Builder.CreateBitCast(SrcPtr, llvm::PointerType::getUnqual(Ty));
273     llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
274     // FIXME: Use better alignment / avoid requiring aligned load.
275     Load->setAlignment(1);
276     return Load;
277   } else {
278     // Otherwise do coercion through memory. This is stupid, but
279     // simple.
280     llvm::Value *Tmp = CGF.CreateTempAlloca(Ty);
281     llvm::Value *Casted =
282       CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(SrcTy));
283     llvm::StoreInst *Store =
284       CGF.Builder.CreateStore(CGF.Builder.CreateLoad(SrcPtr), Casted);
285     // FIXME: Use better alignment / avoid requiring aligned store.
286     Store->setAlignment(1);
287     return CGF.Builder.CreateLoad(Tmp);
288   }
289 }
290 
291 /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
292 /// where the source and destination may have different types.
293 ///
294 /// This safely handles the case when the src type is larger than the
295 /// destination type; the upper bits of the src will be lost.
296 static void CreateCoercedStore(llvm::Value *Src,
297                                llvm::Value *DstPtr,
298                                CodeGenFunction &CGF) {
299   const llvm::Type *SrcTy = Src->getType();
300   const llvm::Type *DstTy =
301     cast<llvm::PointerType>(DstPtr->getType())->getElementType();
302 
303   uint64_t SrcSize = CGF.CGM.getTargetData().getTypeAllocSize(SrcTy);
304   uint64_t DstSize = CGF.CGM.getTargetData().getTypeAllocSize(DstTy);
305 
306   // If store is legal, just bitcast the src pointer.
307   if (SrcSize <= DstSize) {
308     llvm::Value *Casted =
309       CGF.Builder.CreateBitCast(DstPtr, llvm::PointerType::getUnqual(SrcTy));
310     // FIXME: Use better alignment / avoid requiring aligned store.
311     CGF.Builder.CreateStore(Src, Casted)->setAlignment(1);
312   } else {
313     // Otherwise do coercion through memory. This is stupid, but
314     // simple.
315 
316     // Generally SrcSize is never greater than DstSize, since this means we are
317     // losing bits. However, this can happen in cases where the structure has
318     // additional padding, for example due to a user specified alignment.
319     //
320     // FIXME: Assert that we aren't truncating non-padding bits when have access
321     // to that information.
322     llvm::Value *Tmp = CGF.CreateTempAlloca(SrcTy);
323     CGF.Builder.CreateStore(Src, Tmp);
324     llvm::Value *Casted =
325       CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(DstTy));
326     llvm::LoadInst *Load = CGF.Builder.CreateLoad(Casted);
327     // FIXME: Use better alignment / avoid requiring aligned load.
328     Load->setAlignment(1);
329     CGF.Builder.CreateStore(Load, DstPtr);
330   }
331 }
332 
333 /***/
334 
335 bool CodeGenModule::ReturnTypeUsesSret(const CGFunctionInfo &FI) {
336   return FI.getReturnInfo().isIndirect();
337 }
338 
339 const llvm::FunctionType *
340 CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI, bool IsVariadic) {
341   std::vector<const llvm::Type*> ArgTys;
342 
343   const llvm::Type *ResultType = 0;
344 
345   QualType RetTy = FI.getReturnType();
346   const ABIArgInfo &RetAI = FI.getReturnInfo();
347   switch (RetAI.getKind()) {
348   case ABIArgInfo::Expand:
349     assert(0 && "Invalid ABI kind for return argument");
350 
351   case ABIArgInfo::Extend:
352   case ABIArgInfo::Direct:
353     ResultType = ConvertType(RetTy);
354     break;
355 
356   case ABIArgInfo::Indirect: {
357     assert(!RetAI.getIndirectAlign() && "Align unused on indirect return.");
358     ResultType = llvm::Type::getVoidTy(getLLVMContext());
359     const llvm::Type *STy = ConvertType(RetTy);
360     ArgTys.push_back(llvm::PointerType::get(STy, RetTy.getAddressSpace()));
361     break;
362   }
363 
364   case ABIArgInfo::Ignore:
365     ResultType = llvm::Type::getVoidTy(getLLVMContext());
366     break;
367 
368   case ABIArgInfo::Coerce:
369     ResultType = RetAI.getCoerceToType();
370     break;
371   }
372 
373   for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
374          ie = FI.arg_end(); it != ie; ++it) {
375     const ABIArgInfo &AI = it->info;
376 
377     switch (AI.getKind()) {
378     case ABIArgInfo::Ignore:
379       break;
380 
381     case ABIArgInfo::Coerce:
382       ArgTys.push_back(AI.getCoerceToType());
383       break;
384 
385     case ABIArgInfo::Indirect: {
386       // indirect arguments are always on the stack, which is addr space #0.
387       const llvm::Type *LTy = ConvertTypeForMem(it->type);
388       ArgTys.push_back(llvm::PointerType::getUnqual(LTy));
389       break;
390     }
391 
392     case ABIArgInfo::Extend:
393     case ABIArgInfo::Direct:
394       ArgTys.push_back(ConvertType(it->type));
395       break;
396 
397     case ABIArgInfo::Expand:
398       GetExpandedTypes(it->type, ArgTys);
399       break;
400     }
401   }
402 
403   return llvm::FunctionType::get(ResultType, ArgTys, IsVariadic);
404 }
405 
406 void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
407                                            const Decl *TargetDecl,
408                                            AttributeListType &PAL,
409                                            unsigned &CallingConv) {
410   unsigned FuncAttrs = 0;
411   unsigned RetAttrs = 0;
412 
413   CallingConv = FI.getEffectiveCallingConvention();
414 
415   // FIXME: handle sseregparm someday...
416   if (TargetDecl) {
417     if (TargetDecl->hasAttr<NoThrowAttr>())
418       FuncAttrs |= llvm::Attribute::NoUnwind;
419     if (TargetDecl->hasAttr<NoReturnAttr>())
420       FuncAttrs |= llvm::Attribute::NoReturn;
421     if (TargetDecl->hasAttr<ConstAttr>())
422       FuncAttrs |= llvm::Attribute::ReadNone;
423     else if (TargetDecl->hasAttr<PureAttr>())
424       FuncAttrs |= llvm::Attribute::ReadOnly;
425     if (TargetDecl->hasAttr<MallocAttr>())
426       RetAttrs |= llvm::Attribute::NoAlias;
427   }
428 
429   if (CompileOpts.DisableRedZone)
430     FuncAttrs |= llvm::Attribute::NoRedZone;
431   if (CompileOpts.NoImplicitFloat)
432     FuncAttrs |= llvm::Attribute::NoImplicitFloat;
433 
434   if (Features.getStackProtectorMode() == LangOptions::SSPOn)
435     FuncAttrs |= llvm::Attribute::StackProtect;
436   else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
437     FuncAttrs |= llvm::Attribute::StackProtectReq;
438 
439   QualType RetTy = FI.getReturnType();
440   unsigned Index = 1;
441   const ABIArgInfo &RetAI = FI.getReturnInfo();
442   switch (RetAI.getKind()) {
443   case ABIArgInfo::Extend:
444    if (RetTy->isSignedIntegerType()) {
445      RetAttrs |= llvm::Attribute::SExt;
446    } else if (RetTy->isUnsignedIntegerType()) {
447      RetAttrs |= llvm::Attribute::ZExt;
448    }
449    // FALLTHROUGH
450   case ABIArgInfo::Direct:
451     break;
452 
453   case ABIArgInfo::Indirect:
454     PAL.push_back(llvm::AttributeWithIndex::get(Index,
455                                                 llvm::Attribute::StructRet |
456                                                 llvm::Attribute::NoAlias));
457     ++Index;
458     // sret disables readnone and readonly
459     FuncAttrs &= ~(llvm::Attribute::ReadOnly |
460                    llvm::Attribute::ReadNone);
461     break;
462 
463   case ABIArgInfo::Ignore:
464   case ABIArgInfo::Coerce:
465     break;
466 
467   case ABIArgInfo::Expand:
468     assert(0 && "Invalid ABI kind for return argument");
469   }
470 
471   if (RetAttrs)
472     PAL.push_back(llvm::AttributeWithIndex::get(0, RetAttrs));
473 
474   // FIXME: we need to honour command line settings also...
475   // FIXME: RegParm should be reduced in case of nested functions and/or global
476   // register variable.
477   signed RegParm = 0;
478   if (TargetDecl)
479     if (const RegparmAttr *RegParmAttr
480           = TargetDecl->getAttr<RegparmAttr>())
481       RegParm = RegParmAttr->getNumParams();
482 
483   unsigned PointerWidth = getContext().Target.getPointerWidth(0);
484   for (CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
485          ie = FI.arg_end(); it != ie; ++it) {
486     QualType ParamType = it->type;
487     const ABIArgInfo &AI = it->info;
488     unsigned Attributes = 0;
489 
490     switch (AI.getKind()) {
491     case ABIArgInfo::Coerce:
492       break;
493 
494     case ABIArgInfo::Indirect:
495       Attributes |= llvm::Attribute::ByVal;
496       Attributes |=
497         llvm::Attribute::constructAlignmentFromInt(AI.getIndirectAlign());
498       // byval disables readnone and readonly.
499       FuncAttrs &= ~(llvm::Attribute::ReadOnly |
500                      llvm::Attribute::ReadNone);
501       break;
502 
503     case ABIArgInfo::Extend:
504      if (ParamType->isSignedIntegerType()) {
505        Attributes |= llvm::Attribute::SExt;
506      } else if (ParamType->isUnsignedIntegerType()) {
507        Attributes |= llvm::Attribute::ZExt;
508      }
509      // FALLS THROUGH
510     case ABIArgInfo::Direct:
511       if (RegParm > 0 &&
512           (ParamType->isIntegerType() || ParamType->isPointerType())) {
513         RegParm -=
514           (Context.getTypeSize(ParamType) + PointerWidth - 1) / PointerWidth;
515         if (RegParm >= 0)
516           Attributes |= llvm::Attribute::InReg;
517       }
518       // FIXME: handle sseregparm someday...
519       break;
520 
521     case ABIArgInfo::Ignore:
522       // Skip increment, no matching LLVM parameter.
523       continue;
524 
525     case ABIArgInfo::Expand: {
526       std::vector<const llvm::Type*> Tys;
527       // FIXME: This is rather inefficient. Do we ever actually need to do
528       // anything here? The result should be just reconstructed on the other
529       // side, so extension should be a non-issue.
530       getTypes().GetExpandedTypes(ParamType, Tys);
531       Index += Tys.size();
532       continue;
533     }
534     }
535 
536     if (Attributes)
537       PAL.push_back(llvm::AttributeWithIndex::get(Index, Attributes));
538     ++Index;
539   }
540   if (FuncAttrs)
541     PAL.push_back(llvm::AttributeWithIndex::get(~0, FuncAttrs));
542 }
543 
544 void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
545                                          llvm::Function *Fn,
546                                          const FunctionArgList &Args) {
547   // If this is an implicit-return-zero function, go ahead and
548   // initialize the return value.  TODO: it might be nice to have
549   // a more general mechanism for this that didn't require synthesized
550   // return statements.
551   if (const FunctionDecl* FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
552     if (FD->hasImplicitReturnZero()) {
553       QualType RetTy = FD->getResultType().getUnqualifiedType();
554       const llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
555       llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
556       Builder.CreateStore(Zero, ReturnValue);
557     }
558   }
559 
560   // FIXME: We no longer need the types from FunctionArgList; lift up and
561   // simplify.
562 
563   // Emit allocs for param decls.  Give the LLVM Argument nodes names.
564   llvm::Function::arg_iterator AI = Fn->arg_begin();
565 
566   // Name the struct return argument.
567   if (CGM.ReturnTypeUsesSret(FI)) {
568     AI->setName("agg.result");
569     ++AI;
570   }
571 
572   assert(FI.arg_size() == Args.size() &&
573          "Mismatch between function signature & arguments.");
574   CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
575   for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
576        i != e; ++i, ++info_it) {
577     const VarDecl *Arg = i->first;
578     QualType Ty = info_it->type;
579     const ABIArgInfo &ArgI = info_it->info;
580 
581     switch (ArgI.getKind()) {
582     case ABIArgInfo::Indirect: {
583       llvm::Value* V = AI;
584       if (hasAggregateLLVMType(Ty)) {
585         // Do nothing, aggregates and complex variables are accessed by
586         // reference.
587       } else {
588         // Load scalar value from indirect argument.
589         V = EmitLoadOfScalar(V, false, Ty);
590         if (!getContext().typesAreCompatible(Ty, Arg->getType())) {
591           // This must be a promotion, for something like
592           // "void a(x) short x; {..."
593           V = EmitScalarConversion(V, Ty, Arg->getType());
594         }
595       }
596       EmitParmDecl(*Arg, V);
597       break;
598     }
599 
600     case ABIArgInfo::Extend:
601     case ABIArgInfo::Direct: {
602       assert(AI != Fn->arg_end() && "Argument mismatch!");
603       llvm::Value* V = AI;
604       if (hasAggregateLLVMType(Ty)) {
605         // Create a temporary alloca to hold the argument; the rest of
606         // codegen expects to access aggregates & complex values by
607         // reference.
608         V = CreateTempAlloca(ConvertTypeForMem(Ty));
609         Builder.CreateStore(AI, V);
610       } else {
611         if (!getContext().typesAreCompatible(Ty, Arg->getType())) {
612           // This must be a promotion, for something like
613           // "void a(x) short x; {..."
614           V = EmitScalarConversion(V, Ty, Arg->getType());
615         }
616       }
617       EmitParmDecl(*Arg, V);
618       break;
619     }
620 
621     case ABIArgInfo::Expand: {
622       // If this structure was expanded into multiple arguments then
623       // we need to create a temporary and reconstruct it from the
624       // arguments.
625       std::string Name = Arg->getNameAsString();
626       llvm::Value *Temp = CreateTempAlloca(ConvertTypeForMem(Ty),
627                                            (Name + ".addr").c_str());
628       // FIXME: What are the right qualifiers here?
629       llvm::Function::arg_iterator End =
630         ExpandTypeFromArgs(Ty, LValue::MakeAddr(Temp,0), AI);
631       EmitParmDecl(*Arg, Temp);
632 
633       // Name the arguments used in expansion and increment AI.
634       unsigned Index = 0;
635       for (; AI != End; ++AI, ++Index)
636         AI->setName(Name + "." + llvm::Twine(Index));
637       continue;
638     }
639 
640     case ABIArgInfo::Ignore:
641       // Initialize the local variable appropriately.
642       if (hasAggregateLLVMType(Ty)) {
643         EmitParmDecl(*Arg, CreateTempAlloca(ConvertTypeForMem(Ty)));
644       } else {
645         EmitParmDecl(*Arg, llvm::UndefValue::get(ConvertType(Arg->getType())));
646       }
647 
648       // Skip increment, no matching LLVM parameter.
649       continue;
650 
651     case ABIArgInfo::Coerce: {
652       assert(AI != Fn->arg_end() && "Argument mismatch!");
653       // FIXME: This is very wasteful; EmitParmDecl is just going to drop the
654       // result in a new alloca anyway, so we could just store into that
655       // directly if we broke the abstraction down more.
656       llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(Ty), "coerce");
657       CreateCoercedStore(AI, V, *this);
658       // Match to what EmitParmDecl is expecting for this type.
659       if (!CodeGenFunction::hasAggregateLLVMType(Ty)) {
660         V = EmitLoadOfScalar(V, false, Ty);
661         if (!getContext().typesAreCompatible(Ty, Arg->getType())) {
662           // This must be a promotion, for something like
663           // "void a(x) short x; {..."
664           V = EmitScalarConversion(V, Ty, Arg->getType());
665         }
666       }
667       EmitParmDecl(*Arg, V);
668       break;
669     }
670     }
671 
672     ++AI;
673   }
674   assert(AI == Fn->arg_end() && "Argument mismatch!");
675 }
676 
677 void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
678                                          llvm::Value *ReturnValue) {
679   llvm::Value *RV = 0;
680 
681   // Functions with no result always return void.
682   if (ReturnValue) {
683     QualType RetTy = FI.getReturnType();
684     const ABIArgInfo &RetAI = FI.getReturnInfo();
685 
686     switch (RetAI.getKind()) {
687     case ABIArgInfo::Indirect:
688       if (RetTy->isAnyComplexType()) {
689         ComplexPairTy RT = LoadComplexFromAddr(ReturnValue, false);
690         StoreComplexToAddr(RT, CurFn->arg_begin(), false);
691       } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
692         EmitAggregateCopy(CurFn->arg_begin(), ReturnValue, RetTy);
693       } else {
694         EmitStoreOfScalar(Builder.CreateLoad(ReturnValue), CurFn->arg_begin(),
695                           false, RetTy);
696       }
697       break;
698 
699     case ABIArgInfo::Extend:
700     case ABIArgInfo::Direct:
701       // The internal return value temp always will have
702       // pointer-to-return-type type.
703       RV = Builder.CreateLoad(ReturnValue);
704       break;
705 
706     case ABIArgInfo::Ignore:
707       break;
708 
709     case ABIArgInfo::Coerce:
710       RV = CreateCoercedLoad(ReturnValue, RetAI.getCoerceToType(), *this);
711       break;
712 
713     case ABIArgInfo::Expand:
714       assert(0 && "Invalid ABI kind for return argument");
715     }
716   }
717 
718   if (RV) {
719     Builder.CreateRet(RV);
720   } else {
721     Builder.CreateRetVoid();
722   }
723 }
724 
725 RValue CodeGenFunction::EmitCallArg(const Expr *E, QualType ArgType) {
726   if (ArgType->isReferenceType())
727     return EmitReferenceBindingToExpr(E, ArgType);
728 
729   return EmitAnyExprToTemp(E);
730 }
731 
732 RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
733                                  llvm::Value *Callee,
734                                  const CallArgList &CallArgs,
735                                  const Decl *TargetDecl) {
736   // FIXME: We no longer need the types from CallArgs; lift up and simplify.
737   llvm::SmallVector<llvm::Value*, 16> Args;
738 
739   // Handle struct-return functions by passing a pointer to the
740   // location that we would like to return into.
741   QualType RetTy = CallInfo.getReturnType();
742   const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
743 
744 
745   // If the call returns a temporary with struct return, create a temporary
746   // alloca to hold the result.
747   if (CGM.ReturnTypeUsesSret(CallInfo))
748     Args.push_back(CreateTempAlloca(ConvertTypeForMem(RetTy)));
749 
750   assert(CallInfo.arg_size() == CallArgs.size() &&
751          "Mismatch between function signature & arguments.");
752   CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
753   for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
754        I != E; ++I, ++info_it) {
755     const ABIArgInfo &ArgInfo = info_it->info;
756     RValue RV = I->first;
757 
758     switch (ArgInfo.getKind()) {
759     case ABIArgInfo::Indirect:
760       if (RV.isScalar() || RV.isComplex()) {
761         // Make a temporary alloca to pass the argument.
762         Args.push_back(CreateTempAlloca(ConvertTypeForMem(I->second)));
763         if (RV.isScalar())
764           EmitStoreOfScalar(RV.getScalarVal(), Args.back(), false, I->second);
765         else
766           StoreComplexToAddr(RV.getComplexVal(), Args.back(), false);
767       } else {
768         Args.push_back(RV.getAggregateAddr());
769       }
770       break;
771 
772     case ABIArgInfo::Extend:
773     case ABIArgInfo::Direct:
774       if (RV.isScalar()) {
775         Args.push_back(RV.getScalarVal());
776       } else if (RV.isComplex()) {
777         llvm::Value *Tmp = llvm::UndefValue::get(ConvertType(I->second));
778         Tmp = Builder.CreateInsertValue(Tmp, RV.getComplexVal().first, 0);
779         Tmp = Builder.CreateInsertValue(Tmp, RV.getComplexVal().second, 1);
780         Args.push_back(Tmp);
781       } else {
782         Args.push_back(Builder.CreateLoad(RV.getAggregateAddr()));
783       }
784       break;
785 
786     case ABIArgInfo::Ignore:
787       break;
788 
789     case ABIArgInfo::Coerce: {
790       // FIXME: Avoid the conversion through memory if possible.
791       llvm::Value *SrcPtr;
792       if (RV.isScalar()) {
793         SrcPtr = CreateTempAlloca(ConvertTypeForMem(I->second), "coerce");
794         EmitStoreOfScalar(RV.getScalarVal(), SrcPtr, false, I->second);
795       } else if (RV.isComplex()) {
796         SrcPtr = CreateTempAlloca(ConvertTypeForMem(I->second), "coerce");
797         StoreComplexToAddr(RV.getComplexVal(), SrcPtr, false);
798       } else
799         SrcPtr = RV.getAggregateAddr();
800       Args.push_back(CreateCoercedLoad(SrcPtr, ArgInfo.getCoerceToType(),
801                                        *this));
802       break;
803     }
804 
805     case ABIArgInfo::Expand:
806       ExpandTypeToArgs(I->second, RV, Args);
807       break;
808     }
809   }
810 
811   // If the callee is a bitcast of a function to a varargs pointer to function
812   // type, check to see if we can remove the bitcast.  This handles some cases
813   // with unprototyped functions.
814   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
815     if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
816       const llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
817       const llvm::FunctionType *CurFT =
818         cast<llvm::FunctionType>(CurPT->getElementType());
819       const llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
820 
821       if (CE->getOpcode() == llvm::Instruction::BitCast &&
822           ActualFT->getReturnType() == CurFT->getReturnType() &&
823           ActualFT->getNumParams() == CurFT->getNumParams() &&
824           ActualFT->getNumParams() == Args.size()) {
825         bool ArgsMatch = true;
826         for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
827           if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
828             ArgsMatch = false;
829             break;
830           }
831 
832         // Strip the cast if we can get away with it.  This is a nice cleanup,
833         // but also allows us to inline the function at -O0 if it is marked
834         // always_inline.
835         if (ArgsMatch)
836           Callee = CalleeF;
837       }
838     }
839 
840 
841   llvm::BasicBlock *InvokeDest = getInvokeDest();
842   unsigned CallingConv;
843   CodeGen::AttributeListType AttributeList;
844   CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList, CallingConv);
845   llvm::AttrListPtr Attrs = llvm::AttrListPtr::get(AttributeList.begin(),
846                                                    AttributeList.end());
847 
848   llvm::CallSite CS;
849   if (!InvokeDest || (Attrs.getFnAttributes() & llvm::Attribute::NoUnwind)) {
850     CS = Builder.CreateCall(Callee, Args.data(), Args.data()+Args.size());
851   } else {
852     llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
853     CS = Builder.CreateInvoke(Callee, Cont, InvokeDest,
854                               Args.data(), Args.data()+Args.size());
855     EmitBlock(Cont);
856   }
857 
858   CS.setAttributes(Attrs);
859   CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
860 
861   // If the call doesn't return, finish the basic block and clear the
862   // insertion point; this allows the rest of IRgen to discard
863   // unreachable code.
864   if (CS.doesNotReturn()) {
865     Builder.CreateUnreachable();
866     Builder.ClearInsertionPoint();
867 
868     // FIXME: For now, emit a dummy basic block because expr emitters in
869     // generally are not ready to handle emitting expressions at unreachable
870     // points.
871     EnsureInsertPoint();
872 
873     // Return a reasonable RValue.
874     return GetUndefRValue(RetTy);
875   }
876 
877   llvm::Instruction *CI = CS.getInstruction();
878   if (Builder.isNamePreserving() &&
879       CI->getType() != llvm::Type::getVoidTy(VMContext))
880     CI->setName("call");
881 
882   switch (RetAI.getKind()) {
883   case ABIArgInfo::Indirect:
884     if (RetTy->isAnyComplexType())
885       return RValue::getComplex(LoadComplexFromAddr(Args[0], false));
886     if (CodeGenFunction::hasAggregateLLVMType(RetTy))
887       return RValue::getAggregate(Args[0]);
888     return RValue::get(EmitLoadOfScalar(Args[0], false, RetTy));
889 
890   case ABIArgInfo::Extend:
891   case ABIArgInfo::Direct:
892     if (RetTy->isAnyComplexType()) {
893       llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
894       llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
895       return RValue::getComplex(std::make_pair(Real, Imag));
896     }
897     if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
898       llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(RetTy), "agg.tmp");
899       Builder.CreateStore(CI, V);
900       return RValue::getAggregate(V);
901     }
902     return RValue::get(CI);
903 
904   case ABIArgInfo::Ignore:
905     // If we are ignoring an argument that had a result, make sure to
906     // construct the appropriate return value for our caller.
907     return GetUndefRValue(RetTy);
908 
909   case ABIArgInfo::Coerce: {
910     // FIXME: Avoid the conversion through memory if possible.
911     llvm::Value *V = CreateTempAlloca(ConvertTypeForMem(RetTy), "coerce");
912     CreateCoercedStore(CI, V, *this);
913     if (RetTy->isAnyComplexType())
914       return RValue::getComplex(LoadComplexFromAddr(V, false));
915     if (CodeGenFunction::hasAggregateLLVMType(RetTy))
916       return RValue::getAggregate(V);
917     return RValue::get(EmitLoadOfScalar(V, false, RetTy));
918   }
919 
920   case ABIArgInfo::Expand:
921     assert(0 && "Invalid ABI kind for return argument");
922   }
923 
924   assert(0 && "Unhandled ABIArgInfo::Kind");
925   return RValue::get(0);
926 }
927 
928 /* VarArg handling */
929 
930 llvm::Value *CodeGenFunction::EmitVAArg(llvm::Value *VAListAddr, QualType Ty) {
931   return CGM.getTypes().getABIInfo().EmitVAArg(VAListAddr, Ty, *this);
932 }
933