]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CGExprAgg.cpp
Merge ^/head r285153 through r285283.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / CodeGen / CGExprAgg.cpp
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 "CGObjCRuntime.h"
16 #include "CodeGenModule.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/IR/Constants.h"
22 #include "llvm/IR/Function.h"
23 #include "llvm/IR/GlobalVariable.h"
24 #include "llvm/IR/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 IsResultUnused;
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(), IsResultUnused);
53   }
54
55   AggValueSlot EnsureSlot(QualType T) {
56     if (!Dest.isIgnored()) return Dest;
57     return CGF.CreateAggTemp(T, "agg.tmp.ensured");
58   }
59   void EnsureDest(QualType T) {
60     if (!Dest.isIgnored()) return;
61     Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured");
62   }
63
64 public:
65   AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest, bool IsResultUnused)
66     : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
67     IsResultUnused(IsResultUnused) { }
68
69   //===--------------------------------------------------------------------===//
70   //                               Utilities
71   //===--------------------------------------------------------------------===//
72
73   /// EmitAggLoadOfLValue - Given an expression with aggregate type that
74   /// represents a value lvalue, this method emits the address of the lvalue,
75   /// then loads the result into DestPtr.
76   void EmitAggLoadOfLValue(const Expr *E);
77
78   /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
79   void EmitFinalDestCopy(QualType type, const LValue &src);
80   void EmitFinalDestCopy(QualType type, RValue src,
81                          CharUnits srcAlignment = CharUnits::Zero());
82   void EmitCopy(QualType type, const AggValueSlot &dest,
83                 const AggValueSlot &src);
84
85   void EmitMoveFromReturnSlot(const Expr *E, RValue Src);
86
87   void EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
88                      QualType elementType, InitListExpr *E);
89
90   AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
91     if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))
92       return AggValueSlot::NeedsGCBarriers;
93     return AggValueSlot::DoesNotNeedGCBarriers;
94   }
95
96   bool TypeRequiresGCollection(QualType T);
97
98   //===--------------------------------------------------------------------===//
99   //                            Visitor Methods
100   //===--------------------------------------------------------------------===//
101
102   void Visit(Expr *E) {
103     ApplyDebugLocation DL(CGF, E);
104     StmtVisitor<AggExprEmitter>::Visit(E);
105   }
106
107   void VisitStmt(Stmt *S) {
108     CGF.ErrorUnsupported(S, "aggregate expression");
109   }
110   void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
111   void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
112     Visit(GE->getResultExpr());
113   }
114   void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
115   void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
116     return Visit(E->getReplacement());
117   }
118
119   // l-values.
120   void VisitDeclRefExpr(DeclRefExpr *E) {
121     // For aggregates, we should always be able to emit the variable
122     // as an l-value unless it's a reference.  This is due to the fact
123     // that we can't actually ever see a normal l2r conversion on an
124     // aggregate in C++, and in C there's no language standard
125     // actively preventing us from listing variables in the captures
126     // list of a block.
127     if (E->getDecl()->getType()->isReferenceType()) {
128       if (CodeGenFunction::ConstantEmission result
129             = CGF.tryEmitAsConstant(E)) {
130         EmitFinalDestCopy(E->getType(), result.getReferenceLValue(CGF, E));
131         return;
132       }
133     }
134
135     EmitAggLoadOfLValue(E);
136   }
137
138   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
139   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
140   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
141   void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
142   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
143     EmitAggLoadOfLValue(E);
144   }
145   void VisitPredefinedExpr(const PredefinedExpr *E) {
146     EmitAggLoadOfLValue(E);
147   }
148
149   // Operators.
150   void VisitCastExpr(CastExpr *E);
151   void VisitCallExpr(const CallExpr *E);
152   void VisitStmtExpr(const StmtExpr *E);
153   void VisitBinaryOperator(const BinaryOperator *BO);
154   void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
155   void VisitBinAssign(const BinaryOperator *E);
156   void VisitBinComma(const BinaryOperator *E);
157
158   void VisitObjCMessageExpr(ObjCMessageExpr *E);
159   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
160     EmitAggLoadOfLValue(E);
161   }
162
163   void VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E);
164   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
165   void VisitChooseExpr(const ChooseExpr *CE);
166   void VisitInitListExpr(InitListExpr *E);
167   void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
168   void VisitNoInitExpr(NoInitExpr *E) { } // Do nothing.
169   void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
170     Visit(DAE->getExpr());
171   }
172   void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
173     CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
174     Visit(DIE->getExpr());
175   }
176   void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
177   void VisitCXXConstructExpr(const CXXConstructExpr *E);
178   void VisitLambdaExpr(LambdaExpr *E);
179   void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
180   void VisitExprWithCleanups(ExprWithCleanups *E);
181   void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
182   void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
183   void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
184   void VisitOpaqueValueExpr(OpaqueValueExpr *E);
185
186   void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
187     if (E->isGLValue()) {
188       LValue LV = CGF.EmitPseudoObjectLValue(E);
189       return EmitFinalDestCopy(E->getType(), LV);
190     }
191
192     CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
193   }
194
195   void VisitVAArgExpr(VAArgExpr *E);
196
197   void EmitInitializationToLValue(Expr *E, LValue Address);
198   void EmitNullInitializationToLValue(LValue Address);
199   //  case Expr::ChooseExprClass:
200   void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
201   void VisitAtomicExpr(AtomicExpr *E) {
202     CGF.EmitAtomicExpr(E, EnsureSlot(E->getType()).getAddr());
203   }
204 };
205 }  // end anonymous namespace.
206
207 //===----------------------------------------------------------------------===//
208 //                                Utilities
209 //===----------------------------------------------------------------------===//
210
211 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
212 /// represents a value lvalue, this method emits the address of the lvalue,
213 /// then loads the result into DestPtr.
214 void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
215   LValue LV = CGF.EmitLValue(E);
216
217   // If the type of the l-value is atomic, then do an atomic load.
218   if (LV.getType()->isAtomicType() || CGF.LValueIsSuitableForInlineAtomic(LV)) {
219     CGF.EmitAtomicLoad(LV, E->getExprLoc(), Dest);
220     return;
221   }
222
223   EmitFinalDestCopy(E->getType(), LV);
224 }
225
226 /// \brief True if the given aggregate type requires special GC API calls.
227 bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
228   // Only record types have members that might require garbage collection.
229   const RecordType *RecordTy = T->getAs<RecordType>();
230   if (!RecordTy) return false;
231
232   // Don't mess with non-trivial C++ types.
233   RecordDecl *Record = RecordTy->getDecl();
234   if (isa<CXXRecordDecl>(Record) &&
235       (cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() ||
236        !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
237     return false;
238
239   // Check whether the type has an object member.
240   return Record->hasObjectMember();
241 }
242
243 /// \brief Perform the final move to DestPtr if for some reason
244 /// getReturnValueSlot() didn't use it directly.
245 ///
246 /// The idea is that you do something like this:
247 ///   RValue Result = EmitSomething(..., getReturnValueSlot());
248 ///   EmitMoveFromReturnSlot(E, Result);
249 ///
250 /// If nothing interferes, this will cause the result to be emitted
251 /// directly into the return value slot.  Otherwise, a final move
252 /// will be performed.
253 void AggExprEmitter::EmitMoveFromReturnSlot(const Expr *E, RValue src) {
254   if (shouldUseDestForReturnSlot()) {
255     // Logically, Dest.getAddr() should equal Src.getAggregateAddr().
256     // The possibility of undef rvalues complicates that a lot,
257     // though, so we can't really assert.
258     return;
259   }
260
261   // Otherwise, copy from there to the destination.
262   assert(Dest.getAddr() != src.getAggregateAddr());
263   std::pair<CharUnits, CharUnits> typeInfo = 
264     CGF.getContext().getTypeInfoInChars(E->getType());
265   EmitFinalDestCopy(E->getType(), src, typeInfo.second);
266 }
267
268 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
269 void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src,
270                                        CharUnits srcAlign) {
271   assert(src.isAggregate() && "value must be aggregate value!");
272   LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddr(), type, srcAlign);
273   EmitFinalDestCopy(type, srcLV);
274 }
275
276 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
277 void AggExprEmitter::EmitFinalDestCopy(QualType type, const LValue &src) {
278   // If Dest is ignored, then we're evaluating an aggregate expression
279   // in a context that doesn't care about the result.  Note that loads
280   // from volatile l-values force the existence of a non-ignored
281   // destination.
282   if (Dest.isIgnored())
283     return;
284
285   AggValueSlot srcAgg =
286     AggValueSlot::forLValue(src, AggValueSlot::IsDestructed,
287                             needsGC(type), AggValueSlot::IsAliased);
288   EmitCopy(type, Dest, srcAgg);
289 }
290
291 /// Perform a copy from the source into the destination.
292 ///
293 /// \param type - the type of the aggregate being copied; qualifiers are
294 ///   ignored
295 void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,
296                               const AggValueSlot &src) {
297   if (dest.requiresGCollection()) {
298     CharUnits sz = CGF.getContext().getTypeSizeInChars(type);
299     llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());
300     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
301                                                       dest.getAddr(),
302                                                       src.getAddr(),
303                                                       size);
304     return;
305   }
306
307   // If the result of the assignment is used, copy the LHS there also.
308   // It's volatile if either side is.  Use the minimum alignment of
309   // the two sides.
310   CGF.EmitAggregateCopy(dest.getAddr(), src.getAddr(), type,
311                         dest.isVolatile() || src.isVolatile(),
312                         std::min(dest.getAlignment(), src.getAlignment()));
313 }
314
315 /// \brief Emit the initializer for a std::initializer_list initialized with a
316 /// real initializer list.
317 void
318 AggExprEmitter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
319   // Emit an array containing the elements.  The array is externally destructed
320   // if the std::initializer_list object is.
321   ASTContext &Ctx = CGF.getContext();
322   LValue Array = CGF.EmitLValue(E->getSubExpr());
323   assert(Array.isSimple() && "initializer_list array not a simple lvalue");
324   llvm::Value *ArrayPtr = Array.getAddress();
325
326   const ConstantArrayType *ArrayType =
327       Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
328   assert(ArrayType && "std::initializer_list constructed from non-array");
329
330   // FIXME: Perform the checks on the field types in SemaInit.
331   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
332   RecordDecl::field_iterator Field = Record->field_begin();
333   if (Field == Record->field_end()) {
334     CGF.ErrorUnsupported(E, "weird std::initializer_list");
335     return;
336   }
337
338   // Start pointer.
339   if (!Field->getType()->isPointerType() ||
340       !Ctx.hasSameType(Field->getType()->getPointeeType(),
341                        ArrayType->getElementType())) {
342     CGF.ErrorUnsupported(E, "weird std::initializer_list");
343     return;
344   }
345
346   AggValueSlot Dest = EnsureSlot(E->getType());
347   LValue DestLV = CGF.MakeAddrLValue(Dest.getAddr(), E->getType(),
348                                      Dest.getAlignment());
349   LValue Start = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
350   llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0);
351   llvm::Value *IdxStart[] = { Zero, Zero };
352   llvm::Value *ArrayStart =
353       Builder.CreateInBoundsGEP(ArrayPtr, IdxStart, "arraystart");
354   CGF.EmitStoreThroughLValue(RValue::get(ArrayStart), Start);
355   ++Field;
356
357   if (Field == Record->field_end()) {
358     CGF.ErrorUnsupported(E, "weird std::initializer_list");
359     return;
360   }
361
362   llvm::Value *Size = Builder.getInt(ArrayType->getSize());
363   LValue EndOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
364   if (Field->getType()->isPointerType() &&
365       Ctx.hasSameType(Field->getType()->getPointeeType(),
366                       ArrayType->getElementType())) {
367     // End pointer.
368     llvm::Value *IdxEnd[] = { Zero, Size };
369     llvm::Value *ArrayEnd =
370         Builder.CreateInBoundsGEP(ArrayPtr, IdxEnd, "arrayend");
371     CGF.EmitStoreThroughLValue(RValue::get(ArrayEnd), EndOrLength);
372   } else if (Ctx.hasSameType(Field->getType(), Ctx.getSizeType())) {
373     // Length.
374     CGF.EmitStoreThroughLValue(RValue::get(Size), EndOrLength);
375   } else {
376     CGF.ErrorUnsupported(E, "weird std::initializer_list");
377     return;
378   }
379 }
380
381 /// \brief Determine if E is a trivial array filler, that is, one that is
382 /// equivalent to zero-initialization.
383 static bool isTrivialFiller(Expr *E) {
384   if (!E)
385     return true;
386
387   if (isa<ImplicitValueInitExpr>(E))
388     return true;
389
390   if (auto *ILE = dyn_cast<InitListExpr>(E)) {
391     if (ILE->getNumInits())
392       return false;
393     return isTrivialFiller(ILE->getArrayFiller());
394   }
395
396   if (auto *Cons = dyn_cast_or_null<CXXConstructExpr>(E))
397     return Cons->getConstructor()->isDefaultConstructor() &&
398            Cons->getConstructor()->isTrivial();
399
400   // FIXME: Are there other cases where we can avoid emitting an initializer?
401   return false;
402 }
403
404 /// \brief Emit initialization of an array from an initializer list.
405 void AggExprEmitter::EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
406                                    QualType elementType, InitListExpr *E) {
407   uint64_t NumInitElements = E->getNumInits();
408
409   uint64_t NumArrayElements = AType->getNumElements();
410   assert(NumInitElements <= NumArrayElements);
411
412   // DestPtr is an array*.  Construct an elementType* by drilling
413   // down a level.
414   llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
415   llvm::Value *indices[] = { zero, zero };
416   llvm::Value *begin =
417     Builder.CreateInBoundsGEP(DestPtr, indices, "arrayinit.begin");
418
419   // Exception safety requires us to destroy all the
420   // already-constructed members if an initializer throws.
421   // For that, we'll need an EH cleanup.
422   QualType::DestructionKind dtorKind = elementType.isDestructedType();
423   llvm::AllocaInst *endOfInit = nullptr;
424   EHScopeStack::stable_iterator cleanup;
425   llvm::Instruction *cleanupDominator = nullptr;
426   if (CGF.needsEHCleanup(dtorKind)) {
427     // In principle we could tell the cleanup where we are more
428     // directly, but the control flow can get so varied here that it
429     // would actually be quite complex.  Therefore we go through an
430     // alloca.
431     endOfInit = CGF.CreateTempAlloca(begin->getType(),
432                                      "arrayinit.endOfInit");
433     cleanupDominator = Builder.CreateStore(begin, endOfInit);
434     CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
435                                          CGF.getDestroyer(dtorKind));
436     cleanup = CGF.EHStack.stable_begin();
437
438   // Otherwise, remember that we didn't need a cleanup.
439   } else {
440     dtorKind = QualType::DK_none;
441   }
442
443   llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
444
445   // The 'current element to initialize'.  The invariants on this
446   // variable are complicated.  Essentially, after each iteration of
447   // the loop, it points to the last initialized element, except
448   // that it points to the beginning of the array before any
449   // elements have been initialized.
450   llvm::Value *element = begin;
451
452   // Emit the explicit initializers.
453   for (uint64_t i = 0; i != NumInitElements; ++i) {
454     // Advance to the next element.
455     if (i > 0) {
456       element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element");
457
458       // Tell the cleanup that it needs to destroy up to this
459       // element.  TODO: some of these stores can be trivially
460       // observed to be unnecessary.
461       if (endOfInit) Builder.CreateStore(element, endOfInit);
462     }
463
464     LValue elementLV = CGF.MakeAddrLValue(element, elementType);
465     EmitInitializationToLValue(E->getInit(i), elementLV);
466   }
467
468   // Check whether there's a non-trivial array-fill expression.
469   Expr *filler = E->getArrayFiller();
470   bool hasTrivialFiller = isTrivialFiller(filler);
471
472   // Any remaining elements need to be zero-initialized, possibly
473   // using the filler expression.  We can skip this if the we're
474   // emitting to zeroed memory.
475   if (NumInitElements != NumArrayElements &&
476       !(Dest.isZeroed() && hasTrivialFiller &&
477         CGF.getTypes().isZeroInitializable(elementType))) {
478
479     // Use an actual loop.  This is basically
480     //   do { *array++ = filler; } while (array != end);
481
482     // Advance to the start of the rest of the array.
483     if (NumInitElements) {
484       element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start");
485       if (endOfInit) Builder.CreateStore(element, endOfInit);
486     }
487
488     // Compute the end of the array.
489     llvm::Value *end = Builder.CreateInBoundsGEP(begin,
490                       llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
491                                                  "arrayinit.end");
492
493     llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
494     llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
495
496     // Jump into the body.
497     CGF.EmitBlock(bodyBB);
498     llvm::PHINode *currentElement =
499       Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
500     currentElement->addIncoming(element, entryBB);
501
502     // Emit the actual filler expression.
503     LValue elementLV = CGF.MakeAddrLValue(currentElement, elementType);
504     if (filler)
505       EmitInitializationToLValue(filler, elementLV);
506     else
507       EmitNullInitializationToLValue(elementLV);
508
509     // Move on to the next element.
510     llvm::Value *nextElement =
511       Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
512
513     // Tell the EH cleanup that we finished with the last element.
514     if (endOfInit) Builder.CreateStore(nextElement, endOfInit);
515
516     // Leave the loop if we're done.
517     llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
518                                              "arrayinit.done");
519     llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
520     Builder.CreateCondBr(done, endBB, bodyBB);
521     currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
522
523     CGF.EmitBlock(endBB);
524   }
525
526   // Leave the partial-array cleanup if we entered one.
527   if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator);
528 }
529
530 //===----------------------------------------------------------------------===//
531 //                            Visitor Methods
532 //===----------------------------------------------------------------------===//
533
534 void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
535   Visit(E->GetTemporaryExpr());
536 }
537
538 void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
539   EmitFinalDestCopy(e->getType(), CGF.getOpaqueLValueMapping(e));
540 }
541
542 void
543 AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
544   if (Dest.isPotentiallyAliased() &&
545       E->getType().isPODType(CGF.getContext())) {
546     // For a POD type, just emit a load of the lvalue + a copy, because our
547     // compound literal might alias the destination.
548     EmitAggLoadOfLValue(E);
549     return;
550   }
551   
552   AggValueSlot Slot = EnsureSlot(E->getType());
553   CGF.EmitAggExpr(E->getInitializer(), Slot);
554 }
555
556 /// Attempt to look through various unimportant expressions to find a
557 /// cast of the given kind.
558 static Expr *findPeephole(Expr *op, CastKind kind) {
559   while (true) {
560     op = op->IgnoreParens();
561     if (CastExpr *castE = dyn_cast<CastExpr>(op)) {
562       if (castE->getCastKind() == kind)
563         return castE->getSubExpr();
564       if (castE->getCastKind() == CK_NoOp)
565         continue;
566     }
567     return nullptr;
568   }
569 }
570
571 void AggExprEmitter::VisitCastExpr(CastExpr *E) {
572   switch (E->getCastKind()) {
573   case CK_Dynamic: {
574     // FIXME: Can this actually happen? We have no test coverage for it.
575     assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
576     LValue LV = CGF.EmitCheckedLValue(E->getSubExpr(),
577                                       CodeGenFunction::TCK_Load);
578     // FIXME: Do we also need to handle property references here?
579     if (LV.isSimple())
580       CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
581     else
582       CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
583     
584     if (!Dest.isIgnored())
585       CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
586     break;
587   }
588       
589   case CK_ToUnion: {
590     // Evaluate even if the destination is ignored.
591     if (Dest.isIgnored()) {
592       CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(),
593                       /*ignoreResult=*/true);
594       break;
595     }
596
597     // GCC union extension
598     QualType Ty = E->getSubExpr()->getType();
599     QualType PtrTy = CGF.getContext().getPointerType(Ty);
600     llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
601                                                  CGF.ConvertType(PtrTy));
602     EmitInitializationToLValue(E->getSubExpr(),
603                                CGF.MakeAddrLValue(CastPtr, Ty));
604     break;
605   }
606
607   case CK_DerivedToBase:
608   case CK_BaseToDerived:
609   case CK_UncheckedDerivedToBase: {
610     llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
611                 "should have been unpacked before we got here");
612   }
613
614   case CK_NonAtomicToAtomic:
615   case CK_AtomicToNonAtomic: {
616     bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);
617
618     // Determine the atomic and value types.
619     QualType atomicType = E->getSubExpr()->getType();
620     QualType valueType = E->getType();
621     if (isToAtomic) std::swap(atomicType, valueType);
622
623     assert(atomicType->isAtomicType());
624     assert(CGF.getContext().hasSameUnqualifiedType(valueType,
625                           atomicType->castAs<AtomicType>()->getValueType()));
626
627     // Just recurse normally if we're ignoring the result or the
628     // atomic type doesn't change representation.
629     if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {
630       return Visit(E->getSubExpr());
631     }
632
633     CastKind peepholeTarget =
634       (isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic);
635
636     // These two cases are reverses of each other; try to peephole them.
637     if (Expr *op = findPeephole(E->getSubExpr(), peepholeTarget)) {
638       assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),
639                                                      E->getType()) &&
640            "peephole significantly changed types?");
641       return Visit(op);
642     }
643
644     // If we're converting an r-value of non-atomic type to an r-value
645     // of atomic type, just emit directly into the relevant sub-object.
646     if (isToAtomic) {
647       AggValueSlot valueDest = Dest;
648       if (!valueDest.isIgnored() && CGF.CGM.isPaddedAtomicType(atomicType)) {
649         // Zero-initialize.  (Strictly speaking, we only need to intialize
650         // the padding at the end, but this is simpler.)
651         if (!Dest.isZeroed())
652           CGF.EmitNullInitialization(Dest.getAddr(), atomicType);
653
654         // Build a GEP to refer to the subobject.
655         llvm::Value *valueAddr =
656             CGF.Builder.CreateStructGEP(nullptr, valueDest.getAddr(), 0);
657         valueDest = AggValueSlot::forAddr(valueAddr,
658                                           valueDest.getAlignment(),
659                                           valueDest.getQualifiers(),
660                                           valueDest.isExternallyDestructed(),
661                                           valueDest.requiresGCollection(),
662                                           valueDest.isPotentiallyAliased(),
663                                           AggValueSlot::IsZeroed);
664       }
665       
666       CGF.EmitAggExpr(E->getSubExpr(), valueDest);
667       return;
668     }
669
670     // Otherwise, we're converting an atomic type to a non-atomic type.
671     // Make an atomic temporary, emit into that, and then copy the value out.
672     AggValueSlot atomicSlot =
673       CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");
674     CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
675
676     llvm::Value *valueAddr =
677         Builder.CreateStructGEP(nullptr, atomicSlot.getAddr(), 0);
678     RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());
679     return EmitFinalDestCopy(valueType, rvalue);
680   }
681
682   case CK_LValueToRValue:
683     // If we're loading from a volatile type, force the destination
684     // into existence.
685     if (E->getSubExpr()->getType().isVolatileQualified()) {
686       EnsureDest(E->getType());
687       return Visit(E->getSubExpr());
688     }
689
690     // fallthrough
691
692   case CK_NoOp:
693   case CK_UserDefinedConversion:
694   case CK_ConstructorConversion:
695     assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
696                                                    E->getType()) &&
697            "Implicit cast types must be compatible");
698     Visit(E->getSubExpr());
699     break;
700       
701   case CK_LValueBitCast:
702     llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
703
704   case CK_Dependent:
705   case CK_BitCast:
706   case CK_ArrayToPointerDecay:
707   case CK_FunctionToPointerDecay:
708   case CK_NullToPointer:
709   case CK_NullToMemberPointer:
710   case CK_BaseToDerivedMemberPointer:
711   case CK_DerivedToBaseMemberPointer:
712   case CK_MemberPointerToBoolean:
713   case CK_ReinterpretMemberPointer:
714   case CK_IntegralToPointer:
715   case CK_PointerToIntegral:
716   case CK_PointerToBoolean:
717   case CK_ToVoid:
718   case CK_VectorSplat:
719   case CK_IntegralCast:
720   case CK_IntegralToBoolean:
721   case CK_IntegralToFloating:
722   case CK_FloatingToIntegral:
723   case CK_FloatingToBoolean:
724   case CK_FloatingCast:
725   case CK_CPointerToObjCPointerCast:
726   case CK_BlockPointerToObjCPointerCast:
727   case CK_AnyPointerToBlockPointerCast:
728   case CK_ObjCObjectLValueCast:
729   case CK_FloatingRealToComplex:
730   case CK_FloatingComplexToReal:
731   case CK_FloatingComplexToBoolean:
732   case CK_FloatingComplexCast:
733   case CK_FloatingComplexToIntegralComplex:
734   case CK_IntegralRealToComplex:
735   case CK_IntegralComplexToReal:
736   case CK_IntegralComplexToBoolean:
737   case CK_IntegralComplexCast:
738   case CK_IntegralComplexToFloatingComplex:
739   case CK_ARCProduceObject:
740   case CK_ARCConsumeObject:
741   case CK_ARCReclaimReturnedObject:
742   case CK_ARCExtendBlockObject:
743   case CK_CopyAndAutoreleaseBlockObject:
744   case CK_BuiltinFnToFnPtr:
745   case CK_ZeroToOCLEvent:
746   case CK_AddressSpaceConversion:
747     llvm_unreachable("cast kind invalid for aggregate types");
748   }
749 }
750
751 void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
752   if (E->getCallReturnType(CGF.getContext())->isReferenceType()) {
753     EmitAggLoadOfLValue(E);
754     return;
755   }
756
757   RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
758   EmitMoveFromReturnSlot(E, RV);
759 }
760
761 void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
762   RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
763   EmitMoveFromReturnSlot(E, RV);
764 }
765
766 void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
767   CGF.EmitIgnoredExpr(E->getLHS());
768   Visit(E->getRHS());
769 }
770
771 void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
772   CodeGenFunction::StmtExprEvaluation eval(CGF);
773   CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
774 }
775
776 void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
777   if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
778     VisitPointerToDataMemberBinaryOperator(E);
779   else
780     CGF.ErrorUnsupported(E, "aggregate binary expression");
781 }
782
783 void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
784                                                     const BinaryOperator *E) {
785   LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
786   EmitFinalDestCopy(E->getType(), LV);
787 }
788
789 /// Is the value of the given expression possibly a reference to or
790 /// into a __block variable?
791 static bool isBlockVarRef(const Expr *E) {
792   // Make sure we look through parens.
793   E = E->IgnoreParens();
794
795   // Check for a direct reference to a __block variable.
796   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
797     const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
798     return (var && var->hasAttr<BlocksAttr>());
799   }
800
801   // More complicated stuff.
802
803   // Binary operators.
804   if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {
805     // For an assignment or pointer-to-member operation, just care
806     // about the LHS.
807     if (op->isAssignmentOp() || op->isPtrMemOp())
808       return isBlockVarRef(op->getLHS());
809
810     // For a comma, just care about the RHS.
811     if (op->getOpcode() == BO_Comma)
812       return isBlockVarRef(op->getRHS());
813
814     // FIXME: pointer arithmetic?
815     return false;
816
817   // Check both sides of a conditional operator.
818   } else if (const AbstractConditionalOperator *op
819                = dyn_cast<AbstractConditionalOperator>(E)) {
820     return isBlockVarRef(op->getTrueExpr())
821         || isBlockVarRef(op->getFalseExpr());
822
823   // OVEs are required to support BinaryConditionalOperators.
824   } else if (const OpaqueValueExpr *op
825                = dyn_cast<OpaqueValueExpr>(E)) {
826     if (const Expr *src = op->getSourceExpr())
827       return isBlockVarRef(src);
828
829   // Casts are necessary to get things like (*(int*)&var) = foo().
830   // We don't really care about the kind of cast here, except
831   // we don't want to look through l2r casts, because it's okay
832   // to get the *value* in a __block variable.
833   } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {
834     if (cast->getCastKind() == CK_LValueToRValue)
835       return false;
836     return isBlockVarRef(cast->getSubExpr());
837
838   // Handle unary operators.  Again, just aggressively look through
839   // it, ignoring the operation.
840   } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {
841     return isBlockVarRef(uop->getSubExpr());
842
843   // Look into the base of a field access.
844   } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
845     return isBlockVarRef(mem->getBase());
846
847   // Look into the base of a subscript.
848   } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {
849     return isBlockVarRef(sub->getBase());
850   }
851
852   return false;
853 }
854
855 void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
856   // For an assignment to work, the value on the right has
857   // to be compatible with the value on the left.
858   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
859                                                  E->getRHS()->getType())
860          && "Invalid assignment");
861
862   // If the LHS might be a __block variable, and the RHS can
863   // potentially cause a block copy, we need to evaluate the RHS first
864   // so that the assignment goes the right place.
865   // This is pretty semantically fragile.
866   if (isBlockVarRef(E->getLHS()) &&
867       E->getRHS()->HasSideEffects(CGF.getContext())) {
868     // Ensure that we have a destination, and evaluate the RHS into that.
869     EnsureDest(E->getRHS()->getType());
870     Visit(E->getRHS());
871
872     // Now emit the LHS and copy into it.
873     LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
874
875     // That copy is an atomic copy if the LHS is atomic.
876     if (LHS.getType()->isAtomicType() ||
877         CGF.LValueIsSuitableForInlineAtomic(LHS)) {
878       CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
879       return;
880     }
881
882     EmitCopy(E->getLHS()->getType(),
883              AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
884                                      needsGC(E->getLHS()->getType()),
885                                      AggValueSlot::IsAliased),
886              Dest);
887     return;
888   }
889   
890   LValue LHS = CGF.EmitLValue(E->getLHS());
891
892   // If we have an atomic type, evaluate into the destination and then
893   // do an atomic copy.
894   if (LHS.getType()->isAtomicType() ||
895       CGF.LValueIsSuitableForInlineAtomic(LHS)) {
896     EnsureDest(E->getRHS()->getType());
897     Visit(E->getRHS());
898     CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
899     return;
900   }
901
902   // Codegen the RHS so that it stores directly into the LHS.
903   AggValueSlot LHSSlot =
904     AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed, 
905                             needsGC(E->getLHS()->getType()),
906                             AggValueSlot::IsAliased);
907   // A non-volatile aggregate destination might have volatile member.
908   if (!LHSSlot.isVolatile() &&
909       CGF.hasVolatileMember(E->getLHS()->getType()))
910     LHSSlot.setVolatile(true);
911       
912   CGF.EmitAggExpr(E->getRHS(), LHSSlot);
913
914   // Copy into the destination if the assignment isn't ignored.
915   EmitFinalDestCopy(E->getType(), LHS);
916 }
917
918 void AggExprEmitter::
919 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
920   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
921   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
922   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
923
924   // Bind the common expression if necessary.
925   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
926
927   CodeGenFunction::ConditionalEvaluation eval(CGF);
928   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
929                            CGF.getProfileCount(E));
930
931   // Save whether the destination's lifetime is externally managed.
932   bool isExternallyDestructed = Dest.isExternallyDestructed();
933
934   eval.begin(CGF);
935   CGF.EmitBlock(LHSBlock);
936   CGF.incrementProfileCounter(E);
937   Visit(E->getTrueExpr());
938   eval.end(CGF);
939
940   assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
941   CGF.Builder.CreateBr(ContBlock);
942
943   // If the result of an agg expression is unused, then the emission
944   // of the LHS might need to create a destination slot.  That's fine
945   // with us, and we can safely emit the RHS into the same slot, but
946   // we shouldn't claim that it's already being destructed.
947   Dest.setExternallyDestructed(isExternallyDestructed);
948
949   eval.begin(CGF);
950   CGF.EmitBlock(RHSBlock);
951   Visit(E->getFalseExpr());
952   eval.end(CGF);
953
954   CGF.EmitBlock(ContBlock);
955 }
956
957 void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
958   Visit(CE->getChosenSubExpr());
959 }
960
961 void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
962   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
963   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
964
965   if (!ArgPtr) {
966     // If EmitVAArg fails, we fall back to the LLVM instruction.
967     llvm::Value *Val =
968         Builder.CreateVAArg(ArgValue, CGF.ConvertType(VE->getType()));
969     if (!Dest.isIgnored())
970       Builder.CreateStore(Val, Dest.getAddr());
971     return;
972   }
973
974   EmitFinalDestCopy(VE->getType(), CGF.MakeAddrLValue(ArgPtr, VE->getType()));
975 }
976
977 void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
978   // Ensure that we have a slot, but if we already do, remember
979   // whether it was externally destructed.
980   bool wasExternallyDestructed = Dest.isExternallyDestructed();
981   EnsureDest(E->getType());
982
983   // We're going to push a destructor if there isn't already one.
984   Dest.setExternallyDestructed();
985
986   Visit(E->getSubExpr());
987
988   // Push that destructor we promised.
989   if (!wasExternallyDestructed)
990     CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddr());
991 }
992
993 void
994 AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
995   AggValueSlot Slot = EnsureSlot(E->getType());
996   CGF.EmitCXXConstructExpr(E, Slot);
997 }
998
999 void
1000 AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
1001   AggValueSlot Slot = EnsureSlot(E->getType());
1002   CGF.EmitLambdaExpr(E, Slot);
1003 }
1004
1005 void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
1006   CGF.enterFullExpression(E);
1007   CodeGenFunction::RunCleanupsScope cleanups(CGF);
1008   Visit(E->getSubExpr());
1009 }
1010
1011 void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1012   QualType T = E->getType();
1013   AggValueSlot Slot = EnsureSlot(T);
1014   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
1015 }
1016
1017 void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
1018   QualType T = E->getType();
1019   AggValueSlot Slot = EnsureSlot(T);
1020   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
1021 }
1022
1023 /// isSimpleZero - If emitting this value will obviously just cause a store of
1024 /// zero to memory, return true.  This can return false if uncertain, so it just
1025 /// handles simple cases.
1026 static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
1027   E = E->IgnoreParens();
1028
1029   // 0
1030   if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
1031     return IL->getValue() == 0;
1032   // +0.0
1033   if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
1034     return FL->getValue().isPosZero();
1035   // int()
1036   if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
1037       CGF.getTypes().isZeroInitializable(E->getType()))
1038     return true;
1039   // (int*)0 - Null pointer expressions.
1040   if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
1041     return ICE->getCastKind() == CK_NullToPointer;
1042   // '\0'
1043   if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
1044     return CL->getValue() == 0;
1045   
1046   // Otherwise, hard case: conservatively return false.
1047   return false;
1048 }
1049
1050
1051 void 
1052 AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) {
1053   QualType type = LV.getType();
1054   // FIXME: Ignore result?
1055   // FIXME: Are initializers affected by volatile?
1056   if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
1057     // Storing "i32 0" to a zero'd memory location is a noop.
1058     return;
1059   } else if (isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) {
1060     return EmitNullInitializationToLValue(LV);
1061   } else if (isa<NoInitExpr>(E)) {
1062     // Do nothing.
1063     return;
1064   } else if (type->isReferenceType()) {
1065     RValue RV = CGF.EmitReferenceBindingToExpr(E);
1066     return CGF.EmitStoreThroughLValue(RV, LV);
1067   }
1068   
1069   switch (CGF.getEvaluationKind(type)) {
1070   case TEK_Complex:
1071     CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
1072     return;
1073   case TEK_Aggregate:
1074     CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV,
1075                                                AggValueSlot::IsDestructed,
1076                                       AggValueSlot::DoesNotNeedGCBarriers,
1077                                                AggValueSlot::IsNotAliased,
1078                                                Dest.isZeroed()));
1079     return;
1080   case TEK_Scalar:
1081     if (LV.isSimple()) {
1082       CGF.EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false);
1083     } else {
1084       CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
1085     }
1086     return;
1087   }
1088   llvm_unreachable("bad evaluation kind");
1089 }
1090
1091 void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
1092   QualType type = lv.getType();
1093
1094   // If the destination slot is already zeroed out before the aggregate is
1095   // copied into it, we don't have to emit any zeros here.
1096   if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
1097     return;
1098   
1099   if (CGF.hasScalarEvaluationKind(type)) {
1100     // For non-aggregates, we can store the appropriate null constant.
1101     llvm::Value *null = CGF.CGM.EmitNullConstant(type);
1102     // Note that the following is not equivalent to
1103     // EmitStoreThroughBitfieldLValue for ARC types.
1104     if (lv.isBitField()) {
1105       CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
1106     } else {
1107       assert(lv.isSimple());
1108       CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
1109     }
1110   } else {
1111     // There's a potential optimization opportunity in combining
1112     // memsets; that would be easy for arrays, but relatively
1113     // difficult for structures with the current code.
1114     CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
1115   }
1116 }
1117
1118 void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
1119 #if 0
1120   // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
1121   // (Length of globals? Chunks of zeroed-out space?).
1122   //
1123   // If we can, prefer a copy from a global; this is a lot less code for long
1124   // globals, and it's easier for the current optimizers to analyze.
1125   if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
1126     llvm::GlobalVariable* GV =
1127     new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
1128                              llvm::GlobalValue::InternalLinkage, C, "");
1129     EmitFinalDestCopy(E->getType(), CGF.MakeAddrLValue(GV, E->getType()));
1130     return;
1131   }
1132 #endif
1133   if (E->hadArrayRangeDesignator())
1134     CGF.ErrorUnsupported(E, "GNU array range designator extension");
1135
1136   AggValueSlot Dest = EnsureSlot(E->getType());
1137
1138   LValue DestLV = CGF.MakeAddrLValue(Dest.getAddr(), E->getType(),
1139                                      Dest.getAlignment());
1140
1141   // Handle initialization of an array.
1142   if (E->getType()->isArrayType()) {
1143     if (E->isStringLiteralInit())
1144       return Visit(E->getInit(0));
1145
1146     QualType elementType =
1147         CGF.getContext().getAsArrayType(E->getType())->getElementType();
1148
1149     llvm::PointerType *APType =
1150       cast<llvm::PointerType>(Dest.getAddr()->getType());
1151     llvm::ArrayType *AType =
1152       cast<llvm::ArrayType>(APType->getElementType());
1153
1154     EmitArrayInit(Dest.getAddr(), AType, elementType, E);
1155     return;
1156   }
1157
1158   if (E->getType()->isAtomicType()) {
1159     // An _Atomic(T) object can be list-initialized from an expression
1160     // of the same type.
1161     assert(E->getNumInits() == 1 &&
1162            CGF.getContext().hasSameUnqualifiedType(E->getInit(0)->getType(),
1163                                                    E->getType()) &&
1164            "unexpected list initialization for atomic object");
1165     return Visit(E->getInit(0));
1166   }
1167
1168   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
1169
1170   // Do struct initialization; this code just sets each individual member
1171   // to the approprate value.  This makes bitfield support automatic;
1172   // the disadvantage is that the generated code is more difficult for
1173   // the optimizer, especially with bitfields.
1174   unsigned NumInitElements = E->getNumInits();
1175   RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
1176
1177   // Prepare a 'this' for CXXDefaultInitExprs.
1178   CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddr());
1179
1180   if (record->isUnion()) {
1181     // Only initialize one field of a union. The field itself is
1182     // specified by the initializer list.
1183     if (!E->getInitializedFieldInUnion()) {
1184       // Empty union; we have nothing to do.
1185
1186 #ifndef NDEBUG
1187       // Make sure that it's really an empty and not a failure of
1188       // semantic analysis.
1189       for (const auto *Field : record->fields())
1190         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
1191 #endif
1192       return;
1193     }
1194
1195     // FIXME: volatility
1196     FieldDecl *Field = E->getInitializedFieldInUnion();
1197
1198     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
1199     if (NumInitElements) {
1200       // Store the initializer into the field
1201       EmitInitializationToLValue(E->getInit(0), FieldLoc);
1202     } else {
1203       // Default-initialize to null.
1204       EmitNullInitializationToLValue(FieldLoc);
1205     }
1206
1207     return;
1208   }
1209
1210   // We'll need to enter cleanup scopes in case any of the member
1211   // initializers throw an exception.
1212   SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
1213   llvm::Instruction *cleanupDominator = nullptr;
1214
1215   // Here we iterate over the fields; this makes it simpler to both
1216   // default-initialize fields and skip over unnamed fields.
1217   unsigned curInitIndex = 0;
1218   for (const auto *field : record->fields()) {
1219     // We're done once we hit the flexible array member.
1220     if (field->getType()->isIncompleteArrayType())
1221       break;
1222
1223     // Always skip anonymous bitfields.
1224     if (field->isUnnamedBitfield())
1225       continue;
1226
1227     // We're done if we reach the end of the explicit initializers, we
1228     // have a zeroed object, and the rest of the fields are
1229     // zero-initializable.
1230     if (curInitIndex == NumInitElements && Dest.isZeroed() &&
1231         CGF.getTypes().isZeroInitializable(E->getType()))
1232       break;
1233     
1234
1235     LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field);
1236     // We never generate write-barries for initialized fields.
1237     LV.setNonGC(true);
1238     
1239     if (curInitIndex < NumInitElements) {
1240       // Store the initializer into the field.
1241       EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
1242     } else {
1243       // We're out of initalizers; default-initialize to null
1244       EmitNullInitializationToLValue(LV);
1245     }
1246
1247     // Push a destructor if necessary.
1248     // FIXME: if we have an array of structures, all explicitly
1249     // initialized, we can end up pushing a linear number of cleanups.
1250     bool pushedCleanup = false;
1251     if (QualType::DestructionKind dtorKind
1252           = field->getType().isDestructedType()) {
1253       assert(LV.isSimple());
1254       if (CGF.needsEHCleanup(dtorKind)) {
1255         if (!cleanupDominator)
1256           cleanupDominator = CGF.Builder.CreateUnreachable(); // placeholder
1257
1258         CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
1259                         CGF.getDestroyer(dtorKind), false);
1260         cleanups.push_back(CGF.EHStack.stable_begin());
1261         pushedCleanup = true;
1262       }
1263     }
1264     
1265     // If the GEP didn't get used because of a dead zero init or something
1266     // else, clean it up for -O0 builds and general tidiness.
1267     if (!pushedCleanup && LV.isSimple()) 
1268       if (llvm::GetElementPtrInst *GEP =
1269             dyn_cast<llvm::GetElementPtrInst>(LV.getAddress()))
1270         if (GEP->use_empty())
1271           GEP->eraseFromParent();
1272   }
1273
1274   // Deactivate all the partial cleanups in reverse order, which
1275   // generally means popping them.
1276   for (unsigned i = cleanups.size(); i != 0; --i)
1277     CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
1278
1279   // Destroy the placeholder if we made one.
1280   if (cleanupDominator)
1281     cleanupDominator->eraseFromParent();
1282 }
1283
1284 void AggExprEmitter::VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) {
1285   AggValueSlot Dest = EnsureSlot(E->getType());
1286
1287   LValue DestLV = CGF.MakeAddrLValue(Dest.getAddr(), E->getType(),
1288                                      Dest.getAlignment());
1289   EmitInitializationToLValue(E->getBase(), DestLV);
1290   VisitInitListExpr(E->getUpdater());
1291 }
1292
1293 //===----------------------------------------------------------------------===//
1294 //                        Entry Points into this File
1295 //===----------------------------------------------------------------------===//
1296
1297 /// GetNumNonZeroBytesInInit - Get an approximate count of the number of
1298 /// non-zero bytes that will be stored when outputting the initializer for the
1299 /// specified initializer expression.
1300 static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
1301   E = E->IgnoreParens();
1302
1303   // 0 and 0.0 won't require any non-zero stores!
1304   if (isSimpleZero(E, CGF)) return CharUnits::Zero();
1305
1306   // If this is an initlist expr, sum up the size of sizes of the (present)
1307   // elements.  If this is something weird, assume the whole thing is non-zero.
1308   const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
1309   if (!ILE || !CGF.getTypes().isZeroInitializable(ILE->getType()))
1310     return CGF.getContext().getTypeSizeInChars(E->getType());
1311   
1312   // InitListExprs for structs have to be handled carefully.  If there are
1313   // reference members, we need to consider the size of the reference, not the
1314   // referencee.  InitListExprs for unions and arrays can't have references.
1315   if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
1316     if (!RT->isUnionType()) {
1317       RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
1318       CharUnits NumNonZeroBytes = CharUnits::Zero();
1319       
1320       unsigned ILEElement = 0;
1321       for (const auto *Field : SD->fields()) {
1322         // We're done once we hit the flexible array member or run out of
1323         // InitListExpr elements.
1324         if (Field->getType()->isIncompleteArrayType() ||
1325             ILEElement == ILE->getNumInits())
1326           break;
1327         if (Field->isUnnamedBitfield())
1328           continue;
1329
1330         const Expr *E = ILE->getInit(ILEElement++);
1331         
1332         // Reference values are always non-null and have the width of a pointer.
1333         if (Field->getType()->isReferenceType())
1334           NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
1335               CGF.getTarget().getPointerWidth(0));
1336         else
1337           NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
1338       }
1339       
1340       return NumNonZeroBytes;
1341     }
1342   }
1343   
1344   
1345   CharUnits NumNonZeroBytes = CharUnits::Zero();
1346   for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1347     NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
1348   return NumNonZeroBytes;
1349 }
1350
1351 /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
1352 /// zeros in it, emit a memset and avoid storing the individual zeros.
1353 ///
1354 static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
1355                                      CodeGenFunction &CGF) {
1356   // If the slot is already known to be zeroed, nothing to do.  Don't mess with
1357   // volatile stores.
1358   if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == nullptr)
1359     return;
1360
1361   // C++ objects with a user-declared constructor don't need zero'ing.
1362   if (CGF.getLangOpts().CPlusPlus)
1363     if (const RecordType *RT = CGF.getContext()
1364                        .getBaseElementType(E->getType())->getAs<RecordType>()) {
1365       const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1366       if (RD->hasUserDeclaredConstructor())
1367         return;
1368     }
1369
1370   // If the type is 16-bytes or smaller, prefer individual stores over memset.
1371   std::pair<CharUnits, CharUnits> TypeInfo =
1372     CGF.getContext().getTypeInfoInChars(E->getType());
1373   if (TypeInfo.first <= CharUnits::fromQuantity(16))
1374     return;
1375
1376   // Check to see if over 3/4 of the initializer are known to be zero.  If so,
1377   // we prefer to emit memset + individual stores for the rest.
1378   CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
1379   if (NumNonZeroBytes*4 > TypeInfo.first)
1380     return;
1381   
1382   // Okay, it seems like a good idea to use an initial memset, emit the call.
1383   llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first.getQuantity());
1384   CharUnits Align = TypeInfo.second;
1385
1386   llvm::Value *Loc = Slot.getAddr();
1387   
1388   Loc = CGF.Builder.CreateBitCast(Loc, CGF.Int8PtrTy);
1389   CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, 
1390                            Align.getQuantity(), false);
1391   
1392   // Tell the AggExprEmitter that the slot is known zero.
1393   Slot.setZeroed();
1394 }
1395
1396
1397
1398
1399 /// EmitAggExpr - Emit the computation of the specified expression of aggregate
1400 /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
1401 /// the value of the aggregate expression is not needed.  If VolatileDest is
1402 /// true, DestPtr cannot be 0.
1403 void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) {
1404   assert(E && hasAggregateEvaluationKind(E->getType()) &&
1405          "Invalid aggregate expression to emit");
1406   assert((Slot.getAddr() != nullptr || Slot.isIgnored()) &&
1407          "slot has bits but no address");
1408
1409   // Optimize the slot if possible.
1410   CheckAggExprForMemSetUse(Slot, E, *this);
1411  
1412   AggExprEmitter(*this, Slot, Slot.isIgnored()).Visit(const_cast<Expr*>(E));
1413 }
1414
1415 LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
1416   assert(hasAggregateEvaluationKind(E->getType()) && "Invalid argument!");
1417   llvm::Value *Temp = CreateMemTemp(E->getType());
1418   LValue LV = MakeAddrLValue(Temp, E->getType());
1419   EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,
1420                                          AggValueSlot::DoesNotNeedGCBarriers,
1421                                          AggValueSlot::IsNotAliased));
1422   return LV;
1423 }
1424
1425 void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
1426                                         llvm::Value *SrcPtr, QualType Ty,
1427                                         bool isVolatile,
1428                                         CharUnits alignment,
1429                                         bool isAssignment) {
1430   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
1431
1432   if (getLangOpts().CPlusPlus) {
1433     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1434       CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
1435       assert((Record->hasTrivialCopyConstructor() || 
1436               Record->hasTrivialCopyAssignment() ||
1437               Record->hasTrivialMoveConstructor() ||
1438               Record->hasTrivialMoveAssignment() ||
1439               Record->isUnion()) &&
1440              "Trying to aggregate-copy a type without a trivial copy/move "
1441              "constructor or assignment operator");
1442       // Ignore empty classes in C++.
1443       if (Record->isEmpty())
1444         return;
1445     }
1446   }
1447   
1448   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
1449   // C99 6.5.16.1p3, which states "If the value being stored in an object is
1450   // read from another object that overlaps in anyway the storage of the first
1451   // object, then the overlap shall be exact and the two objects shall have
1452   // qualified or unqualified versions of a compatible type."
1453   //
1454   // memcpy is not defined if the source and destination pointers are exactly
1455   // equal, but other compilers do this optimization, and almost every memcpy
1456   // implementation handles this case safely.  If there is a libc that does not
1457   // safely handle this, we can add a target hook.
1458
1459   // Get data size and alignment info for this aggregate. If this is an
1460   // assignment don't copy the tail padding. Otherwise copying it is fine.
1461   std::pair<CharUnits, CharUnits> TypeInfo;
1462   if (isAssignment)
1463     TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);
1464   else
1465     TypeInfo = getContext().getTypeInfoInChars(Ty);
1466
1467   if (alignment.isZero())
1468     alignment = TypeInfo.second;
1469
1470   llvm::Value *SizeVal = nullptr;
1471   if (TypeInfo.first.isZero()) {
1472     // But note that getTypeInfo returns 0 for a VLA.
1473     if (auto *VAT = dyn_cast_or_null<VariableArrayType>(
1474             getContext().getAsArrayType(Ty))) {
1475       QualType BaseEltTy;
1476       SizeVal = emitArrayLength(VAT, BaseEltTy, DestPtr);
1477       TypeInfo = getContext().getTypeInfoDataSizeInChars(BaseEltTy);
1478       std::pair<CharUnits, CharUnits> LastElementTypeInfo;
1479       if (!isAssignment)
1480         LastElementTypeInfo = getContext().getTypeInfoInChars(BaseEltTy);
1481       assert(!TypeInfo.first.isZero());
1482       SizeVal = Builder.CreateNUWMul(
1483           SizeVal,
1484           llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()));
1485       if (!isAssignment) {
1486         SizeVal = Builder.CreateNUWSub(
1487             SizeVal,
1488             llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()));
1489         SizeVal = Builder.CreateNUWAdd(
1490             SizeVal, llvm::ConstantInt::get(
1491                          SizeTy, LastElementTypeInfo.first.getQuantity()));
1492       }
1493     }
1494   }
1495   if (!SizeVal) {
1496     SizeVal = llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity());
1497   }
1498
1499   // FIXME: If we have a volatile struct, the optimizer can remove what might
1500   // appear to be `extra' memory ops:
1501   //
1502   // volatile struct { int i; } a, b;
1503   //
1504   // int main() {
1505   //   a = b;
1506   //   a = b;
1507   // }
1508   //
1509   // we need to use a different call here.  We use isVolatile to indicate when
1510   // either the source or the destination is volatile.
1511
1512   llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
1513   llvm::Type *DBP =
1514     llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace());
1515   DestPtr = Builder.CreateBitCast(DestPtr, DBP);
1516
1517   llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
1518   llvm::Type *SBP =
1519     llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace());
1520   SrcPtr = Builder.CreateBitCast(SrcPtr, SBP);
1521
1522   // Don't do any of the memmove_collectable tests if GC isn't set.
1523   if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
1524     // fall through
1525   } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1526     RecordDecl *Record = RecordTy->getDecl();
1527     if (Record->hasObjectMember()) {
1528       CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, 
1529                                                     SizeVal);
1530       return;
1531     }
1532   } else if (Ty->isArrayType()) {
1533     QualType BaseType = getContext().getBaseElementType(Ty);
1534     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
1535       if (RecordTy->getDecl()->hasObjectMember()) {
1536         CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr, 
1537                                                       SizeVal);
1538         return;
1539       }
1540     }
1541   }
1542
1543   // Determine the metadata to describe the position of any padding in this
1544   // memcpy, as well as the TBAA tags for the members of the struct, in case
1545   // the optimizer wishes to expand it in to scalar memory operations.
1546   llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty);
1547
1548   Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, alignment.getQuantity(),
1549                        isVolatile, /*TBAATag=*/nullptr, TBAAStructTag);
1550 }