CGCall.cpp revision 3aea8cac3ec9ad03b1d2b002f38a0d42a70483c8
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/ASTContext.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclObjC.h"
22#include "llvm/ADT/StringExtras.h"
23#include "llvm/Attributes.h"
24using namespace clang;
25using namespace CodeGen;
26
27/***/
28
29// FIXME: Use iterator and sidestep silly type array creation.
30
31CGFunctionInfo::CGFunctionInfo(const FunctionTypeNoProto *FTNP)
32  : IsVariadic(true)
33{
34  ArgTypes.push_back(FTNP->getResultType());
35}
36
37CGFunctionInfo::CGFunctionInfo(const FunctionTypeProto *FTP)
38  : IsVariadic(FTP->isVariadic())
39{
40  ArgTypes.push_back(FTP->getResultType());
41  for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
42    ArgTypes.push_back(FTP->getArgType(i));
43}
44
45// FIXME: Is there really any reason to have this still?
46CGFunctionInfo::CGFunctionInfo(const FunctionDecl *FD)
47{
48  const FunctionType *FTy = FD->getType()->getAsFunctionType();
49  const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(FTy);
50
51  ArgTypes.push_back(FTy->getResultType());
52  if (FTP) {
53    IsVariadic = FTP->isVariadic();
54    for (unsigned i = 0, e = FTP->getNumArgs(); i != e; ++i)
55      ArgTypes.push_back(FTP->getArgType(i));
56  } else {
57    IsVariadic = true;
58  }
59}
60
61CGFunctionInfo::CGFunctionInfo(const ObjCMethodDecl *MD,
62                               const ASTContext &Context)
63  : IsVariadic(MD->isVariadic())
64{
65  ArgTypes.push_back(MD->getResultType());
66  ArgTypes.push_back(MD->getSelfDecl()->getType());
67  ArgTypes.push_back(Context.getObjCSelType());
68  for (ObjCMethodDecl::param_const_iterator i = MD->param_begin(),
69         e = MD->param_end(); i != e; ++i)
70    ArgTypes.push_back((*i)->getType());
71}
72
73ArgTypeIterator CGFunctionInfo::argtypes_begin() const {
74  return ArgTypes.begin();
75}
76
77ArgTypeIterator CGFunctionInfo::argtypes_end() const {
78  return ArgTypes.end();
79}
80
81/***/
82
83CGCallInfo::CGCallInfo(QualType _ResultType, const CallArgList &_Args) {
84  ArgTypes.push_back(_ResultType);
85  for (CallArgList::const_iterator i = _Args.begin(), e = _Args.end(); i!=e; ++i)
86    ArgTypes.push_back(i->second);
87}
88
89ArgTypeIterator CGCallInfo::argtypes_begin() const {
90  return ArgTypes.begin();
91}
92
93ArgTypeIterator CGCallInfo::argtypes_end() const {
94  return ArgTypes.end();
95}
96
97/***/
98
99/// ABIArgInfo - Helper class to encapsulate information about how a
100/// specific C type should be passed to or returned from a function.
101class ABIArgInfo {
102public:
103  enum Kind {
104    Default,
105    StructRet, /// Only valid for return values. The return value
106               /// should be passed through a pointer to a caller
107               /// allocated location passed as an implicit first
108               /// argument to the function.
109
110    Coerce,    /// Only valid for aggregate return types, the argument
111               /// should be accessed by coercion to a provided type.
112
113    ByVal,     /// Only valid for aggregate argument types. The
114               /// structure should be passed "byval" with the
115               /// specified alignment (0 indicates default
116               /// alignment).
117
118    Expand,    /// Only valid for aggregate argument types. The
119               /// structure should be expanded into consecutive
120               /// arguments for its constituent fields. Currently
121               /// expand is only allowed on structures whose fields
122               /// are all scalar types or are themselves expandable
123               /// types.
124
125    KindFirst=Default, KindLast=Expand
126  };
127
128private:
129  Kind TheKind;
130  const llvm::Type *TypeData;
131  unsigned UIntData;
132
133  ABIArgInfo(Kind K, const llvm::Type *TD=0,
134             unsigned UI=0) : TheKind(K),
135                              TypeData(TD),
136                              UIntData(0) {}
137public:
138  static ABIArgInfo getDefault() {
139    return ABIArgInfo(Default);
140  }
141  static ABIArgInfo getStructRet() {
142    return ABIArgInfo(StructRet);
143  }
144  static ABIArgInfo getCoerce(const llvm::Type *T) {
145    assert(T->isSingleValueType() && "Can only coerce to simple types");
146    return ABIArgInfo(Coerce, T);
147  }
148  static ABIArgInfo getByVal(unsigned Alignment) {
149    return ABIArgInfo(ByVal, 0, Alignment);
150  }
151  static ABIArgInfo getExpand() {
152    return ABIArgInfo(Expand);
153  }
154
155  Kind getKind() const { return TheKind; }
156  bool isDefault() const { return TheKind == Default; }
157  bool isStructRet() const { return TheKind == StructRet; }
158  bool isCoerce() const { return TheKind == Coerce; }
159  bool isByVal() const { return TheKind == ByVal; }
160  bool isExpand() const { return TheKind == Expand; }
161
162  // Coerce accessors
163  const llvm::Type *getCoerceToType() const {
164    assert(TheKind == Coerce && "Invalid kind!");
165    return TypeData;
166  }
167
168  // ByVal accessors
169  unsigned getByValAlignment() const {
170    assert(TheKind == ByVal && "Invalid kind!");
171    return UIntData;
172  }
173};
174
175/***/
176
177/* FIXME: All of this stuff should be part of the target interface
178   somehow. It is currently here because it is not clear how to factor
179   the targets to support this, since the Targets currently live in a
180   layer below types n'stuff.
181 */
182
183/// ABIInfo - Target specific hooks for defining how a type should be
184/// passed or returned from functions.
185class clang::ABIInfo {
186public:
187  virtual ~ABIInfo();
188
189  virtual ABIArgInfo classifyReturnType(QualType RetTy,
190                                        ASTContext &Context) const = 0;
191
192  virtual ABIArgInfo classifyArgumentType(QualType Ty,
193                                          ASTContext &Context) const = 0;
194};
195
196ABIInfo::~ABIInfo() {}
197
198/// isEmptyStruct - Return true iff a structure has no non-empty
199/// members. Note that a structure with a flexible array member is not
200/// considered empty.
201static bool isEmptyStruct(QualType T) {
202  const RecordType *RT = T->getAsStructureType();
203  if (!RT)
204    return 0;
205  const RecordDecl *RD = RT->getDecl();
206  if (RD->hasFlexibleArrayMember())
207    return false;
208  for (RecordDecl::field_const_iterator i = RD->field_begin(),
209         e = RD->field_end(); i != e; ++i) {
210    const FieldDecl *FD = *i;
211    if (!isEmptyStruct(FD->getType()))
212      return false;
213  }
214  return true;
215}
216
217/// isSingleElementStruct - Determine if a structure is a "single
218/// element struct", i.e. it has exactly one non-empty field or
219/// exactly one field which is itself a single element
220/// struct. Structures with flexible array members are never
221/// considered single element structs.
222///
223/// \return The field declaration for the single non-empty field, if
224/// it exists.
225static const FieldDecl *isSingleElementStruct(QualType T) {
226  const RecordType *RT = T->getAsStructureType();
227  if (!RT)
228    return 0;
229
230  const RecordDecl *RD = RT->getDecl();
231  if (RD->hasFlexibleArrayMember())
232    return 0;
233
234  const FieldDecl *Found = 0;
235  for (RecordDecl::field_const_iterator i = RD->field_begin(),
236         e = RD->field_end(); i != e; ++i) {
237    const FieldDecl *FD = *i;
238    QualType FT = FD->getType();
239
240    if (isEmptyStruct(FT)) {
241      // Ignore
242    } else if (Found) {
243      return 0;
244    } else if (!CodeGenFunction::hasAggregateLLVMType(FT)) {
245      Found = FD;
246    } else {
247      Found = isSingleElementStruct(FT);
248      if (!Found)
249        return 0;
250    }
251  }
252
253  return Found;
254}
255
256static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
257  if (!Ty->getAsBuiltinType() && !Ty->isPointerType())
258    return false;
259
260  uint64_t Size = Context.getTypeSize(Ty);
261  return Size == 32 || Size == 64;
262}
263
264static bool areAllFields32Or64BitBasicType(const RecordDecl *RD,
265                                           ASTContext &Context) {
266  for (RecordDecl::field_const_iterator i = RD->field_begin(),
267         e = RD->field_end(); i != e; ++i) {
268    const FieldDecl *FD = *i;
269
270    if (!is32Or64BitBasicType(FD->getType(), Context))
271      return false;
272
273    // If this is a bit-field we need to make sure it is still a
274    // 32-bit or 64-bit type.
275    if (Expr *BW = FD->getBitWidth()) {
276      unsigned Width = BW->getIntegerConstantExprValue(Context).getZExtValue();
277      if (Width <= 16)
278        return false;
279    }
280  }
281  return true;
282}
283
284namespace {
285/// DefaultABIInfo - The default implementation for ABI specific
286/// details. This implementation provides information which results in
287/// sensible LLVM IR generation, but does not conform to any
288/// particular ABI.
289class DefaultABIInfo : public ABIInfo {
290  virtual ABIArgInfo classifyReturnType(QualType RetTy,
291                                        ASTContext &Context) const;
292
293  virtual ABIArgInfo classifyArgumentType(QualType RetTy,
294                                          ASTContext &Context) const;
295};
296
297/// X86_32ABIInfo - The X86-32 ABI information.
298class X86_32ABIInfo : public ABIInfo {
299public:
300  virtual ABIArgInfo classifyReturnType(QualType RetTy,
301                                        ASTContext &Context) const;
302
303  virtual ABIArgInfo classifyArgumentType(QualType RetTy,
304                                          ASTContext &Context) const;
305};
306}
307
308ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
309                                            ASTContext &Context) const {
310  assert(!RetTy->isArrayType() &&
311         "Array types cannot be passed directly.");
312  if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
313    // Classify "single element" structs as their element type.
314    const FieldDecl *SeltFD = isSingleElementStruct(RetTy);
315    if (SeltFD) {
316      QualType SeltTy = SeltFD->getType()->getDesugaredType();
317      if (const BuiltinType *BT = SeltTy->getAsBuiltinType()) {
318        // FIXME: This is gross, it would be nice if we could just
319        // pass back SeltTy and have clients deal with it. Is it worth
320        // supporting coerce to both LLVM and clang Types?
321        if (BT->isIntegerType()) {
322          uint64_t Size = Context.getTypeSize(SeltTy);
323          return ABIArgInfo::getCoerce(llvm::IntegerType::get((unsigned) Size));
324        } else if (BT->getKind() == BuiltinType::Float) {
325          return ABIArgInfo::getCoerce(llvm::Type::FloatTy);
326        } else if (BT->getKind() == BuiltinType::Double) {
327          return ABIArgInfo::getCoerce(llvm::Type::DoubleTy);
328        }
329      } else if (SeltTy->isPointerType()) {
330        // FIXME: It would be really nice if this could come out as
331        // the proper pointer type.
332        llvm::Type *PtrTy =
333          llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
334        return ABIArgInfo::getCoerce(PtrTy);
335      }
336    }
337
338    uint64_t Size = Context.getTypeSize(RetTy);
339    if (Size == 8) {
340      return ABIArgInfo::getCoerce(llvm::Type::Int8Ty);
341    } else if (Size == 16) {
342      return ABIArgInfo::getCoerce(llvm::Type::Int16Ty);
343    } else if (Size == 32) {
344      return ABIArgInfo::getCoerce(llvm::Type::Int32Ty);
345    } else if (Size == 64) {
346      return ABIArgInfo::getCoerce(llvm::Type::Int64Ty);
347    } else {
348      return ABIArgInfo::getStructRet();
349    }
350  } else {
351    return ABIArgInfo::getDefault();
352  }
353}
354
355ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
356                                              ASTContext &Context) const {
357  assert(!Ty->isArrayType() && "Array types cannot be passed directly.");
358  if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
359    // Structures with flexible arrays are always byval.
360    if (const RecordType *RT = Ty->getAsStructureType())
361      if (RT->getDecl()->hasFlexibleArrayMember())
362        return ABIArgInfo::getByVal(0);
363
364    // Expand empty structs (i.e. ignore)
365    uint64_t Size = Context.getTypeSize(Ty);
366    if (Ty->isStructureType() && Size == 0)
367      return ABIArgInfo::getExpand();
368
369    // Expand structs with size <= 128-bits which consist only of
370    // basic types (int, long long, float, double, xxx*). This is
371    // non-recursive and does not ignore empty fields.
372    if (const RecordType *RT = Ty->getAsStructureType()) {
373      if (Context.getTypeSize(Ty) <= 4*32 &&
374          areAllFields32Or64BitBasicType(RT->getDecl(), Context))
375        return ABIArgInfo::getExpand();
376    }
377
378    return ABIArgInfo::getByVal(0);
379  } else {
380    return ABIArgInfo::getDefault();
381  }
382}
383
384ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy,
385                                            ASTContext &Context) const {
386  return ABIArgInfo::getDefault();
387}
388
389ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty,
390                                              ASTContext &Context) const {
391  assert(!Ty->isArrayType() && "Array types cannot be passed directly.");
392  return ABIArgInfo::getDefault();
393}
394
395const ABIInfo &CodeGenTypes::getABIInfo() const {
396  if (TheABIInfo)
397    return *TheABIInfo;
398
399  // For now we just cache this in the CodeGenTypes and don't bother
400  // to free it.
401  const char *TargetPrefix = getContext().Target.getTargetPrefix();
402  if (strcmp(TargetPrefix, "x86") == 0) {
403    if (getContext().Target.getPointerWidth(0) == 32)
404      return *(TheABIInfo = new X86_32ABIInfo());
405  }
406
407  return *(TheABIInfo = new DefaultABIInfo);
408}
409
410// getABIReturnInfo - Wrap the ABIInfo getABIReturnInfo, altering
411// "default" types to StructRet when appropriate for simplicity.
412static ABIArgInfo getABIReturnInfo(QualType Ty, CodeGenTypes &CGT) {
413  assert(!Ty->isArrayType() &&
414         "Array types cannot be passed directly.");
415  ABIArgInfo Info = CGT.getABIInfo().classifyReturnType(Ty, CGT.getContext());
416  // Ensure default on aggregate types is StructRet.
417  if (Info.isDefault() && CodeGenFunction::hasAggregateLLVMType(Ty))
418    return ABIArgInfo::getStructRet();
419  return Info;
420}
421
422// getABIArgumentInfo - Wrap the ABIInfo getABIReturnInfo, altering
423// "default" types to ByVal when appropriate for simplicity.
424static ABIArgInfo getABIArgumentInfo(QualType Ty, CodeGenTypes &CGT) {
425  assert(!Ty->isArrayType() &&
426         "Array types cannot be passed directly.");
427  ABIArgInfo Info = CGT.getABIInfo().classifyArgumentType(Ty, CGT.getContext());
428  // Ensure default on aggregate types is ByVal.
429  if (Info.isDefault() && CodeGenFunction::hasAggregateLLVMType(Ty))
430    return ABIArgInfo::getByVal(0);
431  return Info;
432}
433
434/***/
435
436void CodeGenTypes::GetExpandedTypes(QualType Ty,
437                                    std::vector<const llvm::Type*> &ArgTys) {
438  const RecordType *RT = Ty->getAsStructureType();
439  assert(RT && "Can only expand structure types.");
440  const RecordDecl *RD = RT->getDecl();
441  assert(!RD->hasFlexibleArrayMember() &&
442         "Cannot expand structure with flexible array.");
443
444  for (RecordDecl::field_const_iterator i = RD->field_begin(),
445         e = RD->field_end(); i != e; ++i) {
446    const FieldDecl *FD = *i;
447    assert(!FD->isBitField() &&
448           "Cannot expand structure with bit-field members.");
449
450    QualType FT = FD->getType();
451    if (CodeGenFunction::hasAggregateLLVMType(FT)) {
452      GetExpandedTypes(FT, ArgTys);
453    } else {
454      ArgTys.push_back(ConvertType(FT));
455    }
456  }
457}
458
459llvm::Function::arg_iterator
460CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
461                                    llvm::Function::arg_iterator AI) {
462  const RecordType *RT = Ty->getAsStructureType();
463  assert(RT && "Can only expand structure types.");
464
465  RecordDecl *RD = RT->getDecl();
466  assert(LV.isSimple() &&
467         "Unexpected non-simple lvalue during struct expansion.");
468  llvm::Value *Addr = LV.getAddress();
469  for (RecordDecl::field_iterator i = RD->field_begin(),
470         e = RD->field_end(); i != e; ++i) {
471    FieldDecl *FD = *i;
472    QualType FT = FD->getType();
473
474    // FIXME: What are the right qualifiers here?
475    LValue LV = EmitLValueForField(Addr, FD, false, 0);
476    if (CodeGenFunction::hasAggregateLLVMType(FT)) {
477      AI = ExpandTypeFromArgs(FT, LV, AI);
478    } else {
479      EmitStoreThroughLValue(RValue::get(AI), LV, FT);
480      ++AI;
481    }
482  }
483
484  return AI;
485}
486
487void
488CodeGenFunction::ExpandTypeToArgs(QualType Ty, RValue RV,
489                                  llvm::SmallVector<llvm::Value*, 16> &Args) {
490  const RecordType *RT = Ty->getAsStructureType();
491  assert(RT && "Can only expand structure types.");
492
493  RecordDecl *RD = RT->getDecl();
494  assert(RV.isAggregate() && "Unexpected rvalue during struct expansion");
495  llvm::Value *Addr = RV.getAggregateAddr();
496  for (RecordDecl::field_iterator i = RD->field_begin(),
497         e = RD->field_end(); i != e; ++i) {
498    FieldDecl *FD = *i;
499    QualType FT = FD->getType();
500
501    // FIXME: What are the right qualifiers here?
502    LValue LV = EmitLValueForField(Addr, FD, false, 0);
503    if (CodeGenFunction::hasAggregateLLVMType(FT)) {
504      ExpandTypeToArgs(FT, RValue::getAggregate(LV.getAddress()), Args);
505    } else {
506      RValue RV = EmitLoadOfLValue(LV, FT);
507      assert(RV.isScalar() &&
508             "Unexpected non-scalar rvalue during struct expansion.");
509      Args.push_back(RV.getScalarVal());
510    }
511  }
512}
513
514/***/
515
516const llvm::FunctionType *
517CodeGenTypes::GetFunctionType(const CGCallInfo &CI, bool IsVariadic) {
518  return GetFunctionType(CI.argtypes_begin(), CI.argtypes_end(), IsVariadic);
519}
520
521const llvm::FunctionType *
522CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
523  return GetFunctionType(FI.argtypes_begin(), FI.argtypes_end(), FI.isVariadic());
524}
525
526const llvm::FunctionType *
527CodeGenTypes::GetFunctionType(ArgTypeIterator begin, ArgTypeIterator end,
528                              bool IsVariadic) {
529  std::vector<const llvm::Type*> ArgTys;
530
531  const llvm::Type *ResultType = 0;
532
533  QualType RetTy = *begin;
534  ABIArgInfo RetAI = getABIReturnInfo(RetTy, *this);
535  switch (RetAI.getKind()) {
536  case ABIArgInfo::ByVal:
537  case ABIArgInfo::Expand:
538    assert(0 && "Invalid ABI kind for return argument");
539
540  case ABIArgInfo::Default:
541    if (RetTy->isVoidType()) {
542      ResultType = llvm::Type::VoidTy;
543    } else {
544      ResultType = ConvertType(RetTy);
545    }
546    break;
547
548  case ABIArgInfo::StructRet: {
549    ResultType = llvm::Type::VoidTy;
550    const llvm::Type *STy = ConvertType(RetTy);
551    ArgTys.push_back(llvm::PointerType::get(STy, RetTy.getAddressSpace()));
552    break;
553  }
554
555  case ABIArgInfo::Coerce:
556    ResultType = RetAI.getCoerceToType();
557    break;
558  }
559
560  for (++begin; begin != end; ++begin) {
561    ABIArgInfo AI = getABIArgumentInfo(*begin, *this);
562    const llvm::Type *Ty = ConvertType(*begin);
563
564    switch (AI.getKind()) {
565    case ABIArgInfo::Coerce:
566    case ABIArgInfo::StructRet:
567      assert(0 && "Invalid ABI kind for non-return argument");
568
569    case ABIArgInfo::ByVal:
570      // byval arguments are always on the stack, which is addr space #0.
571      ArgTys.push_back(llvm::PointerType::getUnqual(Ty));
572      assert(AI.getByValAlignment() == 0 && "FIXME: alignment unhandled");
573      break;
574
575    case ABIArgInfo::Default:
576      ArgTys.push_back(Ty);
577      break;
578
579    case ABIArgInfo::Expand:
580      GetExpandedTypes(*begin, ArgTys);
581      break;
582    }
583  }
584
585  return llvm::FunctionType::get(ResultType, ArgTys, IsVariadic);
586}
587
588bool CodeGenModule::ReturnTypeUsesSret(QualType RetTy) {
589  return getABIReturnInfo(RetTy, getTypes()).isStructRet();
590}
591
592void CodeGenModule::ConstructAttributeList(const Decl *TargetDecl,
593                                           ArgTypeIterator begin,
594                                           ArgTypeIterator end,
595                                           AttributeListType &PAL) {
596  unsigned FuncAttrs = 0;
597  unsigned RetAttrs = 0;
598
599  if (TargetDecl) {
600    if (TargetDecl->getAttr<NoThrowAttr>())
601      FuncAttrs |= llvm::Attribute::NoUnwind;
602    if (TargetDecl->getAttr<NoReturnAttr>())
603      FuncAttrs |= llvm::Attribute::NoReturn;
604    if (TargetDecl->getAttr<PureAttr>())
605      FuncAttrs |= llvm::Attribute::ReadOnly;
606    if (TargetDecl->getAttr<ConstAttr>())
607      FuncAttrs |= llvm::Attribute::ReadNone;
608  }
609
610  QualType RetTy = *begin;
611  unsigned Index = 1;
612  ABIArgInfo RetAI = getABIReturnInfo(RetTy, getTypes());
613  switch (RetAI.getKind()) {
614  case ABIArgInfo::Default:
615    if (RetTy->isPromotableIntegerType()) {
616      if (RetTy->isSignedIntegerType()) {
617        RetAttrs |= llvm::Attribute::SExt;
618      } else if (RetTy->isUnsignedIntegerType()) {
619        RetAttrs |= llvm::Attribute::ZExt;
620      }
621    }
622    break;
623
624  case ABIArgInfo::StructRet:
625    PAL.push_back(llvm::AttributeWithIndex::get(Index,
626                                                  llvm::Attribute::StructRet|
627                                                  llvm::Attribute::NoAlias));
628    ++Index;
629    break;
630
631  case ABIArgInfo::Coerce:
632    break;
633
634  case ABIArgInfo::ByVal:
635  case ABIArgInfo::Expand:
636    assert(0 && "Invalid ABI kind for return argument");
637  }
638
639  if (RetAttrs)
640    PAL.push_back(llvm::AttributeWithIndex::get(0, RetAttrs));
641  for (++begin; begin != end; ++begin) {
642    QualType ParamType = *begin;
643    unsigned Attributes = 0;
644    ABIArgInfo AI = getABIArgumentInfo(ParamType, getTypes());
645
646    switch (AI.getKind()) {
647    case ABIArgInfo::StructRet:
648    case ABIArgInfo::Coerce:
649      assert(0 && "Invalid ABI kind for non-return argument");
650
651    case ABIArgInfo::ByVal:
652      Attributes |= llvm::Attribute::ByVal;
653      assert(AI.getByValAlignment() == 0 && "FIXME: alignment unhandled");
654      break;
655
656    case ABIArgInfo::Default:
657      if (ParamType->isPromotableIntegerType()) {
658        if (ParamType->isSignedIntegerType()) {
659          Attributes |= llvm::Attribute::SExt;
660        } else if (ParamType->isUnsignedIntegerType()) {
661          Attributes |= llvm::Attribute::ZExt;
662        }
663      }
664      break;
665
666    case ABIArgInfo::Expand: {
667      std::vector<const llvm::Type*> Tys;
668      // FIXME: This is rather inefficient. Do we ever actually need
669      // to do anything here? The result should be just reconstructed
670      // on the other side, so extension should be a non-issue.
671      getTypes().GetExpandedTypes(ParamType, Tys);
672      Index += Tys.size();
673      continue;
674    }
675    }
676
677    if (Attributes)
678      PAL.push_back(llvm::AttributeWithIndex::get(Index, Attributes));
679    ++Index;
680  }
681  if (FuncAttrs)
682    PAL.push_back(llvm::AttributeWithIndex::get(~0, FuncAttrs));
683
684}
685
686void CodeGenFunction::EmitFunctionProlog(llvm::Function *Fn,
687                                         QualType RetTy,
688                                         const FunctionArgList &Args) {
689  // Emit allocs for param decls.  Give the LLVM Argument nodes names.
690  llvm::Function::arg_iterator AI = Fn->arg_begin();
691
692  // Name the struct return argument.
693  if (CGM.ReturnTypeUsesSret(RetTy)) {
694    AI->setName("agg.result");
695    ++AI;
696  }
697
698  for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
699       i != e; ++i) {
700    const VarDecl *Arg = i->first;
701    QualType Ty = i->second;
702    ABIArgInfo ArgI = getABIArgumentInfo(Ty, CGM.getTypes());
703
704    switch (ArgI.getKind()) {
705    case ABIArgInfo::ByVal:
706    case ABIArgInfo::Default: {
707      assert(AI != Fn->arg_end() && "Argument mismatch!");
708      llvm::Value* V = AI;
709      if (!getContext().typesAreCompatible(Ty, Arg->getType())) {
710        // This must be a promotion, for something like
711        // "void a(x) short x; {..."
712        V = EmitScalarConversion(V, Ty, Arg->getType());
713      }
714      EmitParmDecl(*Arg, V);
715      break;
716    }
717
718    case ABIArgInfo::Expand: {
719      // If this was structure was expand into multiple arguments then
720      // we need to create a temporary and reconstruct it from the
721      // arguments.
722      std::string Name = Arg->getNameAsString();
723      llvm::Value *Temp = CreateTempAlloca(ConvertType(Ty),
724                                           (Name + ".addr").c_str());
725      // FIXME: What are the right qualifiers here?
726      llvm::Function::arg_iterator End =
727        ExpandTypeFromArgs(Ty, LValue::MakeAddr(Temp,0), AI);
728      EmitParmDecl(*Arg, Temp);
729
730      // Name the arguments used in expansion and increment AI.
731      unsigned Index = 0;
732      for (; AI != End; ++AI, ++Index)
733        AI->setName(Name + "." + llvm::utostr(Index));
734      continue;
735    }
736
737    case ABIArgInfo::Coerce:
738    case ABIArgInfo::StructRet:
739      assert(0 && "Invalid ABI kind for non-return argument");
740    }
741
742    ++AI;
743  }
744  assert(AI == Fn->arg_end() && "Argument mismatch!");
745}
746
747void CodeGenFunction::EmitFunctionEpilog(QualType RetTy,
748                                         llvm::Value *ReturnValue) {
749  llvm::Value *RV = 0;
750
751  // Functions with no result always return void.
752  if (ReturnValue) {
753    ABIArgInfo RetAI = getABIReturnInfo(RetTy, CGM.getTypes());
754
755    switch (RetAI.getKind()) {
756    case ABIArgInfo::StructRet:
757      if (RetTy->isAnyComplexType()) {
758        // FIXME: Volatile
759        ComplexPairTy RT = LoadComplexFromAddr(ReturnValue, false);
760        StoreComplexToAddr(RT, CurFn->arg_begin(), false);
761      } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
762        EmitAggregateCopy(CurFn->arg_begin(), ReturnValue, RetTy);
763      } else {
764        Builder.CreateStore(Builder.CreateLoad(ReturnValue),
765                            CurFn->arg_begin());
766      }
767      break;
768
769    case ABIArgInfo::Default:
770      RV = Builder.CreateLoad(ReturnValue);
771      break;
772
773    case ABIArgInfo::Coerce: {
774      const llvm::Type *CoerceToPTy =
775        llvm::PointerType::getUnqual(RetAI.getCoerceToType());
776      RV = Builder.CreateLoad(Builder.CreateBitCast(ReturnValue, CoerceToPTy));
777      break;
778    }
779
780    case ABIArgInfo::ByVal:
781    case ABIArgInfo::Expand:
782      assert(0 && "Invalid ABI kind for return argument");
783    }
784  }
785
786  if (RV) {
787    Builder.CreateRet(RV);
788  } else {
789    Builder.CreateRetVoid();
790  }
791}
792
793RValue CodeGenFunction::EmitCall(llvm::Value *Callee,
794                                 QualType RetTy,
795                                 const CallArgList &CallArgs) {
796  llvm::SmallVector<llvm::Value*, 16> Args;
797
798  // Handle struct-return functions by passing a pointer to the
799  // location that we would like to return into.
800  ABIArgInfo RetAI = getABIReturnInfo(RetTy, CGM.getTypes());
801  switch (RetAI.getKind()) {
802  case ABIArgInfo::StructRet:
803    // Create a temporary alloca to hold the result of the call. :(
804    Args.push_back(CreateTempAlloca(ConvertType(RetTy)));
805    break;
806
807  case ABIArgInfo::Default:
808  case ABIArgInfo::Coerce:
809    break;
810
811  case ABIArgInfo::ByVal:
812  case ABIArgInfo::Expand:
813    assert(0 && "Invalid ABI kind for return argument");
814  }
815
816  for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
817       I != E; ++I) {
818    ABIArgInfo ArgInfo = getABIArgumentInfo(I->second, CGM.getTypes());
819    RValue RV = I->first;
820
821    switch (ArgInfo.getKind()) {
822    case ABIArgInfo::ByVal: // Default is byval
823    case ABIArgInfo::Default:
824      if (RV.isScalar()) {
825        Args.push_back(RV.getScalarVal());
826      } else if (RV.isComplex()) {
827        // Make a temporary alloca to pass the argument.
828        Args.push_back(CreateTempAlloca(ConvertType(I->second)));
829        StoreComplexToAddr(RV.getComplexVal(), Args.back(), false);
830      } else {
831        Args.push_back(RV.getAggregateAddr());
832      }
833      break;
834
835    case ABIArgInfo::StructRet:
836    case ABIArgInfo::Coerce:
837      assert(0 && "Invalid ABI kind for non-return argument");
838      break;
839
840    case ABIArgInfo::Expand:
841      ExpandTypeToArgs(I->second, RV, Args);
842      break;
843    }
844  }
845
846  llvm::CallInst *CI = Builder.CreateCall(Callee,&Args[0],&Args[0]+Args.size());
847  CGCallInfo CallInfo(RetTy, CallArgs);
848
849  // FIXME: Provide TargetDecl so nounwind, noreturn, etc, etc get set.
850  CodeGen::AttributeListType AttributeList;
851  CGM.ConstructAttributeList(0,
852                             CallInfo.argtypes_begin(), CallInfo.argtypes_end(),
853                             AttributeList);
854  CI->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
855                                         AttributeList.size()));
856
857  if (const llvm::Function *F = dyn_cast<llvm::Function>(Callee))
858    CI->setCallingConv(F->getCallingConv());
859  if (CI->getType() != llvm::Type::VoidTy)
860    CI->setName("call");
861
862  switch (RetAI.getKind()) {
863  case ABIArgInfo::StructRet:
864    if (RetTy->isAnyComplexType())
865      return RValue::getComplex(LoadComplexFromAddr(Args[0], false));
866    else if (CodeGenFunction::hasAggregateLLVMType(RetTy))
867      return RValue::getAggregate(Args[0]);
868    else
869      return RValue::get(Builder.CreateLoad(Args[0]));
870
871  case ABIArgInfo::Default:
872    return RValue::get(RetTy->isVoidType() ? 0 : CI);
873
874  case ABIArgInfo::Coerce: {
875    const llvm::Type *CoerceToPTy =
876      llvm::PointerType::getUnqual(RetAI.getCoerceToType());
877    llvm::Value *V = CreateTempAlloca(ConvertType(RetTy), "tmp");
878    Builder.CreateStore(CI, Builder.CreateBitCast(V, CoerceToPTy));
879    if (RetTy->isAnyComplexType())
880      return RValue::getComplex(LoadComplexFromAddr(V, false));
881    else
882      return RValue::getAggregate(V);
883  }
884
885  case ABIArgInfo::ByVal:
886  case ABIArgInfo::Expand:
887    assert(0 && "Invalid ABI kind for return argument");
888  }
889
890  assert(0 && "Unhandled ABIArgInfo::Kind");
891  return RValue::get(0);
892}
893