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/DeclTemplate.h"
20 #include "clang/AST/StmtVisitor.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Intrinsics.h"
25 using namespace clang;
26 using namespace CodeGen;
27 
28 //===----------------------------------------------------------------------===//
29 //                        Aggregate Expression Emitter
30 //===----------------------------------------------------------------------===//
31 
32 namespace  {
33 class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
34   CodeGenFunction &CGF;
35   CGBuilderTy &Builder;
36   AggValueSlot Dest;
37   bool IgnoreResult;
38 
39   /// We want to use 'dest' as the return slot except under two
40   /// conditions:
41   ///   - The destination slot requires garbage collection, so we
42   ///     need to use the GC API.
43   ///   - The destination slot is potentially aliased.
44   bool shouldUseDestForReturnSlot() const {
45     return !(Dest.requiresGCollection() || Dest.isPotentiallyAliased());
46   }
47 
48   ReturnValueSlot getReturnValueSlot() const {
49     if (!shouldUseDestForReturnSlot())
50       return ReturnValueSlot();
51 
52     return ReturnValueSlot(Dest.getAddr(), Dest.isVolatile());
53   }
54 
55   AggValueSlot EnsureSlot(QualType T) {
56     if (!Dest.isIgnored()) return Dest;
57     return CGF.CreateAggTemp(T, "agg.tmp.ensured");
58   }
59 
60 public:
61   AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest,
62                  bool ignore)
63     : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
64       IgnoreResult(ignore) {
65   }
66 
67   //===--------------------------------------------------------------------===//
68   //                               Utilities
69   //===--------------------------------------------------------------------===//
70 
71   /// EmitAggLoadOfLValue - Given an expression with aggregate type that
72   /// represents a value lvalue, this method emits the address of the lvalue,
73   /// then loads the result into DestPtr.
74   void EmitAggLoadOfLValue(const Expr *E);
75 
76   /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
77   void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false);
78   void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false,
79                          unsigned Alignment = 0);
80 
81   void EmitMoveFromReturnSlot(const Expr *E, RValue Src);
82 
83   void EmitStdInitializerList(llvm::Value *DestPtr, InitListExpr *InitList);
84   void EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
85                      QualType elementType, InitListExpr *E);
86 
87   AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
88     if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))
89       return AggValueSlot::NeedsGCBarriers;
90     return AggValueSlot::DoesNotNeedGCBarriers;
91   }
92 
93   bool TypeRequiresGCollection(QualType T);
94 
95   //===--------------------------------------------------------------------===//
96   //                            Visitor Methods
97   //===--------------------------------------------------------------------===//
98 
99   void VisitStmt(Stmt *S) {
100     CGF.ErrorUnsupported(S, "aggregate expression");
101   }
102   void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
103   void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
104     Visit(GE->getResultExpr());
105   }
106   void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
107   void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
108     return Visit(E->getReplacement());
109   }
110 
111   // l-values.
112   void VisitDeclRefExpr(DeclRefExpr *E) {
113     // For aggregates, we should always be able to emit the variable
114     // as an l-value unless it's a reference.  This is due to the fact
115     // that we can't actually ever see a normal l2r conversion on an
116     // aggregate in C++, and in C there's no language standard
117     // actively preventing us from listing variables in the captures
118     // list of a block.
119     if (E->getDecl()->getType()->isReferenceType()) {
120       if (CodeGenFunction::ConstantEmission result
121             = CGF.tryEmitAsConstant(E)) {
122         EmitFinalDestCopy(E, result.getReferenceLValue(CGF, E));
123         return;
124       }
125     }
126 
127     EmitAggLoadOfLValue(E);
128   }
129 
130   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
131   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
132   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
133   void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
134   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
135     EmitAggLoadOfLValue(E);
136   }
137   void VisitPredefinedExpr(const PredefinedExpr *E) {
138     EmitAggLoadOfLValue(E);
139   }
140 
141   // Operators.
142   void VisitCastExpr(CastExpr *E);
143   void VisitCallExpr(const CallExpr *E);
144   void VisitStmtExpr(const StmtExpr *E);
145   void VisitBinaryOperator(const BinaryOperator *BO);
146   void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
147   void VisitBinAssign(const BinaryOperator *E);
148   void VisitBinComma(const BinaryOperator *E);
149 
150   void VisitObjCMessageExpr(ObjCMessageExpr *E);
151   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
152     EmitAggLoadOfLValue(E);
153   }
154 
155   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
156   void VisitChooseExpr(const ChooseExpr *CE);
157   void VisitInitListExpr(InitListExpr *E);
158   void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
159   void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
160     Visit(DAE->getExpr());
161   }
162   void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
163   void VisitCXXConstructExpr(const CXXConstructExpr *E);
164   void VisitLambdaExpr(LambdaExpr *E);
165   void VisitExprWithCleanups(ExprWithCleanups *E);
166   void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
167   void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
168   void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
169   void VisitOpaqueValueExpr(OpaqueValueExpr *E);
170 
171   void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
172     if (E->isGLValue()) {
173       LValue LV = CGF.EmitPseudoObjectLValue(E);
174       return EmitFinalDestCopy(E, LV);
175     }
176 
177     CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
178   }
179 
180   void VisitVAArgExpr(VAArgExpr *E);
181 
182   void EmitInitializationToLValue(Expr *E, LValue Address);
183   void EmitNullInitializationToLValue(LValue Address);
184   //  case Expr::ChooseExprClass:
185   void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
186   void VisitAtomicExpr(AtomicExpr *E) {
187     CGF.EmitAtomicExpr(E, EnsureSlot(E->getType()).getAddr());
188   }
189 };
190 }  // end anonymous namespace.
191 
192 //===----------------------------------------------------------------------===//
193 //                                Utilities
194 //===----------------------------------------------------------------------===//
195 
196 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
197 /// represents a value lvalue, this method emits the address of the lvalue,
198 /// then loads the result into DestPtr.
199 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
200   LValue LV = CGF.EmitLValue(E);
201   EmitFinalDestCopy(E, LV);
202 }
203 
204 /// \brief True if the given aggregate type requires special GC API calls.
205 bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
206   // Only record types have members that might require garbage collection.
207   const RecordType *RecordTy = T->getAs<RecordType>();
208   if (!RecordTy) return false;
209 
210   // Don't mess with non-trivial C++ types.
211   RecordDecl *Record = RecordTy->getDecl();
212   if (isa<CXXRecordDecl>(Record) &&
213       (!cast<CXXRecordDecl>(Record)->hasTrivialCopyConstructor() ||
214        !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
215     return false;
216 
217   // Check whether the type has an object member.
218   return Record->hasObjectMember();
219 }
220 
221 /// \brief Perform the final move to DestPtr if for some reason
222 /// getReturnValueSlot() didn't use it directly.
223 ///
224 /// The idea is that you do something like this:
225 ///   RValue Result = EmitSomething(..., getReturnValueSlot());
226 ///   EmitMoveFromReturnSlot(E, Result);
227 ///
228 /// If nothing interferes, this will cause the result to be emitted
229 /// directly into the return value slot.  Otherwise, a final move
230 /// will be performed.
231 void AggExprEmitter::EmitMoveFromReturnSlot(const Expr *E, RValue Src) {
232   if (shouldUseDestForReturnSlot()) {
233     // Logically, Dest.getAddr() should equal Src.getAggregateAddr().
234     // The possibility of undef rvalues complicates that a lot,
235     // though, so we can't really assert.
236     return;
237   }
238 
239   // Otherwise, do a final copy,
240   assert(Dest.getAddr() != Src.getAggregateAddr());
241   EmitFinalDestCopy(E, Src, /*Ignore*/ true);
242 }
243 
244 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
245 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore,
246                                        unsigned Alignment) {
247   assert(Src.isAggregate() && "value must be aggregate value!");
248 
249   // If Dest is ignored, then we're evaluating an aggregate expression
250   // in a context (like an expression statement) that doesn't care
251   // about the result.  C says that an lvalue-to-rvalue conversion is
252   // performed in these cases; C++ says that it is not.  In either
253   // case, we don't actually need to do anything unless the value is
254   // volatile.
255   if (Dest.isIgnored()) {
256     if (!Src.isVolatileQualified() ||
257         CGF.CGM.getLangOpts().CPlusPlus ||
258         (IgnoreResult && Ignore))
259       return;
260 
261     // If the source is volatile, we must read from it; to do that, we need
262     // some place to put it.
263     Dest = CGF.CreateAggTemp(E->getType(), "agg.tmp");
264   }
265 
266   if (Dest.requiresGCollection()) {
267     CharUnits size = CGF.getContext().getTypeSizeInChars(E->getType());
268     llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
269     llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
270     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
271                                                       Dest.getAddr(),
272                                                       Src.getAggregateAddr(),
273                                                       SizeVal);
274     return;
275   }
276   // If the result of the assignment is used, copy the LHS there also.
277   // FIXME: Pass VolatileDest as well.  I think we also need to merge volatile
278   // from the source as well, as we can't eliminate it if either operand
279   // is volatile, unless copy has volatile for both source and destination..
280   CGF.EmitAggregateCopy(Dest.getAddr(), Src.getAggregateAddr(), E->getType(),
281                         Dest.isVolatile()|Src.isVolatileQualified(),
282                         Alignment);
283 }
284 
285 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
286 void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) {
287   assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc");
288 
289   CharUnits Alignment = std::min(Src.getAlignment(), Dest.getAlignment());
290   EmitFinalDestCopy(E, Src.asAggregateRValue(), Ignore, Alignment.getQuantity());
291 }
292 
293 static QualType GetStdInitializerListElementType(QualType T) {
294   // Just assume that this is really std::initializer_list.
295   ClassTemplateSpecializationDecl *specialization =
296       cast<ClassTemplateSpecializationDecl>(T->castAs<RecordType>()->getDecl());
297   return specialization->getTemplateArgs()[0].getAsType();
298 }
299 
300 /// \brief Prepare cleanup for the temporary array.
301 static void EmitStdInitializerListCleanup(CodeGenFunction &CGF,
302                                           QualType arrayType,
303                                           llvm::Value *addr,
304                                           const InitListExpr *initList) {
305   QualType::DestructionKind dtorKind = arrayType.isDestructedType();
306   if (!dtorKind)
307     return; // Type doesn't need destroying.
308   if (dtorKind != QualType::DK_cxx_destructor) {
309     CGF.ErrorUnsupported(initList, "ObjC ARC type in initializer_list");
310     return;
311   }
312 
313   CodeGenFunction::Destroyer *destroyer = CGF.getDestroyer(dtorKind);
314   CGF.pushDestroy(NormalAndEHCleanup, addr, arrayType, destroyer,
315                   /*EHCleanup=*/true);
316 }
317 
318 /// \brief Emit the initializer for a std::initializer_list initialized with a
319 /// real initializer list.
320 void AggExprEmitter::EmitStdInitializerList(llvm::Value *destPtr,
321                                             InitListExpr *initList) {
322   // We emit an array containing the elements, then have the init list point
323   // at the array.
324   ASTContext &ctx = CGF.getContext();
325   unsigned numInits = initList->getNumInits();
326   QualType element = GetStdInitializerListElementType(initList->getType());
327   llvm::APInt size(ctx.getTypeSize(ctx.getSizeType()), numInits);
328   QualType array = ctx.getConstantArrayType(element, size, ArrayType::Normal,0);
329   llvm::Type *LTy = CGF.ConvertTypeForMem(array);
330   llvm::AllocaInst *alloc = CGF.CreateTempAlloca(LTy);
331   alloc->setAlignment(ctx.getTypeAlignInChars(array).getQuantity());
332   alloc->setName(".initlist.");
333 
334   EmitArrayInit(alloc, cast<llvm::ArrayType>(LTy), element, initList);
335 
336   // FIXME: The diagnostics are somewhat out of place here.
337   RecordDecl *record = initList->getType()->castAs<RecordType>()->getDecl();
338   RecordDecl::field_iterator field = record->field_begin();
339   if (field == record->field_end()) {
340     CGF.ErrorUnsupported(initList, "weird std::initializer_list");
341     return;
342   }
343 
344   QualType elementPtr = ctx.getPointerType(element.withConst());
345 
346   // Start pointer.
347   if (!ctx.hasSameType(field->getType(), elementPtr)) {
348     CGF.ErrorUnsupported(initList, "weird std::initializer_list");
349     return;
350   }
351   LValue start = CGF.EmitLValueForFieldInitialization(destPtr, *field, 0);
352   llvm::Value *arrayStart = Builder.CreateStructGEP(alloc, 0, "arraystart");
353   CGF.EmitStoreThroughLValue(RValue::get(arrayStart), start);
354   ++field;
355 
356   if (field == record->field_end()) {
357     CGF.ErrorUnsupported(initList, "weird std::initializer_list");
358     return;
359   }
360   LValue endOrLength = CGF.EmitLValueForFieldInitialization(destPtr, *field, 0);
361   if (ctx.hasSameType(field->getType(), elementPtr)) {
362     // End pointer.
363     llvm::Value *arrayEnd = Builder.CreateStructGEP(alloc,numInits, "arrayend");
364     CGF.EmitStoreThroughLValue(RValue::get(arrayEnd), endOrLength);
365   } else if(ctx.hasSameType(field->getType(), ctx.getSizeType())) {
366     // Length.
367     CGF.EmitStoreThroughLValue(RValue::get(Builder.getInt(size)), endOrLength);
368   } else {
369     CGF.ErrorUnsupported(initList, "weird std::initializer_list");
370     return;
371   }
372 
373   if (!Dest.isExternallyDestructed())
374     EmitStdInitializerListCleanup(CGF, array, alloc, initList);
375 }
376 
377 /// \brief Emit initialization of an array from an initializer list.
378 void AggExprEmitter::EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
379                                    QualType elementType, InitListExpr *E) {
380   uint64_t NumInitElements = E->getNumInits();
381 
382   uint64_t NumArrayElements = AType->getNumElements();
383   assert(NumInitElements <= NumArrayElements);
384 
385   // DestPtr is an array*.  Construct an elementType* by drilling
386   // down a level.
387   llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
388   llvm::Value *indices[] = { zero, zero };
389   llvm::Value *begin =
390     Builder.CreateInBoundsGEP(DestPtr, indices, "arrayinit.begin");
391 
392   // Exception safety requires us to destroy all the
393   // already-constructed members if an initializer throws.
394   // For that, we'll need an EH cleanup.
395   QualType::DestructionKind dtorKind = elementType.isDestructedType();
396   llvm::AllocaInst *endOfInit = 0;
397   EHScopeStack::stable_iterator cleanup;
398   llvm::Instruction *cleanupDominator = 0;
399   if (CGF.needsEHCleanup(dtorKind)) {
400     // In principle we could tell the cleanup where we are more
401     // directly, but the control flow can get so varied here that it
402     // would actually be quite complex.  Therefore we go through an
403     // alloca.
404     endOfInit = CGF.CreateTempAlloca(begin->getType(),
405                                      "arrayinit.endOfInit");
406     cleanupDominator = Builder.CreateStore(begin, endOfInit);
407     CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
408                                          CGF.getDestroyer(dtorKind));
409     cleanup = CGF.EHStack.stable_begin();
410 
411   // Otherwise, remember that we didn't need a cleanup.
412   } else {
413     dtorKind = QualType::DK_none;
414   }
415 
416   llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
417 
418   // The 'current element to initialize'.  The invariants on this
419   // variable are complicated.  Essentially, after each iteration of
420   // the loop, it points to the last initialized element, except
421   // that it points to the beginning of the array before any
422   // elements have been initialized.
423   llvm::Value *element = begin;
424 
425   // Emit the explicit initializers.
426   for (uint64_t i = 0; i != NumInitElements; ++i) {
427     // Advance to the next element.
428     if (i > 0) {
429       element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element");
430 
431       // Tell the cleanup that it needs to destroy up to this
432       // element.  TODO: some of these stores can be trivially
433       // observed to be unnecessary.
434       if (endOfInit) Builder.CreateStore(element, endOfInit);
435     }
436 
437     // If these are nested std::initializer_list inits, do them directly,
438     // because they are conceptually the same "location".
439     InitListExpr *initList = dyn_cast<InitListExpr>(E->getInit(i));
440     if (initList && initList->initializesStdInitializerList()) {
441       EmitStdInitializerList(element, initList);
442     } else {
443       LValue elementLV = CGF.MakeAddrLValue(element, elementType);
444       EmitInitializationToLValue(E->getInit(i), elementLV);
445     }
446   }
447 
448   // Check whether there's a non-trivial array-fill expression.
449   // Note that this will be a CXXConstructExpr even if the element
450   // type is an array (or array of array, etc.) of class type.
451   Expr *filler = E->getArrayFiller();
452   bool hasTrivialFiller = true;
453   if (CXXConstructExpr *cons = dyn_cast_or_null<CXXConstructExpr>(filler)) {
454     assert(cons->getConstructor()->isDefaultConstructor());
455     hasTrivialFiller = cons->getConstructor()->isTrivial();
456   }
457 
458   // Any remaining elements need to be zero-initialized, possibly
459   // using the filler expression.  We can skip this if the we're
460   // emitting to zeroed memory.
461   if (NumInitElements != NumArrayElements &&
462       !(Dest.isZeroed() && hasTrivialFiller &&
463         CGF.getTypes().isZeroInitializable(elementType))) {
464 
465     // Use an actual loop.  This is basically
466     //   do { *array++ = filler; } while (array != end);
467 
468     // Advance to the start of the rest of the array.
469     if (NumInitElements) {
470       element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start");
471       if (endOfInit) Builder.CreateStore(element, endOfInit);
472     }
473 
474     // Compute the end of the array.
475     llvm::Value *end = Builder.CreateInBoundsGEP(begin,
476                       llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
477                                                  "arrayinit.end");
478 
479     llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
480     llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
481 
482     // Jump into the body.
483     CGF.EmitBlock(bodyBB);
484     llvm::PHINode *currentElement =
485       Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
486     currentElement->addIncoming(element, entryBB);
487 
488     // Emit the actual filler expression.
489     LValue elementLV = CGF.MakeAddrLValue(currentElement, elementType);
490     if (filler)
491       EmitInitializationToLValue(filler, elementLV);
492     else
493       EmitNullInitializationToLValue(elementLV);
494 
495     // Move on to the next element.
496     llvm::Value *nextElement =
497       Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
498 
499     // Tell the EH cleanup that we finished with the last element.
500     if (endOfInit) Builder.CreateStore(nextElement, endOfInit);
501 
502     // Leave the loop if we're done.
503     llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
504                                              "arrayinit.done");
505     llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
506     Builder.CreateCondBr(done, endBB, bodyBB);
507     currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
508 
509     CGF.EmitBlock(endBB);
510   }
511 
512   // Leave the partial-array cleanup if we entered one.
513   if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator);
514 }
515 
516 //===----------------------------------------------------------------------===//
517 //                            Visitor Methods
518 //===----------------------------------------------------------------------===//
519 
520 void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
521   Visit(E->GetTemporaryExpr());
522 }
523 
524 void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
525   EmitFinalDestCopy(e, CGF.getOpaqueLValueMapping(e));
526 }
527 
528 void
529 AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
530   if (E->getType().isPODType(CGF.getContext())) {
531     // For a POD type, just emit a load of the lvalue + a copy, because our
532     // compound literal might alias the destination.
533     // FIXME: This is a band-aid; the real problem appears to be in our handling
534     // of assignments, where we store directly into the LHS without checking
535     // whether anything in the RHS aliases.
536     EmitAggLoadOfLValue(E);
537     return;
538   }
539 
540   AggValueSlot Slot = EnsureSlot(E->getType());
541   CGF.EmitAggExpr(E->getInitializer(), Slot);
542 }
543 
544 
545 void AggExprEmitter::VisitCastExpr(CastExpr *E) {
546   switch (E->getCastKind()) {
547   case CK_Dynamic: {
548     assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
549     LValue LV = CGF.EmitCheckedLValue(E->getSubExpr());
550     // FIXME: Do we also need to handle property references here?
551     if (LV.isSimple())
552       CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
553     else
554       CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
555 
556     if (!Dest.isIgnored())
557       CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
558     break;
559   }
560 
561   case CK_ToUnion: {
562     if (Dest.isIgnored()) break;
563 
564     // GCC union extension
565     QualType Ty = E->getSubExpr()->getType();
566     QualType PtrTy = CGF.getContext().getPointerType(Ty);
567     llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
568                                                  CGF.ConvertType(PtrTy));
569     EmitInitializationToLValue(E->getSubExpr(),
570                                CGF.MakeAddrLValue(CastPtr, Ty));
571     break;
572   }
573 
574   case CK_DerivedToBase:
575   case CK_BaseToDerived:
576   case CK_UncheckedDerivedToBase: {
577     llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
578                 "should have been unpacked before we got here");
579   }
580 
581   case CK_LValueToRValue: // hope for downstream optimization
582   case CK_NoOp:
583   case CK_AtomicToNonAtomic:
584   case CK_NonAtomicToAtomic:
585   case CK_UserDefinedConversion:
586   case CK_ConstructorConversion:
587     assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
588                                                    E->getType()) &&
589            "Implicit cast types must be compatible");
590     Visit(E->getSubExpr());
591     break;
592 
593   case CK_LValueBitCast:
594     llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
595 
596   case CK_Dependent:
597   case CK_BitCast:
598   case CK_ArrayToPointerDecay:
599   case CK_FunctionToPointerDecay:
600   case CK_NullToPointer:
601   case CK_NullToMemberPointer:
602   case CK_BaseToDerivedMemberPointer:
603   case CK_DerivedToBaseMemberPointer:
604   case CK_MemberPointerToBoolean:
605   case CK_ReinterpretMemberPointer:
606   case CK_IntegralToPointer:
607   case CK_PointerToIntegral:
608   case CK_PointerToBoolean:
609   case CK_ToVoid:
610   case CK_VectorSplat:
611   case CK_IntegralCast:
612   case CK_IntegralToBoolean:
613   case CK_IntegralToFloating:
614   case CK_FloatingToIntegral:
615   case CK_FloatingToBoolean:
616   case CK_FloatingCast:
617   case CK_CPointerToObjCPointerCast:
618   case CK_BlockPointerToObjCPointerCast:
619   case CK_AnyPointerToBlockPointerCast:
620   case CK_ObjCObjectLValueCast:
621   case CK_FloatingRealToComplex:
622   case CK_FloatingComplexToReal:
623   case CK_FloatingComplexToBoolean:
624   case CK_FloatingComplexCast:
625   case CK_FloatingComplexToIntegralComplex:
626   case CK_IntegralRealToComplex:
627   case CK_IntegralComplexToReal:
628   case CK_IntegralComplexToBoolean:
629   case CK_IntegralComplexCast:
630   case CK_IntegralComplexToFloatingComplex:
631   case CK_ARCProduceObject:
632   case CK_ARCConsumeObject:
633   case CK_ARCReclaimReturnedObject:
634   case CK_ARCExtendBlockObject:
635   case CK_CopyAndAutoreleaseBlockObject:
636     llvm_unreachable("cast kind invalid for aggregate types");
637   }
638 }
639 
640 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
641   if (E->getCallReturnType()->isReferenceType()) {
642     EmitAggLoadOfLValue(E);
643     return;
644   }
645 
646   RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
647   EmitMoveFromReturnSlot(E, RV);
648 }
649 
650 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
651   RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
652   EmitMoveFromReturnSlot(E, RV);
653 }
654 
655 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
656   CGF.EmitIgnoredExpr(E->getLHS());
657   Visit(E->getRHS());
658 }
659 
660 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
661   CodeGenFunction::StmtExprEvaluation eval(CGF);
662   CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
663 }
664 
665 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
666   if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
667     VisitPointerToDataMemberBinaryOperator(E);
668   else
669     CGF.ErrorUnsupported(E, "aggregate binary expression");
670 }
671 
672 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
673                                                     const BinaryOperator *E) {
674   LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
675   EmitFinalDestCopy(E, LV);
676 }
677 
678 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
679   // For an assignment to work, the value on the right has
680   // to be compatible with the value on the left.
681   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
682                                                  E->getRHS()->getType())
683          && "Invalid assignment");
684 
685   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getLHS()))
686     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
687       if (VD->hasAttr<BlocksAttr>() &&
688           E->getRHS()->HasSideEffects(CGF.getContext())) {
689         // When __block variable on LHS, the RHS must be evaluated first
690         // as it may change the 'forwarding' field via call to Block_copy.
691         LValue RHS = CGF.EmitLValue(E->getRHS());
692         LValue LHS = CGF.EmitLValue(E->getLHS());
693         Dest = AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
694                                        needsGC(E->getLHS()->getType()),
695                                        AggValueSlot::IsAliased);
696         EmitFinalDestCopy(E, RHS, true);
697         return;
698       }
699 
700   LValue LHS = CGF.EmitLValue(E->getLHS());
701 
702   // Codegen the RHS so that it stores directly into the LHS.
703   AggValueSlot LHSSlot =
704     AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
705                             needsGC(E->getLHS()->getType()),
706                             AggValueSlot::IsAliased);
707   CGF.EmitAggExpr(E->getRHS(), LHSSlot, false);
708   EmitFinalDestCopy(E, LHS, true);
709 }
710 
711 void AggExprEmitter::
712 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
713   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
714   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
715   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
716 
717   // Bind the common expression if necessary.
718   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
719 
720   CodeGenFunction::ConditionalEvaluation eval(CGF);
721   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
722 
723   // Save whether the destination's lifetime is externally managed.
724   bool isExternallyDestructed = Dest.isExternallyDestructed();
725 
726   eval.begin(CGF);
727   CGF.EmitBlock(LHSBlock);
728   Visit(E->getTrueExpr());
729   eval.end(CGF);
730 
731   assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
732   CGF.Builder.CreateBr(ContBlock);
733 
734   // If the result of an agg expression is unused, then the emission
735   // of the LHS might need to create a destination slot.  That's fine
736   // with us, and we can safely emit the RHS into the same slot, but
737   // we shouldn't claim that it's already being destructed.
738   Dest.setExternallyDestructed(isExternallyDestructed);
739 
740   eval.begin(CGF);
741   CGF.EmitBlock(RHSBlock);
742   Visit(E->getFalseExpr());
743   eval.end(CGF);
744 
745   CGF.EmitBlock(ContBlock);
746 }
747 
748 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
749   Visit(CE->getChosenSubExpr(CGF.getContext()));
750 }
751 
752 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
753   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
754   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
755 
756   if (!ArgPtr) {
757     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
758     return;
759   }
760 
761   EmitFinalDestCopy(VE, CGF.MakeAddrLValue(ArgPtr, VE->getType()));
762 }
763 
764 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
765   // Ensure that we have a slot, but if we already do, remember
766   // whether it was externally destructed.
767   bool wasExternallyDestructed = Dest.isExternallyDestructed();
768   Dest = EnsureSlot(E->getType());
769 
770   // We're going to push a destructor if there isn't already one.
771   Dest.setExternallyDestructed();
772 
773   Visit(E->getSubExpr());
774 
775   // Push that destructor we promised.
776   if (!wasExternallyDestructed)
777     CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddr());
778 }
779 
780 void
781 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
782   AggValueSlot Slot = EnsureSlot(E->getType());
783   CGF.EmitCXXConstructExpr(E, Slot);
784 }
785 
786 void
787 AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
788   AggValueSlot Slot = EnsureSlot(E->getType());
789   CGF.EmitLambdaExpr(E, Slot);
790 }
791 
792 void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
793   CGF.enterFullExpression(E);
794   CodeGenFunction::RunCleanupsScope cleanups(CGF);
795   Visit(E->getSubExpr());
796 }
797 
798 void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
799   QualType T = E->getType();
800   AggValueSlot Slot = EnsureSlot(T);
801   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
802 }
803 
804 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
805   QualType T = E->getType();
806   AggValueSlot Slot = EnsureSlot(T);
807   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
808 }
809 
810 /// isSimpleZero - If emitting this value will obviously just cause a store of
811 /// zero to memory, return true.  This can return false if uncertain, so it just
812 /// handles simple cases.
813 static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
814   E = E->IgnoreParens();
815 
816   // 0
817   if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
818     return IL->getValue() == 0;
819   // +0.0
820   if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
821     return FL->getValue().isPosZero();
822   // int()
823   if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
824       CGF.getTypes().isZeroInitializable(E->getType()))
825     return true;
826   // (int*)0 - Null pointer expressions.
827   if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
828     return ICE->getCastKind() == CK_NullToPointer;
829   // '\0'
830   if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
831     return CL->getValue() == 0;
832 
833   // Otherwise, hard case: conservatively return false.
834   return false;
835 }
836 
837 
838 void
839 AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) {
840   QualType type = LV.getType();
841   // FIXME: Ignore result?
842   // FIXME: Are initializers affected by volatile?
843   if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
844     // Storing "i32 0" to a zero'd memory location is a noop.
845   } else if (isa<ImplicitValueInitExpr>(E)) {
846     EmitNullInitializationToLValue(LV);
847   } else if (type->isReferenceType()) {
848     RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
849     CGF.EmitStoreThroughLValue(RV, LV);
850   } else if (type->isAnyComplexType()) {
851     CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
852   } else if (CGF.hasAggregateLLVMType(type)) {
853     CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV,
854                                                AggValueSlot::IsDestructed,
855                                       AggValueSlot::DoesNotNeedGCBarriers,
856                                                AggValueSlot::IsNotAliased,
857                                                Dest.isZeroed()));
858   } else if (LV.isSimple()) {
859     CGF.EmitScalarInit(E, /*D=*/0, LV, /*Captured=*/false);
860   } else {
861     CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
862   }
863 }
864 
865 void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
866   QualType type = lv.getType();
867 
868   // If the destination slot is already zeroed out before the aggregate is
869   // copied into it, we don't have to emit any zeros here.
870   if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
871     return;
872 
873   if (!CGF.hasAggregateLLVMType(type)) {
874     // For non-aggregates, we can store zero.
875     llvm::Value *null = llvm::Constant::getNullValue(CGF.ConvertType(type));
876     // Note that the following is not equivalent to
877     // EmitStoreThroughBitfieldLValue for ARC types.
878     if (lv.isBitField()) {
879       CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
880     } else {
881       assert(lv.isSimple());
882       CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
883     }
884   } else {
885     // There's a potential optimization opportunity in combining
886     // memsets; that would be easy for arrays, but relatively
887     // difficult for structures with the current code.
888     CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
889   }
890 }
891 
892 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
893 #if 0
894   // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
895   // (Length of globals? Chunks of zeroed-out space?).
896   //
897   // If we can, prefer a copy from a global; this is a lot less code for long
898   // globals, and it's easier for the current optimizers to analyze.
899   if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
900     llvm::GlobalVariable* GV =
901     new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
902                              llvm::GlobalValue::InternalLinkage, C, "");
903     EmitFinalDestCopy(E, CGF.MakeAddrLValue(GV, E->getType()));
904     return;
905   }
906 #endif
907   if (E->hadArrayRangeDesignator())
908     CGF.ErrorUnsupported(E, "GNU array range designator extension");
909 
910   if (E->initializesStdInitializerList()) {
911     EmitStdInitializerList(Dest.getAddr(), E);
912     return;
913   }
914 
915   llvm::Value *DestPtr = EnsureSlot(E->getType()).getAddr();
916 
917   // Handle initialization of an array.
918   if (E->getType()->isArrayType()) {
919     if (E->isStringLiteralInit())
920       return Visit(E->getInit(0));
921 
922     QualType elementType =
923         CGF.getContext().getAsArrayType(E->getType())->getElementType();
924 
925     llvm::PointerType *APType =
926       cast<llvm::PointerType>(DestPtr->getType());
927     llvm::ArrayType *AType =
928       cast<llvm::ArrayType>(APType->getElementType());
929 
930     EmitArrayInit(DestPtr, AType, elementType, E);
931     return;
932   }
933 
934   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
935 
936   // Do struct initialization; this code just sets each individual member
937   // to the approprate value.  This makes bitfield support automatic;
938   // the disadvantage is that the generated code is more difficult for
939   // the optimizer, especially with bitfields.
940   unsigned NumInitElements = E->getNumInits();
941   RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
942 
943   if (record->isUnion()) {
944     // Only initialize one field of a union. The field itself is
945     // specified by the initializer list.
946     if (!E->getInitializedFieldInUnion()) {
947       // Empty union; we have nothing to do.
948 
949 #ifndef NDEBUG
950       // Make sure that it's really an empty and not a failure of
951       // semantic analysis.
952       for (RecordDecl::field_iterator Field = record->field_begin(),
953                                    FieldEnd = record->field_end();
954            Field != FieldEnd; ++Field)
955         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
956 #endif
957       return;
958     }
959 
960     // FIXME: volatility
961     FieldDecl *Field = E->getInitializedFieldInUnion();
962 
963     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0);
964     if (NumInitElements) {
965       // Store the initializer into the field
966       EmitInitializationToLValue(E->getInit(0), FieldLoc);
967     } else {
968       // Default-initialize to null.
969       EmitNullInitializationToLValue(FieldLoc);
970     }
971 
972     return;
973   }
974 
975   // We'll need to enter cleanup scopes in case any of the member
976   // initializers throw an exception.
977   SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
978   llvm::Instruction *cleanupDominator = 0;
979 
980   // Here we iterate over the fields; this makes it simpler to both
981   // default-initialize fields and skip over unnamed fields.
982   unsigned curInitIndex = 0;
983   for (RecordDecl::field_iterator field = record->field_begin(),
984                                fieldEnd = record->field_end();
985        field != fieldEnd; ++field) {
986     // We're done once we hit the flexible array member.
987     if (field->getType()->isIncompleteArrayType())
988       break;
989 
990     // Always skip anonymous bitfields.
991     if (field->isUnnamedBitfield())
992       continue;
993 
994     // We're done if we reach the end of the explicit initializers, we
995     // have a zeroed object, and the rest of the fields are
996     // zero-initializable.
997     if (curInitIndex == NumInitElements && Dest.isZeroed() &&
998         CGF.getTypes().isZeroInitializable(E->getType()))
999       break;
1000 
1001     // FIXME: volatility
1002     LValue LV = CGF.EmitLValueForFieldInitialization(DestPtr, *field, 0);
1003     // We never generate write-barries for initialized fields.
1004     LV.setNonGC(true);
1005 
1006     if (curInitIndex < NumInitElements) {
1007       // Store the initializer into the field.
1008       EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
1009     } else {
1010       // We're out of initalizers; default-initialize to null
1011       EmitNullInitializationToLValue(LV);
1012     }
1013 
1014     // Push a destructor if necessary.
1015     // FIXME: if we have an array of structures, all explicitly
1016     // initialized, we can end up pushing a linear number of cleanups.
1017     bool pushedCleanup = false;
1018     if (QualType::DestructionKind dtorKind
1019           = field->getType().isDestructedType()) {
1020       assert(LV.isSimple());
1021       if (CGF.needsEHCleanup(dtorKind)) {
1022         if (!cleanupDominator)
1023           cleanupDominator = CGF.Builder.CreateUnreachable(); // placeholder
1024 
1025         CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
1026                         CGF.getDestroyer(dtorKind), false);
1027         cleanups.push_back(CGF.EHStack.stable_begin());
1028         pushedCleanup = true;
1029       }
1030     }
1031 
1032     // If the GEP didn't get used because of a dead zero init or something
1033     // else, clean it up for -O0 builds and general tidiness.
1034     if (!pushedCleanup && LV.isSimple())
1035       if (llvm::GetElementPtrInst *GEP =
1036             dyn_cast<llvm::GetElementPtrInst>(LV.getAddress()))
1037         if (GEP->use_empty())
1038           GEP->eraseFromParent();
1039   }
1040 
1041   // Deactivate all the partial cleanups in reverse order, which
1042   // generally means popping them.
1043   for (unsigned i = cleanups.size(); i != 0; --i)
1044     CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
1045 
1046   // Destroy the placeholder if we made one.
1047   if (cleanupDominator)
1048     cleanupDominator->eraseFromParent();
1049 }
1050 
1051 //===----------------------------------------------------------------------===//
1052 //                        Entry Points into this File
1053 //===----------------------------------------------------------------------===//
1054 
1055 /// GetNumNonZeroBytesInInit - Get an approximate count of the number of
1056 /// non-zero bytes that will be stored when outputting the initializer for the
1057 /// specified initializer expression.
1058 static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
1059   E = E->IgnoreParens();
1060 
1061   // 0 and 0.0 won't require any non-zero stores!
1062   if (isSimpleZero(E, CGF)) return CharUnits::Zero();
1063 
1064   // If this is an initlist expr, sum up the size of sizes of the (present)
1065   // elements.  If this is something weird, assume the whole thing is non-zero.
1066   const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
1067   if (ILE == 0 || !CGF.getTypes().isZeroInitializable(ILE->getType()))
1068     return CGF.getContext().getTypeSizeInChars(E->getType());
1069 
1070   // InitListExprs for structs have to be handled carefully.  If there are
1071   // reference members, we need to consider the size of the reference, not the
1072   // referencee.  InitListExprs for unions and arrays can't have references.
1073   if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
1074     if (!RT->isUnionType()) {
1075       RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
1076       CharUnits NumNonZeroBytes = CharUnits::Zero();
1077 
1078       unsigned ILEElement = 0;
1079       for (RecordDecl::field_iterator Field = SD->field_begin(),
1080            FieldEnd = SD->field_end(); Field != FieldEnd; ++Field) {
1081         // We're done once we hit the flexible array member or run out of
1082         // InitListExpr elements.
1083         if (Field->getType()->isIncompleteArrayType() ||
1084             ILEElement == ILE->getNumInits())
1085           break;
1086         if (Field->isUnnamedBitfield())
1087           continue;
1088 
1089         const Expr *E = ILE->getInit(ILEElement++);
1090 
1091         // Reference values are always non-null and have the width of a pointer.
1092         if (Field->getType()->isReferenceType())
1093           NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
1094               CGF.getContext().getTargetInfo().getPointerWidth(0));
1095         else
1096           NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
1097       }
1098 
1099       return NumNonZeroBytes;
1100     }
1101   }
1102 
1103 
1104   CharUnits NumNonZeroBytes = CharUnits::Zero();
1105   for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1106     NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
1107   return NumNonZeroBytes;
1108 }
1109 
1110 /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
1111 /// zeros in it, emit a memset and avoid storing the individual zeros.
1112 ///
1113 static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
1114                                      CodeGenFunction &CGF) {
1115   // If the slot is already known to be zeroed, nothing to do.  Don't mess with
1116   // volatile stores.
1117   if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == 0) return;
1118 
1119   // C++ objects with a user-declared constructor don't need zero'ing.
1120   if (CGF.getContext().getLangOpts().CPlusPlus)
1121     if (const RecordType *RT = CGF.getContext()
1122                        .getBaseElementType(E->getType())->getAs<RecordType>()) {
1123       const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1124       if (RD->hasUserDeclaredConstructor())
1125         return;
1126     }
1127 
1128   // If the type is 16-bytes or smaller, prefer individual stores over memset.
1129   std::pair<CharUnits, CharUnits> TypeInfo =
1130     CGF.getContext().getTypeInfoInChars(E->getType());
1131   if (TypeInfo.first <= CharUnits::fromQuantity(16))
1132     return;
1133 
1134   // Check to see if over 3/4 of the initializer are known to be zero.  If so,
1135   // we prefer to emit memset + individual stores for the rest.
1136   CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
1137   if (NumNonZeroBytes*4 > TypeInfo.first)
1138     return;
1139 
1140   // Okay, it seems like a good idea to use an initial memset, emit the call.
1141   llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first.getQuantity());
1142   CharUnits Align = TypeInfo.second;
1143 
1144   llvm::Value *Loc = Slot.getAddr();
1145 
1146   Loc = CGF.Builder.CreateBitCast(Loc, CGF.Int8PtrTy);
1147   CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal,
1148                            Align.getQuantity(), false);
1149 
1150   // Tell the AggExprEmitter that the slot is known zero.
1151   Slot.setZeroed();
1152 }
1153 
1154 
1155 
1156 
1157 /// EmitAggExpr - Emit the computation of the specified expression of aggregate
1158 /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
1159 /// the value of the aggregate expression is not needed.  If VolatileDest is
1160 /// true, DestPtr cannot be 0.
1161 ///
1162 /// \param IsInitializer - true if this evaluation is initializing an
1163 /// object whose lifetime is already being managed.
1164 void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot,
1165                                   bool IgnoreResult) {
1166   assert(E && hasAggregateLLVMType(E->getType()) &&
1167          "Invalid aggregate expression to emit");
1168   assert((Slot.getAddr() != 0 || Slot.isIgnored()) &&
1169          "slot has bits but no address");
1170 
1171   // Optimize the slot if possible.
1172   CheckAggExprForMemSetUse(Slot, E, *this);
1173 
1174   AggExprEmitter(*this, Slot, IgnoreResult).Visit(const_cast<Expr*>(E));
1175 }
1176 
1177 LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
1178   assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!");
1179   llvm::Value *Temp = CreateMemTemp(E->getType());
1180   LValue LV = MakeAddrLValue(Temp, E->getType());
1181   EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,
1182                                          AggValueSlot::DoesNotNeedGCBarriers,
1183                                          AggValueSlot::IsNotAliased));
1184   return LV;
1185 }
1186 
1187 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
1188                                         llvm::Value *SrcPtr, QualType Ty,
1189                                         bool isVolatile, unsigned Alignment) {
1190   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
1191 
1192   if (getContext().getLangOpts().CPlusPlus) {
1193     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1194       CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
1195       assert((Record->hasTrivialCopyConstructor() ||
1196               Record->hasTrivialCopyAssignment() ||
1197               Record->hasTrivialMoveConstructor() ||
1198               Record->hasTrivialMoveAssignment()) &&
1199              "Trying to aggregate-copy a type without a trivial copy "
1200              "constructor or assignment operator");
1201       // Ignore empty classes in C++.
1202       if (Record->isEmpty())
1203         return;
1204     }
1205   }
1206 
1207   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
1208   // C99 6.5.16.1p3, which states "If the value being stored in an object is
1209   // read from another object that overlaps in anyway the storage of the first
1210   // object, then the overlap shall be exact and the two objects shall have
1211   // qualified or unqualified versions of a compatible type."
1212   //
1213   // memcpy is not defined if the source and destination pointers are exactly
1214   // equal, but other compilers do this optimization, and almost every memcpy
1215   // implementation handles this case safely.  If there is a libc that does not
1216   // safely handle this, we can add a target hook.
1217 
1218   // Get size and alignment info for this aggregate.
1219   std::pair<CharUnits, CharUnits> TypeInfo =
1220     getContext().getTypeInfoInChars(Ty);
1221 
1222   if (!Alignment)
1223     Alignment = TypeInfo.second.getQuantity();
1224 
1225   // FIXME: Handle variable sized types.
1226 
1227   // FIXME: If we have a volatile struct, the optimizer can remove what might
1228   // appear to be `extra' memory ops:
1229   //
1230   // volatile struct { int i; } a, b;
1231   //
1232   // int main() {
1233   //   a = b;
1234   //   a = b;
1235   // }
1236   //
1237   // we need to use a different call here.  We use isVolatile to indicate when
1238   // either the source or the destination is volatile.
1239 
1240   llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
1241   llvm::Type *DBP =
1242     llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace());
1243   DestPtr = Builder.CreateBitCast(DestPtr, DBP);
1244 
1245   llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
1246   llvm::Type *SBP =
1247     llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace());
1248   SrcPtr = Builder.CreateBitCast(SrcPtr, SBP);
1249 
1250   // Don't do any of the memmove_collectable tests if GC isn't set.
1251   if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
1252     // fall through
1253   } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1254     RecordDecl *Record = RecordTy->getDecl();
1255     if (Record->hasObjectMember()) {
1256       CharUnits size = TypeInfo.first;
1257       llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1258       llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
1259       CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1260                                                     SizeVal);
1261       return;
1262     }
1263   } else if (Ty->isArrayType()) {
1264     QualType BaseType = getContext().getBaseElementType(Ty);
1265     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
1266       if (RecordTy->getDecl()->hasObjectMember()) {
1267         CharUnits size = TypeInfo.first;
1268         llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1269         llvm::Value *SizeVal =
1270           llvm::ConstantInt::get(SizeTy, size.getQuantity());
1271         CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1272                                                       SizeVal);
1273         return;
1274       }
1275     }
1276   }
1277 
1278   Builder.CreateMemCpy(DestPtr, SrcPtr,
1279                        llvm::ConstantInt::get(IntPtrTy,
1280                                               TypeInfo.first.getQuantity()),
1281                        Alignment, isVolatile);
1282 }
1283 
1284 void CodeGenFunction::MaybeEmitStdInitializerListCleanup(llvm::Value *loc,
1285                                                          const Expr *init) {
1286   const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(init);
1287   if (cleanups)
1288     init = cleanups->getSubExpr();
1289 
1290   if (isa<InitListExpr>(init) &&
1291       cast<InitListExpr>(init)->initializesStdInitializerList()) {
1292     // We initialized this std::initializer_list with an initializer list.
1293     // A backing array was created. Push a cleanup for it.
1294     EmitStdInitializerListCleanup(loc, cast<InitListExpr>(init));
1295   }
1296 }
1297 
1298 static void EmitRecursiveStdInitializerListCleanup(CodeGenFunction &CGF,
1299                                                    llvm::Value *arrayStart,
1300                                                    const InitListExpr *init) {
1301   // Check if there are any recursive cleanups to do, i.e. if we have
1302   //   std::initializer_list<std::initializer_list<obj>> list = {{obj()}};
1303   // then we need to destroy the inner array as well.
1304   for (unsigned i = 0, e = init->getNumInits(); i != e; ++i) {
1305     const InitListExpr *subInit = dyn_cast<InitListExpr>(init->getInit(i));
1306     if (!subInit || !subInit->initializesStdInitializerList())
1307       continue;
1308 
1309     // This one needs to be destroyed. Get the address of the std::init_list.
1310     llvm::Value *offset = llvm::ConstantInt::get(CGF.SizeTy, i);
1311     llvm::Value *loc = CGF.Builder.CreateInBoundsGEP(arrayStart, offset,
1312                                                  "std.initlist");
1313     CGF.EmitStdInitializerListCleanup(loc, subInit);
1314   }
1315 }
1316 
1317 void CodeGenFunction::EmitStdInitializerListCleanup(llvm::Value *loc,
1318                                                     const InitListExpr *init) {
1319   ASTContext &ctx = getContext();
1320   QualType element = GetStdInitializerListElementType(init->getType());
1321   unsigned numInits = init->getNumInits();
1322   llvm::APInt size(ctx.getTypeSize(ctx.getSizeType()), numInits);
1323   QualType array =ctx.getConstantArrayType(element, size, ArrayType::Normal, 0);
1324   QualType arrayPtr = ctx.getPointerType(array);
1325   llvm::Type *arrayPtrType = ConvertType(arrayPtr);
1326 
1327   // lvalue is the location of a std::initializer_list, which as its first
1328   // element has a pointer to the array we want to destroy.
1329   llvm::Value *startPointer = Builder.CreateStructGEP(loc, 0, "startPointer");
1330   llvm::Value *startAddress = Builder.CreateLoad(startPointer, "startAddress");
1331 
1332   ::EmitRecursiveStdInitializerListCleanup(*this, startAddress, init);
1333 
1334   llvm::Value *arrayAddress =
1335       Builder.CreateBitCast(startAddress, arrayPtrType, "arrayAddress");
1336   ::EmitStdInitializerListCleanup(*this, array, arrayAddress, init);
1337 }
1338