blob: 573ffed10a010cfee18ef9fdc1d376130ce9db46 [file] [log] [blame]
Anton Korobeynikov73628192009-06-05 22:08:42 +00001//===---- TargetABIInfo.cpp - Encapsulate target ABI 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 "ABIInfo.h"
16#include "CodeGenFunction.h"
17#include "clang/AST/RecordLayout.h"
18#include "llvm/Type.h"
19
20using namespace clang;
21using namespace CodeGen;
22
23ABIInfo::~ABIInfo() {}
24
25void ABIArgInfo::dump() const {
26 fprintf(stderr, "(ABIArgInfo Kind=");
27 switch (TheKind) {
28 case Direct:
29 fprintf(stderr, "Direct");
30 break;
31 case Ignore:
32 fprintf(stderr, "Ignore");
33 break;
34 case Coerce:
35 fprintf(stderr, "Coerce Type=");
36 getCoerceToType()->print(llvm::errs());
37 break;
38 case Indirect:
39 fprintf(stderr, "Indirect Align=%d", getIndirectAlign());
40 break;
41 case Expand:
42 fprintf(stderr, "Expand");
43 break;
44 }
45 fprintf(stderr, ")\n");
46}
47
48static bool isEmptyRecord(ASTContext &Context, QualType T);
49
50/// isEmptyField - Return true iff a the field is "empty", that is it
51/// is an unnamed bit-field or an (array of) empty record(s).
52static bool isEmptyField(ASTContext &Context, const FieldDecl *FD) {
53 if (FD->isUnnamedBitfield())
54 return true;
55
56 QualType FT = FD->getType();
57 // Constant arrays of empty records count as empty, strip them off.
58 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT))
59 FT = AT->getElementType();
60
61 return isEmptyRecord(Context, FT);
62}
63
64/// isEmptyRecord - Return true iff a structure contains only empty
65/// fields. Note that a structure with a flexible array member is not
66/// considered empty.
67static bool isEmptyRecord(ASTContext &Context, QualType T) {
68 const RecordType *RT = T->getAsRecordType();
69 if (!RT)
70 return 0;
71 const RecordDecl *RD = RT->getDecl();
72 if (RD->hasFlexibleArrayMember())
73 return false;
74 for (RecordDecl::field_iterator i = RD->field_begin(Context),
75 e = RD->field_end(Context); i != e; ++i)
76 if (!isEmptyField(Context, *i))
77 return false;
78 return true;
79}
80
81/// isSingleElementStruct - Determine if a structure is a "single
82/// element struct", i.e. it has exactly one non-empty field or
83/// exactly one field which is itself a single element
84/// struct. Structures with flexible array members are never
85/// considered single element structs.
86///
87/// \return The field declaration for the single non-empty field, if
88/// it exists.
89static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
90 const RecordType *RT = T->getAsStructureType();
91 if (!RT)
92 return 0;
93
94 const RecordDecl *RD = RT->getDecl();
95 if (RD->hasFlexibleArrayMember())
96 return 0;
97
98 const Type *Found = 0;
99 for (RecordDecl::field_iterator i = RD->field_begin(Context),
100 e = RD->field_end(Context); i != e; ++i) {
101 const FieldDecl *FD = *i;
102 QualType FT = FD->getType();
103
104 // Ignore empty fields.
105 if (isEmptyField(Context, FD))
106 continue;
107
108 // If we already found an element then this isn't a single-element
109 // struct.
110 if (Found)
111 return 0;
112
113 // Treat single element arrays as the element.
114 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
115 if (AT->getSize().getZExtValue() != 1)
116 break;
117 FT = AT->getElementType();
118 }
119
120 if (!CodeGenFunction::hasAggregateLLVMType(FT)) {
121 Found = FT.getTypePtr();
122 } else {
123 Found = isSingleElementStruct(FT, Context);
124 if (!Found)
125 return 0;
126 }
127 }
128
129 return Found;
130}
131
132static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
133 if (!Ty->getAsBuiltinType() && !Ty->isPointerType())
134 return false;
135
136 uint64_t Size = Context.getTypeSize(Ty);
137 return Size == 32 || Size == 64;
138}
139
140static bool areAllFields32Or64BitBasicType(const RecordDecl *RD,
141 ASTContext &Context) {
142 for (RecordDecl::field_iterator i = RD->field_begin(Context),
143 e = RD->field_end(Context); i != e; ++i) {
144 const FieldDecl *FD = *i;
145
146 if (!is32Or64BitBasicType(FD->getType(), Context))
147 return false;
148
149 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
150 // how to expand them yet, and the predicate for telling if a bitfield still
151 // counts as "basic" is more complicated than what we were doing previously.
152 if (FD->isBitField())
153 return false;
154 }
155
156 return true;
157}
158
159namespace {
160/// DefaultABIInfo - The default implementation for ABI specific
161/// details. This implementation provides information which results in
162/// self-consistent and sensible LLVM IR generation, but does not
163/// conform to any particular ABI.
164class DefaultABIInfo : public ABIInfo {
165 ABIArgInfo classifyReturnType(QualType RetTy,
166 ASTContext &Context) const;
167
168 ABIArgInfo classifyArgumentType(QualType RetTy,
169 ASTContext &Context) const;
170
171 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
172 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
173 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
174 it != ie; ++it)
175 it->info = classifyArgumentType(it->type, Context);
176 }
177
178 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
179 CodeGenFunction &CGF) const;
180};
181
182/// X86_32ABIInfo - The X86-32 ABI information.
183class X86_32ABIInfo : public ABIInfo {
184 ASTContext &Context;
185 bool IsDarwin;
186
187 static bool isRegisterSize(unsigned Size) {
188 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
189 }
190
191 static bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context);
192
193public:
194 ABIArgInfo classifyReturnType(QualType RetTy,
195 ASTContext &Context) const;
196
197 ABIArgInfo classifyArgumentType(QualType RetTy,
198 ASTContext &Context) const;
199
200 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
201 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
202 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
203 it != ie; ++it)
204 it->info = classifyArgumentType(it->type, Context);
205 }
206
207 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
208 CodeGenFunction &CGF) const;
209
210 X86_32ABIInfo(ASTContext &Context, bool d)
211 : ABIInfo(), Context(Context), IsDarwin(d) {}
212};
213}
214
215
216/// shouldReturnTypeInRegister - Determine if the given type should be
217/// passed in a register (for the Darwin ABI).
218bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
219 ASTContext &Context) {
220 uint64_t Size = Context.getTypeSize(Ty);
221
222 // Type must be register sized.
223 if (!isRegisterSize(Size))
224 return false;
225
226 if (Ty->isVectorType()) {
227 // 64- and 128- bit vectors inside structures are not returned in
228 // registers.
229 if (Size == 64 || Size == 128)
230 return false;
231
232 return true;
233 }
234
235 // If this is a builtin, pointer, or complex type, it is ok.
236 if (Ty->getAsBuiltinType() || Ty->isPointerType() || Ty->isAnyComplexType())
237 return true;
238
239 // Arrays are treated like records.
240 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
241 return shouldReturnTypeInRegister(AT->getElementType(), Context);
242
243 // Otherwise, it must be a record type.
244 const RecordType *RT = Ty->getAsRecordType();
245 if (!RT) return false;
246
247 // Structure types are passed in register if all fields would be
248 // passed in a register.
249 for (RecordDecl::field_iterator i = RT->getDecl()->field_begin(Context),
250 e = RT->getDecl()->field_end(Context); i != e; ++i) {
251 const FieldDecl *FD = *i;
252
253 // Empty fields are ignored.
254 if (isEmptyField(Context, FD))
255 continue;
256
257 // Check fields recursively.
258 if (!shouldReturnTypeInRegister(FD->getType(), Context))
259 return false;
260 }
261
262 return true;
263}
264
265ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
266 ASTContext &Context) const {
267 if (RetTy->isVoidType()) {
268 return ABIArgInfo::getIgnore();
269 } else if (const VectorType *VT = RetTy->getAsVectorType()) {
270 // On Darwin, some vectors are returned in registers.
271 if (IsDarwin) {
272 uint64_t Size = Context.getTypeSize(RetTy);
273
274 // 128-bit vectors are a special case; they are returned in
275 // registers and we need to make sure to pick a type the LLVM
276 // backend will like.
277 if (Size == 128)
278 return ABIArgInfo::getCoerce(llvm::VectorType::get(llvm::Type::Int64Ty,
279 2));
280
281 // Always return in register if it fits in a general purpose
282 // register, or if it is 64 bits and has a single element.
283 if ((Size == 8 || Size == 16 || Size == 32) ||
284 (Size == 64 && VT->getNumElements() == 1))
285 return ABIArgInfo::getCoerce(llvm::IntegerType::get(Size));
286
287 return ABIArgInfo::getIndirect(0);
288 }
289
290 return ABIArgInfo::getDirect();
291 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
292 // Structures with flexible arrays are always indirect.
293 if (const RecordType *RT = RetTy->getAsStructureType())
294 if (RT->getDecl()->hasFlexibleArrayMember())
295 return ABIArgInfo::getIndirect(0);
296
297 // Outside of Darwin, structs and unions are always indirect.
298 if (!IsDarwin && !RetTy->isAnyComplexType())
299 return ABIArgInfo::getIndirect(0);
300
301 // Classify "single element" structs as their element type.
302 if (const Type *SeltTy = isSingleElementStruct(RetTy, Context)) {
303 if (const BuiltinType *BT = SeltTy->getAsBuiltinType()) {
304 if (BT->isIntegerType()) {
305 // We need to use the size of the structure, padding
306 // bit-fields can adjust that to be larger than the single
307 // element type.
308 uint64_t Size = Context.getTypeSize(RetTy);
309 return ABIArgInfo::getCoerce(llvm::IntegerType::get((unsigned) Size));
310 } else if (BT->getKind() == BuiltinType::Float) {
311 assert(Context.getTypeSize(RetTy) == Context.getTypeSize(SeltTy) &&
312 "Unexpect single element structure size!");
313 return ABIArgInfo::getCoerce(llvm::Type::FloatTy);
314 } else if (BT->getKind() == BuiltinType::Double) {
315 assert(Context.getTypeSize(RetTy) == Context.getTypeSize(SeltTy) &&
316 "Unexpect single element structure size!");
317 return ABIArgInfo::getCoerce(llvm::Type::DoubleTy);
318 }
319 } else if (SeltTy->isPointerType()) {
320 // FIXME: It would be really nice if this could come out as the proper
321 // pointer type.
322 llvm::Type *PtrTy =
323 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
324 return ABIArgInfo::getCoerce(PtrTy);
325 } else if (SeltTy->isVectorType()) {
326 // 64- and 128-bit vectors are never returned in a
327 // register when inside a structure.
328 uint64_t Size = Context.getTypeSize(RetTy);
329 if (Size == 64 || Size == 128)
330 return ABIArgInfo::getIndirect(0);
331
332 return classifyReturnType(QualType(SeltTy, 0), Context);
333 }
334 }
335
336 // Small structures which are register sized are generally returned
337 // in a register.
338 if (X86_32ABIInfo::shouldReturnTypeInRegister(RetTy, Context)) {
339 uint64_t Size = Context.getTypeSize(RetTy);
340 return ABIArgInfo::getCoerce(llvm::IntegerType::get(Size));
341 }
342
343 return ABIArgInfo::getIndirect(0);
344 } else {
345 return ABIArgInfo::getDirect();
346 }
347}
348
349ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
350 ASTContext &Context) const {
351 // FIXME: Set alignment on indirect arguments.
352 if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
353 // Structures with flexible arrays are always indirect.
354 if (const RecordType *RT = Ty->getAsStructureType())
355 if (RT->getDecl()->hasFlexibleArrayMember())
356 return ABIArgInfo::getIndirect(0);
357
358 // Ignore empty structs.
359 uint64_t Size = Context.getTypeSize(Ty);
360 if (Ty->isStructureType() && Size == 0)
361 return ABIArgInfo::getIgnore();
362
363 // Expand structs with size <= 128-bits which consist only of
364 // basic types (int, long long, float, double, xxx*). This is
365 // non-recursive and does not ignore empty fields.
366 if (const RecordType *RT = Ty->getAsStructureType()) {
367 if (Context.getTypeSize(Ty) <= 4*32 &&
368 areAllFields32Or64BitBasicType(RT->getDecl(), Context))
369 return ABIArgInfo::getExpand();
370 }
371
372 return ABIArgInfo::getIndirect(0);
373 } else {
374 return ABIArgInfo::getDirect();
375 }
376}
377
378llvm::Value *X86_32ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
379 CodeGenFunction &CGF) const {
380 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
381 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
382
383 CGBuilderTy &Builder = CGF.Builder;
384 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
385 "ap");
386 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
387 llvm::Type *PTy =
388 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
389 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
390
391 uint64_t Offset =
392 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
393 llvm::Value *NextAddr =
394 Builder.CreateGEP(Addr,
395 llvm::ConstantInt::get(llvm::Type::Int32Ty, Offset),
396 "ap.next");
397 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
398
399 return AddrTyped;
400}
401
402namespace {
403/// X86_64ABIInfo - The X86_64 ABI information.
404class X86_64ABIInfo : public ABIInfo {
405 enum Class {
406 Integer = 0,
407 SSE,
408 SSEUp,
409 X87,
410 X87Up,
411 ComplexX87,
412 NoClass,
413 Memory
414 };
415
416 /// merge - Implement the X86_64 ABI merging algorithm.
417 ///
418 /// Merge an accumulating classification \arg Accum with a field
419 /// classification \arg Field.
420 ///
421 /// \param Accum - The accumulating classification. This should
422 /// always be either NoClass or the result of a previous merge
423 /// call. In addition, this should never be Memory (the caller
424 /// should just return Memory for the aggregate).
425 Class merge(Class Accum, Class Field) const;
426
427 /// classify - Determine the x86_64 register classes in which the
428 /// given type T should be passed.
429 ///
430 /// \param Lo - The classification for the parts of the type
431 /// residing in the low word of the containing object.
432 ///
433 /// \param Hi - The classification for the parts of the type
434 /// residing in the high word of the containing object.
435 ///
436 /// \param OffsetBase - The bit offset of this type in the
437 /// containing object. Some parameters are classified different
438 /// depending on whether they straddle an eightbyte boundary.
439 ///
440 /// If a word is unused its result will be NoClass; if a type should
441 /// be passed in Memory then at least the classification of \arg Lo
442 /// will be Memory.
443 ///
444 /// The \arg Lo class will be NoClass iff the argument is ignored.
445 ///
446 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
447 /// also be ComplexX87.
448 void classify(QualType T, ASTContext &Context, uint64_t OffsetBase,
449 Class &Lo, Class &Hi) const;
450
451 /// getCoerceResult - Given a source type \arg Ty and an LLVM type
452 /// to coerce to, chose the best way to pass Ty in the same place
453 /// that \arg CoerceTo would be passed, but while keeping the
454 /// emitted code as simple as possible.
455 ///
456 /// FIXME: Note, this should be cleaned up to just take an enumeration of all
457 /// the ways we might want to pass things, instead of constructing an LLVM
458 /// type. This makes this code more explicit, and it makes it clearer that we
459 /// are also doing this for correctness in the case of passing scalar types.
460 ABIArgInfo getCoerceResult(QualType Ty,
461 const llvm::Type *CoerceTo,
462 ASTContext &Context) const;
463
464 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
465 /// such that the argument will be passed in memory.
466 ABIArgInfo getIndirectResult(QualType Ty,
467 ASTContext &Context) const;
468
469 ABIArgInfo classifyReturnType(QualType RetTy,
470 ASTContext &Context) const;
471
472 ABIArgInfo classifyArgumentType(QualType Ty,
473 ASTContext &Context,
474 unsigned &neededInt,
475 unsigned &neededSSE) const;
476
477public:
478 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const;
479
480 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
481 CodeGenFunction &CGF) const;
482};
483}
484
485X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum,
486 Class Field) const {
487 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
488 // classified recursively so that always two fields are
489 // considered. The resulting class is calculated according to
490 // the classes of the fields in the eightbyte:
491 //
492 // (a) If both classes are equal, this is the resulting class.
493 //
494 // (b) If one of the classes is NO_CLASS, the resulting class is
495 // the other class.
496 //
497 // (c) If one of the classes is MEMORY, the result is the MEMORY
498 // class.
499 //
500 // (d) If one of the classes is INTEGER, the result is the
501 // INTEGER.
502 //
503 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
504 // MEMORY is used as class.
505 //
506 // (f) Otherwise class SSE is used.
507
508 // Accum should never be memory (we should have returned) or
509 // ComplexX87 (because this cannot be passed in a structure).
510 assert((Accum != Memory && Accum != ComplexX87) &&
511 "Invalid accumulated classification during merge.");
512 if (Accum == Field || Field == NoClass)
513 return Accum;
514 else if (Field == Memory)
515 return Memory;
516 else if (Accum == NoClass)
517 return Field;
518 else if (Accum == Integer || Field == Integer)
519 return Integer;
520 else if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
521 Accum == X87 || Accum == X87Up)
522 return Memory;
523 else
524 return SSE;
525}
526
527void X86_64ABIInfo::classify(QualType Ty,
528 ASTContext &Context,
529 uint64_t OffsetBase,
530 Class &Lo, Class &Hi) const {
531 // FIXME: This code can be simplified by introducing a simple value class for
532 // Class pairs with appropriate constructor methods for the various
533 // situations.
534
535 // FIXME: Some of the split computations are wrong; unaligned vectors
536 // shouldn't be passed in registers for example, so there is no chance they
537 // can straddle an eightbyte. Verify & simplify.
538
539 Lo = Hi = NoClass;
540
541 Class &Current = OffsetBase < 64 ? Lo : Hi;
542 Current = Memory;
543
544 if (const BuiltinType *BT = Ty->getAsBuiltinType()) {
545 BuiltinType::Kind k = BT->getKind();
546
547 if (k == BuiltinType::Void) {
548 Current = NoClass;
549 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
550 Lo = Integer;
551 Hi = Integer;
552 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
553 Current = Integer;
554 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
555 Current = SSE;
556 } else if (k == BuiltinType::LongDouble) {
557 Lo = X87;
558 Hi = X87Up;
559 }
560 // FIXME: _Decimal32 and _Decimal64 are SSE.
561 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
562 } else if (const EnumType *ET = Ty->getAsEnumType()) {
563 // Classify the underlying integer type.
564 classify(ET->getDecl()->getIntegerType(), Context, OffsetBase, Lo, Hi);
565 } else if (Ty->hasPointerRepresentation()) {
566 Current = Integer;
567 } else if (const VectorType *VT = Ty->getAsVectorType()) {
568 uint64_t Size = Context.getTypeSize(VT);
569 if (Size == 32) {
570 // gcc passes all <4 x char>, <2 x short>, <1 x int>, <1 x
571 // float> as integer.
572 Current = Integer;
573
574 // If this type crosses an eightbyte boundary, it should be
575 // split.
576 uint64_t EB_Real = (OffsetBase) / 64;
577 uint64_t EB_Imag = (OffsetBase + Size - 1) / 64;
578 if (EB_Real != EB_Imag)
579 Hi = Lo;
580 } else if (Size == 64) {
581 // gcc passes <1 x double> in memory. :(
582 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
583 return;
584
585 // gcc passes <1 x long long> as INTEGER.
586 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong))
587 Current = Integer;
588 else
589 Current = SSE;
590
591 // If this type crosses an eightbyte boundary, it should be
592 // split.
593 if (OffsetBase && OffsetBase != 64)
594 Hi = Lo;
595 } else if (Size == 128) {
596 Lo = SSE;
597 Hi = SSEUp;
598 }
599 } else if (const ComplexType *CT = Ty->getAsComplexType()) {
600 QualType ET = Context.getCanonicalType(CT->getElementType());
601
602 uint64_t Size = Context.getTypeSize(Ty);
603 if (ET->isIntegralType()) {
604 if (Size <= 64)
605 Current = Integer;
606 else if (Size <= 128)
607 Lo = Hi = Integer;
608 } else if (ET == Context.FloatTy)
609 Current = SSE;
610 else if (ET == Context.DoubleTy)
611 Lo = Hi = SSE;
612 else if (ET == Context.LongDoubleTy)
613 Current = ComplexX87;
614
615 // If this complex type crosses an eightbyte boundary then it
616 // should be split.
617 uint64_t EB_Real = (OffsetBase) / 64;
618 uint64_t EB_Imag = (OffsetBase + Context.getTypeSize(ET)) / 64;
619 if (Hi == NoClass && EB_Real != EB_Imag)
620 Hi = Lo;
621 } else if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
622 // Arrays are treated like structures.
623
624 uint64_t Size = Context.getTypeSize(Ty);
625
626 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
627 // than two eightbytes, ..., it has class MEMORY.
628 if (Size > 128)
629 return;
630
631 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
632 // fields, it has class MEMORY.
633 //
634 // Only need to check alignment of array base.
635 if (OffsetBase % Context.getTypeAlign(AT->getElementType()))
636 return;
637
638 // Otherwise implement simplified merge. We could be smarter about
639 // this, but it isn't worth it and would be harder to verify.
640 Current = NoClass;
641 uint64_t EltSize = Context.getTypeSize(AT->getElementType());
642 uint64_t ArraySize = AT->getSize().getZExtValue();
643 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
644 Class FieldLo, FieldHi;
645 classify(AT->getElementType(), Context, Offset, FieldLo, FieldHi);
646 Lo = merge(Lo, FieldLo);
647 Hi = merge(Hi, FieldHi);
648 if (Lo == Memory || Hi == Memory)
649 break;
650 }
651
652 // Do post merger cleanup (see below). Only case we worry about is Memory.
653 if (Hi == Memory)
654 Lo = Memory;
655 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
656 } else if (const RecordType *RT = Ty->getAsRecordType()) {
657 uint64_t Size = Context.getTypeSize(Ty);
658
659 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
660 // than two eightbytes, ..., it has class MEMORY.
661 if (Size > 128)
662 return;
663
664 const RecordDecl *RD = RT->getDecl();
665
666 // Assume variable sized types are passed in memory.
667 if (RD->hasFlexibleArrayMember())
668 return;
669
670 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
671
672 // Reset Lo class, this will be recomputed.
673 Current = NoClass;
674 unsigned idx = 0;
675 for (RecordDecl::field_iterator i = RD->field_begin(Context),
676 e = RD->field_end(Context); i != e; ++i, ++idx) {
677 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
678 bool BitField = i->isBitField();
679
680 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
681 // fields, it has class MEMORY.
682 //
683 // Note, skip this test for bit-fields, see below.
684 if (!BitField && Offset % Context.getTypeAlign(i->getType())) {
685 Lo = Memory;
686 return;
687 }
688
689 // Classify this field.
690 //
691 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
692 // exceeds a single eightbyte, each is classified
693 // separately. Each eightbyte gets initialized to class
694 // NO_CLASS.
695 Class FieldLo, FieldHi;
696
697 // Bit-fields require special handling, they do not force the
698 // structure to be passed in memory even if unaligned, and
699 // therefore they can straddle an eightbyte.
700 if (BitField) {
701 // Ignore padding bit-fields.
702 if (i->isUnnamedBitfield())
703 continue;
704
705 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
706 uint64_t Size = i->getBitWidth()->EvaluateAsInt(Context).getZExtValue();
707
708 uint64_t EB_Lo = Offset / 64;
709 uint64_t EB_Hi = (Offset + Size - 1) / 64;
710 FieldLo = FieldHi = NoClass;
711 if (EB_Lo) {
712 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
713 FieldLo = NoClass;
714 FieldHi = Integer;
715 } else {
716 FieldLo = Integer;
717 FieldHi = EB_Hi ? Integer : NoClass;
718 }
719 } else
720 classify(i->getType(), Context, Offset, FieldLo, FieldHi);
721 Lo = merge(Lo, FieldLo);
722 Hi = merge(Hi, FieldHi);
723 if (Lo == Memory || Hi == Memory)
724 break;
725 }
726
727 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
728 //
729 // (a) If one of the classes is MEMORY, the whole argument is
730 // passed in memory.
731 //
732 // (b) If SSEUP is not preceeded by SSE, it is converted to SSE.
733
734 // The first of these conditions is guaranteed by how we implement
735 // the merge (just bail).
736 //
737 // The second condition occurs in the case of unions; for example
738 // union { _Complex double; unsigned; }.
739 if (Hi == Memory)
740 Lo = Memory;
741 if (Hi == SSEUp && Lo != SSE)
742 Hi = SSE;
743 }
744}
745
746ABIArgInfo X86_64ABIInfo::getCoerceResult(QualType Ty,
747 const llvm::Type *CoerceTo,
748 ASTContext &Context) const {
749 if (CoerceTo == llvm::Type::Int64Ty) {
750 // Integer and pointer types will end up in a general purpose
751 // register.
752 if (Ty->isIntegralType() || Ty->isPointerType())
753 return ABIArgInfo::getDirect();
754
755 } else if (CoerceTo == llvm::Type::DoubleTy) {
756 // FIXME: It would probably be better to make CGFunctionInfo only map using
757 // canonical types than to canonize here.
758 QualType CTy = Context.getCanonicalType(Ty);
759
760 // Float and double end up in a single SSE reg.
761 if (CTy == Context.FloatTy || CTy == Context.DoubleTy)
762 return ABIArgInfo::getDirect();
763
764 }
765
766 return ABIArgInfo::getCoerce(CoerceTo);
767}
768
769ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
770 ASTContext &Context) const {
771 // If this is a scalar LLVM value then assume LLVM will pass it in the right
772 // place naturally.
773 if (!CodeGenFunction::hasAggregateLLVMType(Ty))
774 return ABIArgInfo::getDirect();
775
776 // FIXME: Set alignment correctly.
777 return ABIArgInfo::getIndirect(0);
778}
779
780ABIArgInfo X86_64ABIInfo::classifyReturnType(QualType RetTy,
781 ASTContext &Context) const {
782 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
783 // classification algorithm.
784 X86_64ABIInfo::Class Lo, Hi;
785 classify(RetTy, Context, 0, Lo, Hi);
786
787 // Check some invariants.
788 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
789 assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification.");
790 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
791
792 const llvm::Type *ResType = 0;
793 switch (Lo) {
794 case NoClass:
795 return ABIArgInfo::getIgnore();
796
797 case SSEUp:
798 case X87Up:
799 assert(0 && "Invalid classification for lo word.");
800
801 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
802 // hidden argument.
803 case Memory:
804 return getIndirectResult(RetTy, Context);
805
806 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
807 // available register of the sequence %rax, %rdx is used.
808 case Integer:
809 ResType = llvm::Type::Int64Ty; break;
810
811 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
812 // available SSE register of the sequence %xmm0, %xmm1 is used.
813 case SSE:
814 ResType = llvm::Type::DoubleTy; break;
815
816 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
817 // returned on the X87 stack in %st0 as 80-bit x87 number.
818 case X87:
819 ResType = llvm::Type::X86_FP80Ty; break;
820
821 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
822 // part of the value is returned in %st0 and the imaginary part in
823 // %st1.
824 case ComplexX87:
825 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
826 ResType = llvm::StructType::get(llvm::Type::X86_FP80Ty,
827 llvm::Type::X86_FP80Ty,
828 NULL);
829 break;
830 }
831
832 switch (Hi) {
833 // Memory was handled previously and X87 should
834 // never occur as a hi class.
835 case Memory:
836 case X87:
837 assert(0 && "Invalid classification for hi word.");
838
839 case ComplexX87: // Previously handled.
840 case NoClass: break;
841
842 case Integer:
843 ResType = llvm::StructType::get(ResType, llvm::Type::Int64Ty, NULL);
844 break;
845 case SSE:
846 ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL);
847 break;
848
849 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
850 // is passed in the upper half of the last used SSE register.
851 //
852 // SSEUP should always be preceeded by SSE, just widen.
853 case SSEUp:
854 assert(Lo == SSE && "Unexpected SSEUp classification.");
855 ResType = llvm::VectorType::get(llvm::Type::DoubleTy, 2);
856 break;
857
858 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
859 // returned together with the previous X87 value in %st0.
860 case X87Up:
861 // If X87Up is preceeded by X87, we don't need to do
862 // anything. However, in some cases with unions it may not be
863 // preceeded by X87. In such situations we follow gcc and pass the
864 // extra bits in an SSE reg.
865 if (Lo != X87)
866 ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL);
867 break;
868 }
869
870 return getCoerceResult(RetTy, ResType, Context);
871}
872
873ABIArgInfo X86_64ABIInfo::classifyArgumentType(QualType Ty, ASTContext &Context,
874 unsigned &neededInt,
875 unsigned &neededSSE) const {
876 X86_64ABIInfo::Class Lo, Hi;
877 classify(Ty, Context, 0, Lo, Hi);
878
879 // Check some invariants.
880 // FIXME: Enforce these by construction.
881 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
882 assert((Lo != NoClass || Hi == NoClass) && "Invalid null classification.");
883 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
884
885 neededInt = 0;
886 neededSSE = 0;
887 const llvm::Type *ResType = 0;
888 switch (Lo) {
889 case NoClass:
890 return ABIArgInfo::getIgnore();
891
892 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
893 // on the stack.
894 case Memory:
895
896 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
897 // COMPLEX_X87, it is passed in memory.
898 case X87:
899 case ComplexX87:
900 return getIndirectResult(Ty, Context);
901
902 case SSEUp:
903 case X87Up:
904 assert(0 && "Invalid classification for lo word.");
905
906 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
907 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
908 // and %r9 is used.
909 case Integer:
910 ++neededInt;
911 ResType = llvm::Type::Int64Ty;
912 break;
913
914 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
915 // available SSE register is used, the registers are taken in the
916 // order from %xmm0 to %xmm7.
917 case SSE:
918 ++neededSSE;
919 ResType = llvm::Type::DoubleTy;
920 break;
921 }
922
923 switch (Hi) {
924 // Memory was handled previously, ComplexX87 and X87 should
925 // never occur as hi classes, and X87Up must be preceed by X87,
926 // which is passed in memory.
927 case Memory:
928 case X87:
929 case ComplexX87:
930 assert(0 && "Invalid classification for hi word.");
931 break;
932
933 case NoClass: break;
934 case Integer:
935 ResType = llvm::StructType::get(ResType, llvm::Type::Int64Ty, NULL);
936 ++neededInt;
937 break;
938
939 // X87Up generally doesn't occur here (long double is passed in
940 // memory), except in situations involving unions.
941 case X87Up:
942 case SSE:
943 ResType = llvm::StructType::get(ResType, llvm::Type::DoubleTy, NULL);
944 ++neededSSE;
945 break;
946
947 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
948 // eightbyte is passed in the upper half of the last used SSE
949 // register.
950 case SSEUp:
951 assert(Lo == SSE && "Unexpected SSEUp classification.");
952 ResType = llvm::VectorType::get(llvm::Type::DoubleTy, 2);
953 break;
954 }
955
956 return getCoerceResult(Ty, ResType, Context);
957}
958
959void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
960 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
961
962 // Keep track of the number of assigned registers.
963 unsigned freeIntRegs = 6, freeSSERegs = 8;
964
965 // If the return value is indirect, then the hidden argument is consuming one
966 // integer register.
967 if (FI.getReturnInfo().isIndirect())
968 --freeIntRegs;
969
970 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
971 // get assigned (in left-to-right order) for passing as follows...
972 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
973 it != ie; ++it) {
974 unsigned neededInt, neededSSE;
975 it->info = classifyArgumentType(it->type, Context, neededInt, neededSSE);
976
977 // AMD64-ABI 3.2.3p3: If there are no registers available for any
978 // eightbyte of an argument, the whole argument is passed on the
979 // stack. If registers have already been assigned for some
980 // eightbytes of such an argument, the assignments get reverted.
981 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
982 freeIntRegs -= neededInt;
983 freeSSERegs -= neededSSE;
984 } else {
985 it->info = getIndirectResult(it->type, Context);
986 }
987 }
988}
989
990static llvm::Value *EmitVAArgFromMemory(llvm::Value *VAListAddr,
991 QualType Ty,
992 CodeGenFunction &CGF) {
993 llvm::Value *overflow_arg_area_p =
994 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
995 llvm::Value *overflow_arg_area =
996 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
997
998 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
999 // byte boundary if alignment needed by type exceeds 8 byte boundary.
1000 uint64_t Align = CGF.getContext().getTypeAlign(Ty) / 8;
1001 if (Align > 8) {
1002 // Note that we follow the ABI & gcc here, even though the type
1003 // could in theory have an alignment greater than 16. This case
1004 // shouldn't ever matter in practice.
1005
1006 // overflow_arg_area = (overflow_arg_area + 15) & ~15;
1007 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty, 15);
1008 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
1009 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
1010 llvm::Type::Int64Ty);
1011 llvm::Value *Mask = llvm::ConstantInt::get(llvm::Type::Int64Ty, ~15LL);
1012 overflow_arg_area =
1013 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
1014 overflow_arg_area->getType(),
1015 "overflow_arg_area.align");
1016 }
1017
1018 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
1019 const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1020 llvm::Value *Res =
1021 CGF.Builder.CreateBitCast(overflow_arg_area,
1022 llvm::PointerType::getUnqual(LTy));
1023
1024 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
1025 // l->overflow_arg_area + sizeof(type).
1026 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
1027 // an 8 byte boundary.
1028
1029 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
1030 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty,
1031 (SizeInBytes + 7) & ~7);
1032 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
1033 "overflow_arg_area.next");
1034 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
1035
1036 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
1037 return Res;
1038}
1039
1040llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1041 CodeGenFunction &CGF) const {
1042 // Assume that va_list type is correct; should be pointer to LLVM type:
1043 // struct {
1044 // i32 gp_offset;
1045 // i32 fp_offset;
1046 // i8* overflow_arg_area;
1047 // i8* reg_save_area;
1048 // };
1049 unsigned neededInt, neededSSE;
1050 ABIArgInfo AI = classifyArgumentType(Ty, CGF.getContext(),
1051 neededInt, neededSSE);
1052
1053 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
1054 // in the registers. If not go to step 7.
1055 if (!neededInt && !neededSSE)
1056 return EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1057
1058 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
1059 // general purpose registers needed to pass type and num_fp to hold
1060 // the number of floating point registers needed.
1061
1062 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
1063 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
1064 // l->fp_offset > 304 - num_fp * 16 go to step 7.
1065 //
1066 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
1067 // register save space).
1068
1069 llvm::Value *InRegs = 0;
1070 llvm::Value *gp_offset_p = 0, *gp_offset = 0;
1071 llvm::Value *fp_offset_p = 0, *fp_offset = 0;
1072 if (neededInt) {
1073 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
1074 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
1075 InRegs =
1076 CGF.Builder.CreateICmpULE(gp_offset,
1077 llvm::ConstantInt::get(llvm::Type::Int32Ty,
1078 48 - neededInt * 8),
1079 "fits_in_gp");
1080 }
1081
1082 if (neededSSE) {
1083 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
1084 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
1085 llvm::Value *FitsInFP =
1086 CGF.Builder.CreateICmpULE(fp_offset,
1087 llvm::ConstantInt::get(llvm::Type::Int32Ty,
1088 176 - neededSSE * 16),
1089 "fits_in_fp");
1090 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
1091 }
1092
1093 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
1094 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
1095 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
1096 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
1097
1098 // Emit code to load the value if it was passed in registers.
1099
1100 CGF.EmitBlock(InRegBlock);
1101
1102 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
1103 // an offset of l->gp_offset and/or l->fp_offset. This may require
1104 // copying to a temporary location in case the parameter is passed
1105 // in different register classes or requires an alignment greater
1106 // than 8 for general purpose registers and 16 for XMM registers.
1107 //
1108 // FIXME: This really results in shameful code when we end up needing to
1109 // collect arguments from different places; often what should result in a
1110 // simple assembling of a structure from scattered addresses has many more
1111 // loads than necessary. Can we clean this up?
1112 const llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
1113 llvm::Value *RegAddr =
1114 CGF.Builder.CreateLoad(CGF.Builder.CreateStructGEP(VAListAddr, 3),
1115 "reg_save_area");
1116 if (neededInt && neededSSE) {
1117 // FIXME: Cleanup.
1118 assert(AI.isCoerce() && "Unexpected ABI info for mixed regs");
1119 const llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
1120 llvm::Value *Tmp = CGF.CreateTempAlloca(ST);
1121 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
1122 const llvm::Type *TyLo = ST->getElementType(0);
1123 const llvm::Type *TyHi = ST->getElementType(1);
1124 assert((TyLo->isFloatingPoint() ^ TyHi->isFloatingPoint()) &&
1125 "Unexpected ABI info for mixed regs");
1126 const llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
1127 const llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
1128 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1129 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1130 llvm::Value *RegLoAddr = TyLo->isFloatingPoint() ? FPAddr : GPAddr;
1131 llvm::Value *RegHiAddr = TyLo->isFloatingPoint() ? GPAddr : FPAddr;
1132 llvm::Value *V =
1133 CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
1134 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1135 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
1136 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1137
1138 RegAddr = CGF.Builder.CreateBitCast(Tmp, llvm::PointerType::getUnqual(LTy));
1139 } else if (neededInt) {
1140 RegAddr = CGF.Builder.CreateGEP(RegAddr, gp_offset);
1141 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1142 llvm::PointerType::getUnqual(LTy));
1143 } else {
1144 if (neededSSE == 1) {
1145 RegAddr = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1146 RegAddr = CGF.Builder.CreateBitCast(RegAddr,
1147 llvm::PointerType::getUnqual(LTy));
1148 } else {
1149 assert(neededSSE == 2 && "Invalid number of needed registers!");
1150 // SSE registers are spaced 16 bytes apart in the register save
1151 // area, we need to collect the two eightbytes together.
1152 llvm::Value *RegAddrLo = CGF.Builder.CreateGEP(RegAddr, fp_offset);
1153 llvm::Value *RegAddrHi =
1154 CGF.Builder.CreateGEP(RegAddrLo,
1155 llvm::ConstantInt::get(llvm::Type::Int32Ty, 16));
1156 const llvm::Type *DblPtrTy =
1157 llvm::PointerType::getUnqual(llvm::Type::DoubleTy);
1158 const llvm::StructType *ST = llvm::StructType::get(llvm::Type::DoubleTy,
1159 llvm::Type::DoubleTy,
1160 NULL);
1161 llvm::Value *V, *Tmp = CGF.CreateTempAlloca(ST);
1162 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrLo,
1163 DblPtrTy));
1164 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
1165 V = CGF.Builder.CreateLoad(CGF.Builder.CreateBitCast(RegAddrHi,
1166 DblPtrTy));
1167 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
1168 RegAddr = CGF.Builder.CreateBitCast(Tmp,
1169 llvm::PointerType::getUnqual(LTy));
1170 }
1171 }
1172
1173 // AMD64-ABI 3.5.7p5: Step 5. Set:
1174 // l->gp_offset = l->gp_offset + num_gp * 8
1175 // l->fp_offset = l->fp_offset + num_fp * 16.
1176 if (neededInt) {
1177 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty,
1178 neededInt * 8);
1179 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
1180 gp_offset_p);
1181 }
1182 if (neededSSE) {
1183 llvm::Value *Offset = llvm::ConstantInt::get(llvm::Type::Int32Ty,
1184 neededSSE * 16);
1185 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
1186 fp_offset_p);
1187 }
1188 CGF.EmitBranch(ContBlock);
1189
1190 // Emit code to load the value if it was passed in memory.
1191
1192 CGF.EmitBlock(InMemBlock);
1193 llvm::Value *MemAddr = EmitVAArgFromMemory(VAListAddr, Ty, CGF);
1194
1195 // Return the appropriate result.
1196
1197 CGF.EmitBlock(ContBlock);
1198 llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(RegAddr->getType(),
1199 "vaarg.addr");
1200 ResAddr->reserveOperandSpace(2);
1201 ResAddr->addIncoming(RegAddr, InRegBlock);
1202 ResAddr->addIncoming(MemAddr, InMemBlock);
1203
1204 return ResAddr;
1205}
1206
1207// ABI Info for PIC16
1208class PIC16ABIInfo : public ABIInfo {
1209 ABIArgInfo classifyReturnType(QualType RetTy,
1210 ASTContext &Context) const;
1211
1212 ABIArgInfo classifyArgumentType(QualType RetTy,
1213 ASTContext &Context) const;
1214
1215 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
1216 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
1217 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1218 it != ie; ++it)
1219 it->info = classifyArgumentType(it->type, Context);
1220 }
1221
1222 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1223 CodeGenFunction &CGF) const;
1224
1225};
1226
1227ABIArgInfo PIC16ABIInfo::classifyReturnType(QualType RetTy,
1228 ASTContext &Context) const {
1229 if (RetTy->isVoidType()) {
1230 return ABIArgInfo::getIgnore();
1231 } else {
1232 return ABIArgInfo::getDirect();
1233 }
1234}
1235
1236ABIArgInfo PIC16ABIInfo::classifyArgumentType(QualType Ty,
1237 ASTContext &Context) const {
1238 return ABIArgInfo::getDirect();
1239}
1240
1241llvm::Value *PIC16ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1242 CodeGenFunction &CGF) const {
1243 return 0;
1244}
1245
1246class ARMABIInfo : public ABIInfo {
1247 ABIArgInfo classifyReturnType(QualType RetTy,
1248 ASTContext &Context) const;
1249
1250 ABIArgInfo classifyArgumentType(QualType RetTy,
1251 ASTContext &Context) const;
1252
1253 virtual void computeInfo(CGFunctionInfo &FI, ASTContext &Context) const;
1254
1255 virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1256 CodeGenFunction &CGF) const;
1257};
1258
1259void ARMABIInfo::computeInfo(CGFunctionInfo &FI, ASTContext &Context) const {
1260 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), Context);
1261 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
1262 it != ie; ++it) {
1263 it->info = classifyArgumentType(it->type, Context);
1264 }
1265}
1266
1267ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
1268 ASTContext &Context) const {
1269 if (!CodeGenFunction::hasAggregateLLVMType(Ty)) {
1270 return ABIArgInfo::getDirect();
1271 }
1272 // FIXME: This is kind of nasty... but there isn't much choice because the ARM
1273 // backend doesn't support byval.
1274 // FIXME: This doesn't handle alignment > 64 bits.
1275 const llvm::Type* ElemTy;
1276 unsigned SizeRegs;
1277 if (Context.getTypeAlign(Ty) > 32) {
1278 ElemTy = llvm::Type::Int64Ty;
1279 SizeRegs = (Context.getTypeSize(Ty) + 63) / 64;
1280 } else {
1281 ElemTy = llvm::Type::Int32Ty;
1282 SizeRegs = (Context.getTypeSize(Ty) + 31) / 32;
1283 }
1284 std::vector<const llvm::Type*> LLVMFields;
1285 LLVMFields.push_back(llvm::ArrayType::get(ElemTy, SizeRegs));
1286 const llvm::Type* STy = llvm::StructType::get(LLVMFields, true);
1287 return ABIArgInfo::getCoerce(STy);
1288}
1289
1290ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
1291 ASTContext &Context) const {
1292 if (RetTy->isVoidType()) {
1293 return ABIArgInfo::getIgnore();
1294 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1295 // Aggregates <= 4 bytes are returned in r0; other aggregates
1296 // are returned indirectly.
1297 uint64_t Size = Context.getTypeSize(RetTy);
1298 if (Size <= 32)
1299 return ABIArgInfo::getCoerce(llvm::Type::Int32Ty);
1300 return ABIArgInfo::getIndirect(0);
1301 } else {
1302 return ABIArgInfo::getDirect();
1303 }
1304}
1305
1306llvm::Value *ARMABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1307 CodeGenFunction &CGF) const {
1308 // FIXME: Need to handle alignment
1309 const llvm::Type *BP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
1310 const llvm::Type *BPP = llvm::PointerType::getUnqual(BP);
1311
1312 CGBuilderTy &Builder = CGF.Builder;
1313 llvm::Value *VAListAddrAsBPP = Builder.CreateBitCast(VAListAddr, BPP,
1314 "ap");
1315 llvm::Value *Addr = Builder.CreateLoad(VAListAddrAsBPP, "ap.cur");
1316 llvm::Type *PTy =
1317 llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
1318 llvm::Value *AddrTyped = Builder.CreateBitCast(Addr, PTy);
1319
1320 uint64_t Offset =
1321 llvm::RoundUpToAlignment(CGF.getContext().getTypeSize(Ty) / 8, 4);
1322 llvm::Value *NextAddr =
1323 Builder.CreateGEP(Addr,
1324 llvm::ConstantInt::get(llvm::Type::Int32Ty, Offset),
1325 "ap.next");
1326 Builder.CreateStore(NextAddr, VAListAddrAsBPP);
1327
1328 return AddrTyped;
1329}
1330
1331ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy,
1332 ASTContext &Context) const {
1333 if (RetTy->isVoidType()) {
1334 return ABIArgInfo::getIgnore();
1335 } else if (CodeGenFunction::hasAggregateLLVMType(RetTy)) {
1336 return ABIArgInfo::getIndirect(0);
1337 } else {
1338 return ABIArgInfo::getDirect();
1339 }
1340}
1341
1342ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty,
1343 ASTContext &Context) const {
1344 if (CodeGenFunction::hasAggregateLLVMType(Ty)) {
1345 return ABIArgInfo::getIndirect(0);
1346 } else {
1347 return ABIArgInfo::getDirect();
1348 }
1349}
1350
1351llvm::Value *DefaultABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
1352 CodeGenFunction &CGF) const {
1353 return 0;
1354}
1355
1356const ABIInfo &CodeGenTypes::getABIInfo() const {
1357 if (TheABIInfo)
1358 return *TheABIInfo;
1359
1360 // For now we just cache this in the CodeGenTypes and don't bother
1361 // to free it.
1362 const char *TargetPrefix = getContext().Target.getTargetPrefix();
1363 if (strcmp(TargetPrefix, "x86") == 0) {
1364 bool IsDarwin = strstr(getContext().Target.getTargetTriple(), "darwin");
1365 switch (getContext().Target.getPointerWidth(0)) {
1366 case 32:
1367 return *(TheABIInfo = new X86_32ABIInfo(Context, IsDarwin));
1368 case 64:
1369 return *(TheABIInfo = new X86_64ABIInfo());
1370 }
1371 } else if (strcmp(TargetPrefix, "arm") == 0) {
1372 // FIXME: Support for OABI?
1373 return *(TheABIInfo = new ARMABIInfo());
1374 } else if (strcmp(TargetPrefix, "pic16") == 0) {
1375 return *(TheABIInfo = new PIC16ABIInfo());
1376 }
1377
1378 return *(TheABIInfo = new DefaultABIInfo);
1379}