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