1 //===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===//
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 // This contains code to emit Aggregate Expr nodes as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CodeGenModule.h"
16 #include "CGObjCRuntime.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/StmtVisitor.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Function.h"
22 #include "llvm/GlobalVariable.h"
23 #include "llvm/Intrinsics.h"
24 using namespace clang;
25 using namespace CodeGen;
26 
27 //===----------------------------------------------------------------------===//
28 //                        Aggregate Expression Emitter
29 //===----------------------------------------------------------------------===//
30 
31 namespace  {
32 class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
33   CodeGenFunction &CGF;
34   CGBuilderTy &Builder;
35   llvm::Value *DestPtr;
36   bool VolatileDest;
37   bool IgnoreResult;
38   bool IsInitializer;
39   bool RequiresGCollection;
40 
41   ReturnValueSlot getReturnValueSlot() const {
42     // If the destination slot requires garbage collection, we can't
43     // use the real return value slot, because we have to use the GC
44     // API.
45     if (RequiresGCollection) return ReturnValueSlot();
46 
47     return ReturnValueSlot(DestPtr, VolatileDest);
48   }
49 
50 public:
51   AggExprEmitter(CodeGenFunction &cgf, llvm::Value *destPtr, bool v,
52                  bool ignore, bool isinit, bool requiresGCollection)
53     : CGF(cgf), Builder(CGF.Builder),
54       DestPtr(destPtr), VolatileDest(v), IgnoreResult(ignore),
55       IsInitializer(isinit), RequiresGCollection(requiresGCollection) {
56   }
57 
58   //===--------------------------------------------------------------------===//
59   //                               Utilities
60   //===--------------------------------------------------------------------===//
61 
62   /// EmitAggLoadOfLValue - Given an expression with aggregate type that
63   /// represents a value lvalue, this method emits the address of the lvalue,
64   /// then loads the result into DestPtr.
65   void EmitAggLoadOfLValue(const Expr *E);
66 
67   /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
68   void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false);
69   void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false);
70 
71   void EmitGCMove(const Expr *E, RValue Src);
72 
73   bool TypeRequiresGCollection(QualType T);
74 
75   //===--------------------------------------------------------------------===//
76   //                            Visitor Methods
77   //===--------------------------------------------------------------------===//
78 
79   void VisitStmt(Stmt *S) {
80     CGF.ErrorUnsupported(S, "aggregate expression");
81   }
82   void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
83   void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
84 
85   // l-values.
86   void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); }
87   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
88   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
89   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
90   void VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
91     EmitAggLoadOfLValue(E);
92   }
93   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
94     EmitAggLoadOfLValue(E);
95   }
96   void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
97     EmitAggLoadOfLValue(E);
98   }
99   void VisitPredefinedExpr(const PredefinedExpr *E) {
100     EmitAggLoadOfLValue(E);
101   }
102 
103   // Operators.
104   void VisitCastExpr(CastExpr *E);
105   void VisitCallExpr(const CallExpr *E);
106   void VisitStmtExpr(const StmtExpr *E);
107   void VisitBinaryOperator(const BinaryOperator *BO);
108   void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
109   void VisitBinAssign(const BinaryOperator *E);
110   void VisitBinComma(const BinaryOperator *E);
111 
112   void VisitObjCMessageExpr(ObjCMessageExpr *E);
113   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
114     EmitAggLoadOfLValue(E);
115   }
116   void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E);
117   void VisitObjCImplicitSetterGetterRefExpr(ObjCImplicitSetterGetterRefExpr *E);
118 
119   void VisitConditionalOperator(const ConditionalOperator *CO);
120   void VisitChooseExpr(const ChooseExpr *CE);
121   void VisitInitListExpr(InitListExpr *E);
122   void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
123   void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
124     Visit(DAE->getExpr());
125   }
126   void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
127   void VisitCXXConstructExpr(const CXXConstructExpr *E);
128   void VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E);
129   void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
130   void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
131 
132   void VisitVAArgExpr(VAArgExpr *E);
133 
134   void EmitInitializationToLValue(Expr *E, LValue Address, QualType T);
135   void EmitNullInitializationToLValue(LValue Address, QualType T);
136   //  case Expr::ChooseExprClass:
137   void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
138 };
139 }  // end anonymous namespace.
140 
141 //===----------------------------------------------------------------------===//
142 //                                Utilities
143 //===----------------------------------------------------------------------===//
144 
145 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
146 /// represents a value lvalue, this method emits the address of the lvalue,
147 /// then loads the result into DestPtr.
148 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
149   LValue LV = CGF.EmitLValue(E);
150   EmitFinalDestCopy(E, LV);
151 }
152 
153 /// \brief True if the given aggregate type requires special GC API calls.
154 bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
155   // Only record types have members that might require garbage collection.
156   const RecordType *RecordTy = T->getAs<RecordType>();
157   if (!RecordTy) return false;
158 
159   // Don't mess with non-trivial C++ types.
160   RecordDecl *Record = RecordTy->getDecl();
161   if (isa<CXXRecordDecl>(Record) &&
162       (!cast<CXXRecordDecl>(Record)->hasTrivialCopyConstructor() ||
163        !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
164     return false;
165 
166   // Check whether the type has an object member.
167   return Record->hasObjectMember();
168 }
169 
170 /// \brief Perform the final move to DestPtr if RequiresGCollection is set.
171 ///
172 /// The idea is that you do something like this:
173 ///   RValue Result = EmitSomething(..., getReturnValueSlot());
174 ///   EmitGCMove(E, Result);
175 /// If GC doesn't interfere, this will cause the result to be emitted
176 /// directly into the return value slot.  If GC does interfere, a final
177 /// move will be performed.
178 void AggExprEmitter::EmitGCMove(const Expr *E, RValue Src) {
179   if (RequiresGCollection) {
180     std::pair<uint64_t, unsigned> TypeInfo =
181       CGF.getContext().getTypeInfo(E->getType());
182     unsigned long size = TypeInfo.first/8;
183     const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
184     llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size);
185     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, DestPtr,
186                                                     Src.getAggregateAddr(),
187                                                     SizeVal);
188   }
189 }
190 
191 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
192 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) {
193   assert(Src.isAggregate() && "value must be aggregate value!");
194 
195   // If the result is ignored, don't copy from the value.
196   if (DestPtr == 0) {
197     if (!Src.isVolatileQualified() || (IgnoreResult && Ignore))
198       return;
199     // If the source is volatile, we must read from it; to do that, we need
200     // some place to put it.
201     DestPtr = CGF.CreateMemTemp(E->getType(), "agg.tmp");
202   }
203 
204   if (RequiresGCollection) {
205     std::pair<uint64_t, unsigned> TypeInfo =
206     CGF.getContext().getTypeInfo(E->getType());
207     unsigned long size = TypeInfo.first/8;
208     const llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
209     llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size);
210     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
211                                               DestPtr, Src.getAggregateAddr(),
212                                               SizeVal);
213     return;
214   }
215   // If the result of the assignment is used, copy the LHS there also.
216   // FIXME: Pass VolatileDest as well.  I think we also need to merge volatile
217   // from the source as well, as we can't eliminate it if either operand
218   // is volatile, unless copy has volatile for both source and destination..
219   CGF.EmitAggregateCopy(DestPtr, Src.getAggregateAddr(), E->getType(),
220                         VolatileDest|Src.isVolatileQualified());
221 }
222 
223 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
224 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) {
225   assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc");
226 
227   EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(),
228                                             Src.isVolatileQualified()),
229                     Ignore);
230 }
231 
232 //===----------------------------------------------------------------------===//
233 //                            Visitor Methods
234 //===----------------------------------------------------------------------===//
235 
236 void AggExprEmitter::VisitCastExpr(CastExpr *E) {
237   if (!DestPtr && E->getCastKind() != CastExpr::CK_Dynamic) {
238     Visit(E->getSubExpr());
239     return;
240   }
241 
242   switch (E->getCastKind()) {
243   default: assert(0 && "Unhandled cast kind!");
244 
245   case CastExpr::CK_Dynamic: {
246     assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
247     LValue LV = CGF.EmitCheckedLValue(E->getSubExpr());
248     // FIXME: Do we also need to handle property references here?
249     if (LV.isSimple())
250       CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
251     else
252       CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
253 
254     if (DestPtr)
255       CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
256     break;
257   }
258 
259   case CastExpr::CK_ToUnion: {
260     // GCC union extension
261     QualType Ty = E->getSubExpr()->getType();
262     QualType PtrTy = CGF.getContext().getPointerType(Ty);
263     llvm::Value *CastPtr = Builder.CreateBitCast(DestPtr,
264                                                  CGF.ConvertType(PtrTy));
265     EmitInitializationToLValue(E->getSubExpr(), CGF.MakeAddrLValue(CastPtr, Ty),
266                                Ty);
267     break;
268   }
269 
270   case CastExpr::CK_DerivedToBase:
271   case CastExpr::CK_BaseToDerived:
272   case CastExpr::CK_UncheckedDerivedToBase: {
273     assert(0 && "cannot perform hierarchy conversion in EmitAggExpr: "
274                 "should have been unpacked before we got here");
275     break;
276   }
277 
278   // FIXME: Remove the CK_Unknown check here.
279   case CastExpr::CK_Unknown:
280   case CastExpr::CK_NoOp:
281   case CastExpr::CK_UserDefinedConversion:
282   case CastExpr::CK_ConstructorConversion:
283     assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
284                                                    E->getType()) &&
285            "Implicit cast types must be compatible");
286     Visit(E->getSubExpr());
287     break;
288 
289   case CastExpr::CK_LValueBitCast:
290     llvm_unreachable("there are no lvalue bit-casts on aggregates");
291     break;
292   }
293 }
294 
295 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
296   if (E->getCallReturnType()->isReferenceType()) {
297     EmitAggLoadOfLValue(E);
298     return;
299   }
300 
301   RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
302   EmitGCMove(E, RV);
303 }
304 
305 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
306   RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
307   EmitGCMove(E, RV);
308 }
309 
310 void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
311   RValue RV = CGF.EmitObjCPropertyGet(E, getReturnValueSlot());
312   EmitGCMove(E, RV);
313 }
314 
315 void AggExprEmitter::VisitObjCImplicitSetterGetterRefExpr(
316                                    ObjCImplicitSetterGetterRefExpr *E) {
317   RValue RV = CGF.EmitObjCPropertyGet(E, getReturnValueSlot());
318   EmitGCMove(E, RV);
319 }
320 
321 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
322   CGF.EmitAnyExpr(E->getLHS(), 0, false, true);
323   CGF.EmitAggExpr(E->getRHS(), DestPtr, VolatileDest,
324                   /*IgnoreResult=*/false, IsInitializer);
325 }
326 
327 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
328   CGF.EmitCompoundStmt(*E->getSubStmt(), true, DestPtr, VolatileDest);
329 }
330 
331 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
332   if (E->getOpcode() == BinaryOperator::PtrMemD ||
333       E->getOpcode() == BinaryOperator::PtrMemI)
334     VisitPointerToDataMemberBinaryOperator(E);
335   else
336     CGF.ErrorUnsupported(E, "aggregate binary expression");
337 }
338 
339 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
340                                                     const BinaryOperator *E) {
341   LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
342   EmitFinalDestCopy(E, LV);
343 }
344 
345 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
346   // For an assignment to work, the value on the right has
347   // to be compatible with the value on the left.
348   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
349                                                  E->getRHS()->getType())
350          && "Invalid assignment");
351   LValue LHS = CGF.EmitLValue(E->getLHS());
352 
353   // We have to special case property setters, otherwise we must have
354   // a simple lvalue (no aggregates inside vectors, bitfields).
355   if (LHS.isPropertyRef()) {
356     llvm::Value *AggLoc = DestPtr;
357     if (!AggLoc)
358       AggLoc = CGF.CreateMemTemp(E->getRHS()->getType());
359     CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
360     CGF.EmitObjCPropertySet(LHS.getPropertyRefExpr(),
361                             RValue::getAggregate(AggLoc, VolatileDest));
362   } else if (LHS.isKVCRef()) {
363     llvm::Value *AggLoc = DestPtr;
364     if (!AggLoc)
365       AggLoc = CGF.CreateMemTemp(E->getRHS()->getType());
366     CGF.EmitAggExpr(E->getRHS(), AggLoc, VolatileDest);
367     CGF.EmitObjCPropertySet(LHS.getKVCRefExpr(),
368                             RValue::getAggregate(AggLoc, VolatileDest));
369   } else {
370     bool RequiresGCollection = false;
371     if (CGF.getContext().getLangOptions().getGCMode())
372       RequiresGCollection = TypeRequiresGCollection(E->getLHS()->getType());
373 
374     // Codegen the RHS so that it stores directly into the LHS.
375     CGF.EmitAggExpr(E->getRHS(), LHS.getAddress(), LHS.isVolatileQualified(),
376                     false, false, RequiresGCollection);
377     EmitFinalDestCopy(E, LHS, true);
378   }
379 }
380 
381 void AggExprEmitter::VisitConditionalOperator(const ConditionalOperator *E) {
382   if (!E->getLHS()) {
383     CGF.ErrorUnsupported(E, "conditional operator with missing LHS");
384     return;
385   }
386 
387   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
388   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
389   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
390 
391   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
392 
393   CGF.BeginConditionalBranch();
394   CGF.EmitBlock(LHSBlock);
395 
396   // Handle the GNU extension for missing LHS.
397   assert(E->getLHS() && "Must have LHS for aggregate value");
398 
399   Visit(E->getLHS());
400   CGF.EndConditionalBranch();
401   CGF.EmitBranch(ContBlock);
402 
403   CGF.BeginConditionalBranch();
404   CGF.EmitBlock(RHSBlock);
405 
406   Visit(E->getRHS());
407   CGF.EndConditionalBranch();
408   CGF.EmitBranch(ContBlock);
409 
410   CGF.EmitBlock(ContBlock);
411 }
412 
413 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
414   Visit(CE->getChosenSubExpr(CGF.getContext()));
415 }
416 
417 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
418   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
419   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
420 
421   if (!ArgPtr) {
422     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
423     return;
424   }
425 
426   EmitFinalDestCopy(VE, CGF.MakeAddrLValue(ArgPtr, VE->getType()));
427 }
428 
429 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
430   llvm::Value *Val = DestPtr;
431 
432   if (!Val) {
433     // Create a temporary variable.
434     Val = CGF.CreateMemTemp(E->getType(), "tmp");
435 
436     // FIXME: volatile
437     CGF.EmitAggExpr(E->getSubExpr(), Val, false);
438   } else
439     Visit(E->getSubExpr());
440 
441   // Don't make this a live temporary if we're emitting an initializer expr.
442   if (!IsInitializer)
443     CGF.EmitCXXTemporary(E->getTemporary(), Val);
444 }
445 
446 void
447 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
448   llvm::Value *Val = DestPtr;
449 
450   if (!Val) // Create a temporary variable.
451     Val = CGF.CreateMemTemp(E->getType(), "tmp");
452 
453   CGF.EmitCXXConstructExpr(Val, E);
454 }
455 
456 void AggExprEmitter::VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
457   llvm::Value *Val = DestPtr;
458 
459   CGF.EmitCXXExprWithTemporaries(E, Val, VolatileDest, IsInitializer);
460 }
461 
462 void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
463   llvm::Value *Val = DestPtr;
464 
465   if (!Val) {
466     // Create a temporary variable.
467     Val = CGF.CreateMemTemp(E->getType(), "tmp");
468   }
469   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Val, E->getType()),
470                                  E->getType());
471 }
472 
473 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
474   llvm::Value *Val = DestPtr;
475 
476   if (!Val) {
477     // Create a temporary variable.
478     Val = CGF.CreateMemTemp(E->getType(), "tmp");
479   }
480   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Val, E->getType()),
481                                  E->getType());
482 }
483 
484 void
485 AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV, QualType T) {
486   // FIXME: Ignore result?
487   // FIXME: Are initializers affected by volatile?
488   if (isa<ImplicitValueInitExpr>(E)) {
489     EmitNullInitializationToLValue(LV, T);
490   } else if (T->isReferenceType()) {
491     RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
492     CGF.EmitStoreThroughLValue(RV, LV, T);
493   } else if (T->isAnyComplexType()) {
494     CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
495   } else if (CGF.hasAggregateLLVMType(T)) {
496     CGF.EmitAnyExpr(E, LV.getAddress(), false);
497   } else {
498     CGF.EmitStoreThroughLValue(CGF.EmitAnyExpr(E), LV, T);
499   }
500 }
501 
502 void AggExprEmitter::EmitNullInitializationToLValue(LValue LV, QualType T) {
503   if (!CGF.hasAggregateLLVMType(T)) {
504     // For non-aggregates, we can store zero
505     llvm::Value *Null = llvm::Constant::getNullValue(CGF.ConvertType(T));
506     CGF.EmitStoreThroughLValue(RValue::get(Null), LV, T);
507   } else {
508     // There's a potential optimization opportunity in combining
509     // memsets; that would be easy for arrays, but relatively
510     // difficult for structures with the current code.
511     CGF.EmitNullInitialization(LV.getAddress(), T);
512   }
513 }
514 
515 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
516 #if 0
517   // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
518   // (Length of globals? Chunks of zeroed-out space?).
519   //
520   // If we can, prefer a copy from a global; this is a lot less code for long
521   // globals, and it's easier for the current optimizers to analyze.
522   if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
523     llvm::GlobalVariable* GV =
524     new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
525                              llvm::GlobalValue::InternalLinkage, C, "");
526     EmitFinalDestCopy(E, CGF.MakeAddrLValue(GV, E->getType()));
527     return;
528   }
529 #endif
530   if (E->hadArrayRangeDesignator()) {
531     CGF.ErrorUnsupported(E, "GNU array range designator extension");
532   }
533 
534   // Handle initialization of an array.
535   if (E->getType()->isArrayType()) {
536     const llvm::PointerType *APType =
537       cast<llvm::PointerType>(DestPtr->getType());
538     const llvm::ArrayType *AType =
539       cast<llvm::ArrayType>(APType->getElementType());
540 
541     uint64_t NumInitElements = E->getNumInits();
542 
543     if (E->getNumInits() > 0) {
544       QualType T1 = E->getType();
545       QualType T2 = E->getInit(0)->getType();
546       if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
547         EmitAggLoadOfLValue(E->getInit(0));
548         return;
549       }
550     }
551 
552     uint64_t NumArrayElements = AType->getNumElements();
553     QualType ElementType = CGF.getContext().getCanonicalType(E->getType());
554     ElementType = CGF.getContext().getAsArrayType(ElementType)->getElementType();
555 
556     // FIXME: were we intentionally ignoring address spaces and GC attributes?
557 
558     for (uint64_t i = 0; i != NumArrayElements; ++i) {
559       llvm::Value *NextVal = Builder.CreateStructGEP(DestPtr, i, ".array");
560       LValue LV = CGF.MakeAddrLValue(NextVal, ElementType);
561       if (i < NumInitElements)
562         EmitInitializationToLValue(E->getInit(i), LV, ElementType);
563 
564       else
565         EmitNullInitializationToLValue(LV, ElementType);
566     }
567     return;
568   }
569 
570   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
571 
572   // Do struct initialization; this code just sets each individual member
573   // to the approprate value.  This makes bitfield support automatic;
574   // the disadvantage is that the generated code is more difficult for
575   // the optimizer, especially with bitfields.
576   unsigned NumInitElements = E->getNumInits();
577   RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
578   unsigned CurInitVal = 0;
579 
580   if (E->getType()->isUnionType()) {
581     // Only initialize one field of a union. The field itself is
582     // specified by the initializer list.
583     if (!E->getInitializedFieldInUnion()) {
584       // Empty union; we have nothing to do.
585 
586 #ifndef NDEBUG
587       // Make sure that it's really an empty and not a failure of
588       // semantic analysis.
589       for (RecordDecl::field_iterator Field = SD->field_begin(),
590                                    FieldEnd = SD->field_end();
591            Field != FieldEnd; ++Field)
592         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
593 #endif
594       return;
595     }
596 
597     // FIXME: volatility
598     FieldDecl *Field = E->getInitializedFieldInUnion();
599     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0);
600 
601     if (NumInitElements) {
602       // Store the initializer into the field
603       EmitInitializationToLValue(E->getInit(0), FieldLoc, Field->getType());
604     } else {
605       // Default-initialize to null
606       EmitNullInitializationToLValue(FieldLoc, Field->getType());
607     }
608 
609     return;
610   }
611 
612   // If we're initializing the whole aggregate, just do it in place.
613   // FIXME: This is a hack around an AST bug (PR6537).
614   if (NumInitElements == 1 && E->getType() == E->getInit(0)->getType()) {
615     EmitInitializationToLValue(E->getInit(0),
616                                CGF.MakeAddrLValue(DestPtr, E->getType()),
617                                E->getType());
618     return;
619   }
620 
621 
622   // Here we iterate over the fields; this makes it simpler to both
623   // default-initialize fields and skip over unnamed fields.
624   for (RecordDecl::field_iterator Field = SD->field_begin(),
625                                FieldEnd = SD->field_end();
626        Field != FieldEnd; ++Field) {
627     // We're done once we hit the flexible array member
628     if (Field->getType()->isIncompleteArrayType())
629       break;
630 
631     if (Field->isUnnamedBitfield())
632       continue;
633 
634     // FIXME: volatility
635     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, *Field, 0);
636     // We never generate write-barries for initialized fields.
637     FieldLoc.setNonGC(true);
638     if (CurInitVal < NumInitElements) {
639       // Store the initializer into the field.
640       EmitInitializationToLValue(E->getInit(CurInitVal++), FieldLoc,
641                                  Field->getType());
642     } else {
643       // We're out of initalizers; default-initialize to null
644       EmitNullInitializationToLValue(FieldLoc, Field->getType());
645     }
646   }
647 }
648 
649 //===----------------------------------------------------------------------===//
650 //                        Entry Points into this File
651 //===----------------------------------------------------------------------===//
652 
653 /// EmitAggExpr - Emit the computation of the specified expression of aggregate
654 /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
655 /// the value of the aggregate expression is not needed.  If VolatileDest is
656 /// true, DestPtr cannot be 0.
657 //
658 // FIXME: Take Qualifiers object.
659 void CodeGenFunction::EmitAggExpr(const Expr *E, llvm::Value *DestPtr,
660                                   bool VolatileDest, bool IgnoreResult,
661                                   bool IsInitializer,
662                                   bool RequiresGCollection) {
663   assert(E && hasAggregateLLVMType(E->getType()) &&
664          "Invalid aggregate expression to emit");
665   assert ((DestPtr != 0 || VolatileDest == false)
666           && "volatile aggregate can't be 0");
667 
668   AggExprEmitter(*this, DestPtr, VolatileDest, IgnoreResult, IsInitializer,
669                  RequiresGCollection)
670     .Visit(const_cast<Expr*>(E));
671 }
672 
673 LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
674   assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!");
675   llvm::Value *Temp = CreateMemTemp(E->getType());
676   LValue LV = MakeAddrLValue(Temp, E->getType());
677   EmitAggExpr(E, Temp, LV.isVolatileQualified());
678   return LV;
679 }
680 
681 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
682                                         llvm::Value *SrcPtr, QualType Ty,
683                                         bool isVolatile) {
684   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
685 
686   if (getContext().getLangOptions().CPlusPlus) {
687     if (const RecordType *RT = Ty->getAs<RecordType>()) {
688       CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
689       assert((Record->hasTrivialCopyConstructor() ||
690               Record->hasTrivialCopyAssignment()) &&
691              "Trying to aggregate-copy a type without a trivial copy "
692              "constructor or assignment operator");
693       // Ignore empty classes in C++.
694       if (Record->isEmpty())
695         return;
696     }
697   }
698 
699   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
700   // C99 6.5.16.1p3, which states "If the value being stored in an object is
701   // read from another object that overlaps in anyway the storage of the first
702   // object, then the overlap shall be exact and the two objects shall have
703   // qualified or unqualified versions of a compatible type."
704   //
705   // memcpy is not defined if the source and destination pointers are exactly
706   // equal, but other compilers do this optimization, and almost every memcpy
707   // implementation handles this case safely.  If there is a libc that does not
708   // safely handle this, we can add a target hook.
709 
710   // Get size and alignment info for this aggregate.
711   std::pair<uint64_t, unsigned> TypeInfo = getContext().getTypeInfo(Ty);
712 
713   // FIXME: Handle variable sized types.
714 
715   // FIXME: If we have a volatile struct, the optimizer can remove what might
716   // appear to be `extra' memory ops:
717   //
718   // volatile struct { int i; } a, b;
719   //
720   // int main() {
721   //   a = b;
722   //   a = b;
723   // }
724   //
725   // we need to use a different call here.  We use isVolatile to indicate when
726   // either the source or the destination is volatile.
727 
728   const llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
729   const llvm::Type *DBP =
730     llvm::Type::getInt8PtrTy(VMContext, DPT->getAddressSpace());
731   DestPtr = Builder.CreateBitCast(DestPtr, DBP, "tmp");
732 
733   const llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
734   const llvm::Type *SBP =
735     llvm::Type::getInt8PtrTy(VMContext, SPT->getAddressSpace());
736   SrcPtr = Builder.CreateBitCast(SrcPtr, SBP, "tmp");
737 
738   if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
739     RecordDecl *Record = RecordTy->getDecl();
740     if (Record->hasObjectMember()) {
741       unsigned long size = TypeInfo.first/8;
742       const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
743       llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size);
744       CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
745                                                     SizeVal);
746       return;
747     }
748   } else if (getContext().getAsArrayType(Ty)) {
749     QualType BaseType = getContext().getBaseElementType(Ty);
750     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
751       if (RecordTy->getDecl()->hasObjectMember()) {
752         unsigned long size = TypeInfo.first/8;
753         const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
754         llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size);
755         CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
756                                                       SizeVal);
757         return;
758       }
759     }
760   }
761 
762   Builder.CreateCall5(CGM.getMemCpyFn(DestPtr->getType(), SrcPtr->getType(),
763                                       IntPtrTy),
764                       DestPtr, SrcPtr,
765                       // TypeInfo.first describes size in bits.
766                       llvm::ConstantInt::get(IntPtrTy, TypeInfo.first/8),
767                       Builder.getInt32(TypeInfo.second/8),
768                       Builder.getInt1(isVolatile));
769 }
770