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