1f22ef01cSRoman Divacky //===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This contains code to emit Aggregate Expr nodes as LLVM code.
11f22ef01cSRoman Divacky //
12f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
13f22ef01cSRoman Divacky 
14f22ef01cSRoman Divacky #include "CodeGenFunction.h"
15f22ef01cSRoman Divacky #include "CGObjCRuntime.h"
16139f7f9bSDimitry Andric #include "CodeGenModule.h"
17f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h"
18f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h"
19dff0c46cSDimitry Andric #include "clang/AST/DeclTemplate.h"
20f22ef01cSRoman Divacky #include "clang/AST/StmtVisitor.h"
21139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
22139f7f9bSDimitry Andric #include "llvm/IR/Function.h"
23139f7f9bSDimitry Andric #include "llvm/IR/GlobalVariable.h"
24139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
25f22ef01cSRoman Divacky using namespace clang;
26f22ef01cSRoman Divacky using namespace CodeGen;
27f22ef01cSRoman Divacky 
28f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
29f22ef01cSRoman Divacky //                        Aggregate Expression Emitter
30f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
31f22ef01cSRoman Divacky 
32f22ef01cSRoman Divacky namespace  {
33f22ef01cSRoman Divacky class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
34f22ef01cSRoman Divacky   CodeGenFunction &CGF;
35f22ef01cSRoman Divacky   CGBuilderTy &Builder;
362754fe60SDimitry Andric   AggValueSlot Dest;
3797bc6c73SDimitry Andric   bool IsResultUnused;
38f22ef01cSRoman Divacky 
396122f3e6SDimitry Andric   /// We want to use 'dest' as the return slot except under two
406122f3e6SDimitry Andric   /// conditions:
416122f3e6SDimitry Andric   ///   - The destination slot requires garbage collection, so we
426122f3e6SDimitry Andric   ///     need to use the GC API.
436122f3e6SDimitry Andric   ///   - The destination slot is potentially aliased.
446122f3e6SDimitry Andric   bool shouldUseDestForReturnSlot() const {
456122f3e6SDimitry Andric     return !(Dest.requiresGCollection() || Dest.isPotentiallyAliased());
466122f3e6SDimitry Andric   }
476122f3e6SDimitry Andric 
48f22ef01cSRoman Divacky   ReturnValueSlot getReturnValueSlot() const {
496122f3e6SDimitry Andric     if (!shouldUseDestForReturnSlot())
506122f3e6SDimitry Andric       return ReturnValueSlot();
51f22ef01cSRoman Divacky 
520623d748SDimitry Andric     return ReturnValueSlot(Dest.getAddress(), Dest.isVolatile(),
530623d748SDimitry Andric                            IsResultUnused);
542754fe60SDimitry Andric   }
552754fe60SDimitry Andric 
562754fe60SDimitry Andric   AggValueSlot EnsureSlot(QualType T) {
572754fe60SDimitry Andric     if (!Dest.isIgnored()) return Dest;
582754fe60SDimitry Andric     return CGF.CreateAggTemp(T, "agg.tmp.ensured");
59f22ef01cSRoman Divacky   }
607ae0e2c9SDimitry Andric   void EnsureDest(QualType T) {
617ae0e2c9SDimitry Andric     if (!Dest.isIgnored()) return;
627ae0e2c9SDimitry Andric     Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured");
637ae0e2c9SDimitry Andric   }
64f22ef01cSRoman Divacky 
65f22ef01cSRoman Divacky public:
6697bc6c73SDimitry Andric   AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest, bool IsResultUnused)
6797bc6c73SDimitry Andric     : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
6897bc6c73SDimitry Andric     IsResultUnused(IsResultUnused) { }
69f22ef01cSRoman Divacky 
70f22ef01cSRoman Divacky   //===--------------------------------------------------------------------===//
71f22ef01cSRoman Divacky   //                               Utilities
72f22ef01cSRoman Divacky   //===--------------------------------------------------------------------===//
73f22ef01cSRoman Divacky 
74f22ef01cSRoman Divacky   /// EmitAggLoadOfLValue - Given an expression with aggregate type that
75f22ef01cSRoman Divacky   /// represents a value lvalue, this method emits the address of the lvalue,
76f22ef01cSRoman Divacky   /// then loads the result into DestPtr.
77f22ef01cSRoman Divacky   void EmitAggLoadOfLValue(const Expr *E);
78f22ef01cSRoman Divacky 
79f22ef01cSRoman Divacky   /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
807ae0e2c9SDimitry Andric   void EmitFinalDestCopy(QualType type, const LValue &src);
810623d748SDimitry Andric   void EmitFinalDestCopy(QualType type, RValue src);
827ae0e2c9SDimitry Andric   void EmitCopy(QualType type, const AggValueSlot &dest,
837ae0e2c9SDimitry Andric                 const AggValueSlot &src);
84f22ef01cSRoman Divacky 
856122f3e6SDimitry Andric   void EmitMoveFromReturnSlot(const Expr *E, RValue Src);
866122f3e6SDimitry Andric 
870623d748SDimitry Andric   void EmitArrayInit(Address DestPtr, llvm::ArrayType *AType,
88dff0c46cSDimitry Andric                      QualType elementType, InitListExpr *E);
89dff0c46cSDimitry Andric 
906122f3e6SDimitry Andric   AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
91dff0c46cSDimitry Andric     if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))
926122f3e6SDimitry Andric       return AggValueSlot::NeedsGCBarriers;
936122f3e6SDimitry Andric     return AggValueSlot::DoesNotNeedGCBarriers;
946122f3e6SDimitry Andric   }
95f22ef01cSRoman Divacky 
96f22ef01cSRoman Divacky   bool TypeRequiresGCollection(QualType T);
97f22ef01cSRoman Divacky 
98f22ef01cSRoman Divacky   //===--------------------------------------------------------------------===//
99f22ef01cSRoman Divacky   //                            Visitor Methods
100f22ef01cSRoman Divacky   //===--------------------------------------------------------------------===//
101f22ef01cSRoman Divacky 
10233956c43SDimitry Andric   void Visit(Expr *E) {
10333956c43SDimitry Andric     ApplyDebugLocation DL(CGF, E);
10433956c43SDimitry Andric     StmtVisitor<AggExprEmitter>::Visit(E);
10533956c43SDimitry Andric   }
10633956c43SDimitry Andric 
107f22ef01cSRoman Divacky   void VisitStmt(Stmt *S) {
108f22ef01cSRoman Divacky     CGF.ErrorUnsupported(S, "aggregate expression");
109f22ef01cSRoman Divacky   }
110f22ef01cSRoman Divacky   void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
1113b0f4066SDimitry Andric   void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
1123b0f4066SDimitry Andric     Visit(GE->getResultExpr());
1133b0f4066SDimitry Andric   }
11420e90f04SDimitry Andric   void VisitCoawaitExpr(CoawaitExpr *E) {
11520e90f04SDimitry Andric     CGF.EmitCoawaitExpr(*E, Dest, IsResultUnused);
11620e90f04SDimitry Andric   }
11720e90f04SDimitry Andric   void VisitCoyieldExpr(CoyieldExpr *E) {
11820e90f04SDimitry Andric     CGF.EmitCoyieldExpr(*E, Dest, IsResultUnused);
11920e90f04SDimitry Andric   }
12020e90f04SDimitry Andric   void VisitUnaryCoawait(UnaryOperator *E) { Visit(E->getSubExpr()); }
121f22ef01cSRoman Divacky   void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
12217a519f9SDimitry Andric   void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
12317a519f9SDimitry Andric     return Visit(E->getReplacement());
12417a519f9SDimitry Andric   }
125f22ef01cSRoman Divacky 
126f22ef01cSRoman Divacky   // l-values.
1279a199699SDimitry Andric   void VisitDeclRefExpr(DeclRefExpr *E) { EmitAggLoadOfLValue(E); }
128f22ef01cSRoman Divacky   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
129f22ef01cSRoman Divacky   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
130f22ef01cSRoman Divacky   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
13117a519f9SDimitry Andric   void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
132f22ef01cSRoman Divacky   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
133f22ef01cSRoman Divacky     EmitAggLoadOfLValue(E);
134f22ef01cSRoman Divacky   }
135f22ef01cSRoman Divacky   void VisitPredefinedExpr(const PredefinedExpr *E) {
136f22ef01cSRoman Divacky     EmitAggLoadOfLValue(E);
137f22ef01cSRoman Divacky   }
138f22ef01cSRoman Divacky 
139f22ef01cSRoman Divacky   // Operators.
140f22ef01cSRoman Divacky   void VisitCastExpr(CastExpr *E);
141f22ef01cSRoman Divacky   void VisitCallExpr(const CallExpr *E);
142f22ef01cSRoman Divacky   void VisitStmtExpr(const StmtExpr *E);
143f22ef01cSRoman Divacky   void VisitBinaryOperator(const BinaryOperator *BO);
144f22ef01cSRoman Divacky   void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
145f22ef01cSRoman Divacky   void VisitBinAssign(const BinaryOperator *E);
146f22ef01cSRoman Divacky   void VisitBinComma(const BinaryOperator *E);
147f22ef01cSRoman Divacky 
148f22ef01cSRoman Divacky   void VisitObjCMessageExpr(ObjCMessageExpr *E);
149f22ef01cSRoman Divacky   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
150f22ef01cSRoman Divacky     EmitAggLoadOfLValue(E);
151f22ef01cSRoman Divacky   }
152f22ef01cSRoman Divacky 
1538f0fd8f6SDimitry Andric   void VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E);
1542754fe60SDimitry Andric   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
155f22ef01cSRoman Divacky   void VisitChooseExpr(const ChooseExpr *CE);
156f22ef01cSRoman Divacky   void VisitInitListExpr(InitListExpr *E);
15744290647SDimitry Andric   void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
15844290647SDimitry Andric                               llvm::Value *outerBegin = nullptr);
159f22ef01cSRoman Divacky   void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
1608f0fd8f6SDimitry Andric   void VisitNoInitExpr(NoInitExpr *E) { } // Do nothing.
161f22ef01cSRoman Divacky   void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
162f22ef01cSRoman Divacky     Visit(DAE->getExpr());
163f22ef01cSRoman Divacky   }
164284c1978SDimitry Andric   void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
165284c1978SDimitry Andric     CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
166284c1978SDimitry Andric     Visit(DIE->getExpr());
167284c1978SDimitry Andric   }
168f22ef01cSRoman Divacky   void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
169f22ef01cSRoman Divacky   void VisitCXXConstructExpr(const CXXConstructExpr *E);
170e7145dcbSDimitry Andric   void VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
171dff0c46cSDimitry Andric   void VisitLambdaExpr(LambdaExpr *E);
172f785676fSDimitry Andric   void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
1732754fe60SDimitry Andric   void VisitExprWithCleanups(ExprWithCleanups *E);
174ffd1746dSEd Schouten   void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
175f22ef01cSRoman Divacky   void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
17617a519f9SDimitry Andric   void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
1772754fe60SDimitry Andric   void VisitOpaqueValueExpr(OpaqueValueExpr *E);
1782754fe60SDimitry Andric 
179dff0c46cSDimitry Andric   void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
180dff0c46cSDimitry Andric     if (E->isGLValue()) {
181dff0c46cSDimitry Andric       LValue LV = CGF.EmitPseudoObjectLValue(E);
1827ae0e2c9SDimitry Andric       return EmitFinalDestCopy(E->getType(), LV);
183dff0c46cSDimitry Andric     }
184dff0c46cSDimitry Andric 
185dff0c46cSDimitry Andric     CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
186dff0c46cSDimitry Andric   }
187dff0c46cSDimitry Andric 
188f22ef01cSRoman Divacky   void VisitVAArgExpr(VAArgExpr *E);
189f22ef01cSRoman Divacky 
19017a519f9SDimitry Andric   void EmitInitializationToLValue(Expr *E, LValue Address);
19117a519f9SDimitry Andric   void EmitNullInitializationToLValue(LValue Address);
192f22ef01cSRoman Divacky   //  case Expr::ChooseExprClass:
193f22ef01cSRoman Divacky   void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
1946122f3e6SDimitry Andric   void VisitAtomicExpr(AtomicExpr *E) {
1950623d748SDimitry Andric     RValue Res = CGF.EmitAtomicExpr(E);
1960623d748SDimitry Andric     EmitFinalDestCopy(E->getType(), Res);
1976122f3e6SDimitry Andric   }
198f22ef01cSRoman Divacky };
199f22ef01cSRoman Divacky }  // end anonymous namespace.
200f22ef01cSRoman Divacky 
201f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
202f22ef01cSRoman Divacky //                                Utilities
203f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
204f22ef01cSRoman Divacky 
205f22ef01cSRoman Divacky /// EmitAggLoadOfLValue - Given an expression with aggregate type that
206f22ef01cSRoman Divacky /// represents a value lvalue, this method emits the address of the lvalue,
207f22ef01cSRoman Divacky /// then loads the result into DestPtr.
208f22ef01cSRoman Divacky void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
209f22ef01cSRoman Divacky   LValue LV = CGF.EmitLValue(E);
210139f7f9bSDimitry Andric 
211139f7f9bSDimitry Andric   // If the type of the l-value is atomic, then do an atomic load.
21233956c43SDimitry Andric   if (LV.getType()->isAtomicType() || CGF.LValueIsSuitableForInlineAtomic(LV)) {
213f785676fSDimitry Andric     CGF.EmitAtomicLoad(LV, E->getExprLoc(), Dest);
214139f7f9bSDimitry Andric     return;
215139f7f9bSDimitry Andric   }
216139f7f9bSDimitry Andric 
2177ae0e2c9SDimitry Andric   EmitFinalDestCopy(E->getType(), LV);
218f22ef01cSRoman Divacky }
219f22ef01cSRoman Divacky 
220f22ef01cSRoman Divacky /// \brief True if the given aggregate type requires special GC API calls.
221f22ef01cSRoman Divacky bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
222f22ef01cSRoman Divacky   // Only record types have members that might require garbage collection.
223f22ef01cSRoman Divacky   const RecordType *RecordTy = T->getAs<RecordType>();
224f22ef01cSRoman Divacky   if (!RecordTy) return false;
225f22ef01cSRoman Divacky 
226f22ef01cSRoman Divacky   // Don't mess with non-trivial C++ types.
227f22ef01cSRoman Divacky   RecordDecl *Record = RecordTy->getDecl();
228f22ef01cSRoman Divacky   if (isa<CXXRecordDecl>(Record) &&
229139f7f9bSDimitry Andric       (cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() ||
230f22ef01cSRoman Divacky        !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
231f22ef01cSRoman Divacky     return false;
232f22ef01cSRoman Divacky 
233f22ef01cSRoman Divacky   // Check whether the type has an object member.
234f22ef01cSRoman Divacky   return Record->hasObjectMember();
235f22ef01cSRoman Divacky }
236f22ef01cSRoman Divacky 
2376122f3e6SDimitry Andric /// \brief Perform the final move to DestPtr if for some reason
2386122f3e6SDimitry Andric /// getReturnValueSlot() didn't use it directly.
239f22ef01cSRoman Divacky ///
240f22ef01cSRoman Divacky /// The idea is that you do something like this:
241f22ef01cSRoman Divacky ///   RValue Result = EmitSomething(..., getReturnValueSlot());
2426122f3e6SDimitry Andric ///   EmitMoveFromReturnSlot(E, Result);
2436122f3e6SDimitry Andric ///
2446122f3e6SDimitry Andric /// If nothing interferes, this will cause the result to be emitted
2456122f3e6SDimitry Andric /// directly into the return value slot.  Otherwise, a final move
2466122f3e6SDimitry Andric /// will be performed.
2477ae0e2c9SDimitry Andric void AggExprEmitter::EmitMoveFromReturnSlot(const Expr *E, RValue src) {
2486122f3e6SDimitry Andric   if (shouldUseDestForReturnSlot()) {
2496122f3e6SDimitry Andric     // Logically, Dest.getAddr() should equal Src.getAggregateAddr().
2506122f3e6SDimitry Andric     // The possibility of undef rvalues complicates that a lot,
2516122f3e6SDimitry Andric     // though, so we can't really assert.
2526122f3e6SDimitry Andric     return;
253ffd1746dSEd Schouten   }
2546122f3e6SDimitry Andric 
2557ae0e2c9SDimitry Andric   // Otherwise, copy from there to the destination.
2560623d748SDimitry Andric   assert(Dest.getPointer() != src.getAggregatePointer());
2570623d748SDimitry Andric   EmitFinalDestCopy(E->getType(), src);
258f22ef01cSRoman Divacky }
259f22ef01cSRoman Divacky 
260f22ef01cSRoman Divacky /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
2610623d748SDimitry Andric void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src) {
2627ae0e2c9SDimitry Andric   assert(src.isAggregate() && "value must be aggregate value!");
2630623d748SDimitry Andric   LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddress(), type);
2647ae0e2c9SDimitry Andric   EmitFinalDestCopy(type, srcLV);
2657ae0e2c9SDimitry Andric }
266f22ef01cSRoman Divacky 
2677ae0e2c9SDimitry Andric /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
2687ae0e2c9SDimitry Andric void AggExprEmitter::EmitFinalDestCopy(QualType type, const LValue &src) {
2692754fe60SDimitry Andric   // If Dest is ignored, then we're evaluating an aggregate expression
2707ae0e2c9SDimitry Andric   // in a context that doesn't care about the result.  Note that loads
2717ae0e2c9SDimitry Andric   // from volatile l-values force the existence of a non-ignored
2727ae0e2c9SDimitry Andric   // destination.
2737ae0e2c9SDimitry Andric   if (Dest.isIgnored())
274f22ef01cSRoman Divacky     return;
275e580952dSDimitry Andric 
2767ae0e2c9SDimitry Andric   AggValueSlot srcAgg =
2777ae0e2c9SDimitry Andric     AggValueSlot::forLValue(src, AggValueSlot::IsDestructed,
2787ae0e2c9SDimitry Andric                             needsGC(type), AggValueSlot::IsAliased);
2797ae0e2c9SDimitry Andric   EmitCopy(type, Dest, srcAgg);
280f22ef01cSRoman Divacky }
281f22ef01cSRoman Divacky 
2827ae0e2c9SDimitry Andric /// Perform a copy from the source into the destination.
2837ae0e2c9SDimitry Andric ///
2847ae0e2c9SDimitry Andric /// \param type - the type of the aggregate being copied; qualifiers are
2857ae0e2c9SDimitry Andric ///   ignored
2867ae0e2c9SDimitry Andric void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,
2877ae0e2c9SDimitry Andric                               const AggValueSlot &src) {
2887ae0e2c9SDimitry Andric   if (dest.requiresGCollection()) {
2897ae0e2c9SDimitry Andric     CharUnits sz = CGF.getContext().getTypeSizeInChars(type);
2907ae0e2c9SDimitry Andric     llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());
291f22ef01cSRoman Divacky     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
2920623d748SDimitry Andric                                                       dest.getAddress(),
2930623d748SDimitry Andric                                                       src.getAddress(),
2947ae0e2c9SDimitry Andric                                                       size);
295f22ef01cSRoman Divacky     return;
296f22ef01cSRoman Divacky   }
2977ae0e2c9SDimitry Andric 
298f22ef01cSRoman Divacky   // If the result of the assignment is used, copy the LHS there also.
2997ae0e2c9SDimitry Andric   // It's volatile if either side is.  Use the minimum alignment of
3007ae0e2c9SDimitry Andric   // the two sides.
3010623d748SDimitry Andric   CGF.EmitAggregateCopy(dest.getAddress(), src.getAddress(), type,
3020623d748SDimitry Andric                         dest.isVolatile() || src.isVolatile());
303dff0c46cSDimitry Andric }
304dff0c46cSDimitry Andric 
305dff0c46cSDimitry Andric /// \brief Emit the initializer for a std::initializer_list initialized with a
306dff0c46cSDimitry Andric /// real initializer list.
307f785676fSDimitry Andric void
308f785676fSDimitry Andric AggExprEmitter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
309f785676fSDimitry Andric   // Emit an array containing the elements.  The array is externally destructed
310f785676fSDimitry Andric   // if the std::initializer_list object is.
311f785676fSDimitry Andric   ASTContext &Ctx = CGF.getContext();
312f785676fSDimitry Andric   LValue Array = CGF.EmitLValue(E->getSubExpr());
313f785676fSDimitry Andric   assert(Array.isSimple() && "initializer_list array not a simple lvalue");
3140623d748SDimitry Andric   Address ArrayPtr = Array.getAddress();
315dff0c46cSDimitry Andric 
316f785676fSDimitry Andric   const ConstantArrayType *ArrayType =
317f785676fSDimitry Andric       Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
318f785676fSDimitry Andric   assert(ArrayType && "std::initializer_list constructed from non-array");
319dff0c46cSDimitry Andric 
320f785676fSDimitry Andric   // FIXME: Perform the checks on the field types in SemaInit.
321f785676fSDimitry Andric   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
322f785676fSDimitry Andric   RecordDecl::field_iterator Field = Record->field_begin();
323f785676fSDimitry Andric   if (Field == Record->field_end()) {
324f785676fSDimitry Andric     CGF.ErrorUnsupported(E, "weird std::initializer_list");
325dff0c46cSDimitry Andric     return;
326dff0c46cSDimitry Andric   }
327dff0c46cSDimitry Andric 
328dff0c46cSDimitry Andric   // Start pointer.
329f785676fSDimitry Andric   if (!Field->getType()->isPointerType() ||
330f785676fSDimitry Andric       !Ctx.hasSameType(Field->getType()->getPointeeType(),
331f785676fSDimitry Andric                        ArrayType->getElementType())) {
332f785676fSDimitry Andric     CGF.ErrorUnsupported(E, "weird std::initializer_list");
333dff0c46cSDimitry Andric     return;
334dff0c46cSDimitry Andric   }
335dff0c46cSDimitry Andric 
336f785676fSDimitry Andric   AggValueSlot Dest = EnsureSlot(E->getType());
3370623d748SDimitry Andric   LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
338f785676fSDimitry Andric   LValue Start = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
339f785676fSDimitry Andric   llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0);
340f785676fSDimitry Andric   llvm::Value *IdxStart[] = { Zero, Zero };
341f785676fSDimitry Andric   llvm::Value *ArrayStart =
3420623d748SDimitry Andric       Builder.CreateInBoundsGEP(ArrayPtr.getPointer(), IdxStart, "arraystart");
343f785676fSDimitry Andric   CGF.EmitStoreThroughLValue(RValue::get(ArrayStart), Start);
344f785676fSDimitry Andric   ++Field;
345f785676fSDimitry Andric 
346f785676fSDimitry Andric   if (Field == Record->field_end()) {
347f785676fSDimitry Andric     CGF.ErrorUnsupported(E, "weird std::initializer_list");
348dff0c46cSDimitry Andric     return;
349dff0c46cSDimitry Andric   }
350f785676fSDimitry Andric 
351f785676fSDimitry Andric   llvm::Value *Size = Builder.getInt(ArrayType->getSize());
352f785676fSDimitry Andric   LValue EndOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
353f785676fSDimitry Andric   if (Field->getType()->isPointerType() &&
354f785676fSDimitry Andric       Ctx.hasSameType(Field->getType()->getPointeeType(),
355f785676fSDimitry Andric                       ArrayType->getElementType())) {
356dff0c46cSDimitry Andric     // End pointer.
357f785676fSDimitry Andric     llvm::Value *IdxEnd[] = { Zero, Size };
358f785676fSDimitry Andric     llvm::Value *ArrayEnd =
3590623d748SDimitry Andric         Builder.CreateInBoundsGEP(ArrayPtr.getPointer(), IdxEnd, "arrayend");
360f785676fSDimitry Andric     CGF.EmitStoreThroughLValue(RValue::get(ArrayEnd), EndOrLength);
361f785676fSDimitry Andric   } else if (Ctx.hasSameType(Field->getType(), Ctx.getSizeType())) {
362dff0c46cSDimitry Andric     // Length.
363f785676fSDimitry Andric     CGF.EmitStoreThroughLValue(RValue::get(Size), EndOrLength);
364dff0c46cSDimitry Andric   } else {
365f785676fSDimitry Andric     CGF.ErrorUnsupported(E, "weird std::initializer_list");
366dff0c46cSDimitry Andric     return;
367dff0c46cSDimitry Andric   }
368dff0c46cSDimitry Andric }
369dff0c46cSDimitry Andric 
37059d1ed5bSDimitry Andric /// \brief Determine if E is a trivial array filler, that is, one that is
37159d1ed5bSDimitry Andric /// equivalent to zero-initialization.
37259d1ed5bSDimitry Andric static bool isTrivialFiller(Expr *E) {
37359d1ed5bSDimitry Andric   if (!E)
37459d1ed5bSDimitry Andric     return true;
37559d1ed5bSDimitry Andric 
37659d1ed5bSDimitry Andric   if (isa<ImplicitValueInitExpr>(E))
37759d1ed5bSDimitry Andric     return true;
37859d1ed5bSDimitry Andric 
37959d1ed5bSDimitry Andric   if (auto *ILE = dyn_cast<InitListExpr>(E)) {
38059d1ed5bSDimitry Andric     if (ILE->getNumInits())
38159d1ed5bSDimitry Andric       return false;
38259d1ed5bSDimitry Andric     return isTrivialFiller(ILE->getArrayFiller());
38359d1ed5bSDimitry Andric   }
38459d1ed5bSDimitry Andric 
38559d1ed5bSDimitry Andric   if (auto *Cons = dyn_cast_or_null<CXXConstructExpr>(E))
38659d1ed5bSDimitry Andric     return Cons->getConstructor()->isDefaultConstructor() &&
38759d1ed5bSDimitry Andric            Cons->getConstructor()->isTrivial();
38859d1ed5bSDimitry Andric 
38959d1ed5bSDimitry Andric   // FIXME: Are there other cases where we can avoid emitting an initializer?
39059d1ed5bSDimitry Andric   return false;
39159d1ed5bSDimitry Andric }
39259d1ed5bSDimitry Andric 
393dff0c46cSDimitry Andric /// \brief Emit initialization of an array from an initializer list.
3940623d748SDimitry Andric void AggExprEmitter::EmitArrayInit(Address DestPtr, llvm::ArrayType *AType,
395dff0c46cSDimitry Andric                                    QualType elementType, InitListExpr *E) {
396dff0c46cSDimitry Andric   uint64_t NumInitElements = E->getNumInits();
397dff0c46cSDimitry Andric 
398dff0c46cSDimitry Andric   uint64_t NumArrayElements = AType->getNumElements();
399dff0c46cSDimitry Andric   assert(NumInitElements <= NumArrayElements);
400dff0c46cSDimitry Andric 
401dff0c46cSDimitry Andric   // DestPtr is an array*.  Construct an elementType* by drilling
402dff0c46cSDimitry Andric   // down a level.
403dff0c46cSDimitry Andric   llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
404dff0c46cSDimitry Andric   llvm::Value *indices[] = { zero, zero };
405dff0c46cSDimitry Andric   llvm::Value *begin =
4060623d748SDimitry Andric     Builder.CreateInBoundsGEP(DestPtr.getPointer(), indices, "arrayinit.begin");
4070623d748SDimitry Andric 
4080623d748SDimitry Andric   CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
4090623d748SDimitry Andric   CharUnits elementAlign =
4100623d748SDimitry Andric     DestPtr.getAlignment().alignmentOfArrayElement(elementSize);
411dff0c46cSDimitry Andric 
412dff0c46cSDimitry Andric   // Exception safety requires us to destroy all the
413dff0c46cSDimitry Andric   // already-constructed members if an initializer throws.
414dff0c46cSDimitry Andric   // For that, we'll need an EH cleanup.
415dff0c46cSDimitry Andric   QualType::DestructionKind dtorKind = elementType.isDestructedType();
4160623d748SDimitry Andric   Address endOfInit = Address::invalid();
417dff0c46cSDimitry Andric   EHScopeStack::stable_iterator cleanup;
41859d1ed5bSDimitry Andric   llvm::Instruction *cleanupDominator = nullptr;
419dff0c46cSDimitry Andric   if (CGF.needsEHCleanup(dtorKind)) {
420dff0c46cSDimitry Andric     // In principle we could tell the cleanup where we are more
421dff0c46cSDimitry Andric     // directly, but the control flow can get so varied here that it
422dff0c46cSDimitry Andric     // would actually be quite complex.  Therefore we go through an
423dff0c46cSDimitry Andric     // alloca.
4240623d748SDimitry Andric     endOfInit = CGF.CreateTempAlloca(begin->getType(), CGF.getPointerAlign(),
425dff0c46cSDimitry Andric                                      "arrayinit.endOfInit");
426dff0c46cSDimitry Andric     cleanupDominator = Builder.CreateStore(begin, endOfInit);
427dff0c46cSDimitry Andric     CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
4280623d748SDimitry Andric                                          elementAlign,
429dff0c46cSDimitry Andric                                          CGF.getDestroyer(dtorKind));
430dff0c46cSDimitry Andric     cleanup = CGF.EHStack.stable_begin();
431dff0c46cSDimitry Andric 
432dff0c46cSDimitry Andric   // Otherwise, remember that we didn't need a cleanup.
433dff0c46cSDimitry Andric   } else {
434dff0c46cSDimitry Andric     dtorKind = QualType::DK_none;
435dff0c46cSDimitry Andric   }
436dff0c46cSDimitry Andric 
437dff0c46cSDimitry Andric   llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
438dff0c46cSDimitry Andric 
439dff0c46cSDimitry Andric   // The 'current element to initialize'.  The invariants on this
440dff0c46cSDimitry Andric   // variable are complicated.  Essentially, after each iteration of
441dff0c46cSDimitry Andric   // the loop, it points to the last initialized element, except
442dff0c46cSDimitry Andric   // that it points to the beginning of the array before any
443dff0c46cSDimitry Andric   // elements have been initialized.
444dff0c46cSDimitry Andric   llvm::Value *element = begin;
445dff0c46cSDimitry Andric 
446dff0c46cSDimitry Andric   // Emit the explicit initializers.
447dff0c46cSDimitry Andric   for (uint64_t i = 0; i != NumInitElements; ++i) {
448dff0c46cSDimitry Andric     // Advance to the next element.
449dff0c46cSDimitry Andric     if (i > 0) {
450dff0c46cSDimitry Andric       element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element");
451dff0c46cSDimitry Andric 
452dff0c46cSDimitry Andric       // Tell the cleanup that it needs to destroy up to this
453dff0c46cSDimitry Andric       // element.  TODO: some of these stores can be trivially
454dff0c46cSDimitry Andric       // observed to be unnecessary.
4550623d748SDimitry Andric       if (endOfInit.isValid()) Builder.CreateStore(element, endOfInit);
456dff0c46cSDimitry Andric     }
457dff0c46cSDimitry Andric 
4580623d748SDimitry Andric     LValue elementLV =
4590623d748SDimitry Andric       CGF.MakeAddrLValue(Address(element, elementAlign), elementType);
460dff0c46cSDimitry Andric     EmitInitializationToLValue(E->getInit(i), elementLV);
461dff0c46cSDimitry Andric   }
462dff0c46cSDimitry Andric 
463dff0c46cSDimitry Andric   // Check whether there's a non-trivial array-fill expression.
464dff0c46cSDimitry Andric   Expr *filler = E->getArrayFiller();
46559d1ed5bSDimitry Andric   bool hasTrivialFiller = isTrivialFiller(filler);
466dff0c46cSDimitry Andric 
467dff0c46cSDimitry Andric   // Any remaining elements need to be zero-initialized, possibly
468dff0c46cSDimitry Andric   // using the filler expression.  We can skip this if the we're
469dff0c46cSDimitry Andric   // emitting to zeroed memory.
470dff0c46cSDimitry Andric   if (NumInitElements != NumArrayElements &&
471dff0c46cSDimitry Andric       !(Dest.isZeroed() && hasTrivialFiller &&
472dff0c46cSDimitry Andric         CGF.getTypes().isZeroInitializable(elementType))) {
473dff0c46cSDimitry Andric 
474dff0c46cSDimitry Andric     // Use an actual loop.  This is basically
475dff0c46cSDimitry Andric     //   do { *array++ = filler; } while (array != end);
476dff0c46cSDimitry Andric 
477dff0c46cSDimitry Andric     // Advance to the start of the rest of the array.
478dff0c46cSDimitry Andric     if (NumInitElements) {
479dff0c46cSDimitry Andric       element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start");
4800623d748SDimitry Andric       if (endOfInit.isValid()) Builder.CreateStore(element, endOfInit);
481dff0c46cSDimitry Andric     }
482dff0c46cSDimitry Andric 
483dff0c46cSDimitry Andric     // Compute the end of the array.
484dff0c46cSDimitry Andric     llvm::Value *end = Builder.CreateInBoundsGEP(begin,
485dff0c46cSDimitry Andric                       llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
486dff0c46cSDimitry Andric                                                  "arrayinit.end");
487dff0c46cSDimitry Andric 
488dff0c46cSDimitry Andric     llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
489dff0c46cSDimitry Andric     llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
490dff0c46cSDimitry Andric 
491dff0c46cSDimitry Andric     // Jump into the body.
492dff0c46cSDimitry Andric     CGF.EmitBlock(bodyBB);
493dff0c46cSDimitry Andric     llvm::PHINode *currentElement =
494dff0c46cSDimitry Andric       Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
495dff0c46cSDimitry Andric     currentElement->addIncoming(element, entryBB);
496dff0c46cSDimitry Andric 
497dff0c46cSDimitry Andric     // Emit the actual filler expression.
4985517e702SDimitry Andric     {
4995517e702SDimitry Andric       // C++1z [class.temporary]p5:
5005517e702SDimitry Andric       //   when a default constructor is called to initialize an element of
5015517e702SDimitry Andric       //   an array with no corresponding initializer [...] the destruction of
5025517e702SDimitry Andric       //   every temporary created in a default argument is sequenced before
5035517e702SDimitry Andric       //   the construction of the next array element, if any
5045517e702SDimitry Andric       CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
5050623d748SDimitry Andric       LValue elementLV =
5060623d748SDimitry Andric         CGF.MakeAddrLValue(Address(currentElement, elementAlign), elementType);
507dff0c46cSDimitry Andric       if (filler)
508dff0c46cSDimitry Andric         EmitInitializationToLValue(filler, elementLV);
509dff0c46cSDimitry Andric       else
510dff0c46cSDimitry Andric         EmitNullInitializationToLValue(elementLV);
5115517e702SDimitry Andric     }
512dff0c46cSDimitry Andric 
513dff0c46cSDimitry Andric     // Move on to the next element.
514dff0c46cSDimitry Andric     llvm::Value *nextElement =
515dff0c46cSDimitry Andric       Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
516dff0c46cSDimitry Andric 
517dff0c46cSDimitry Andric     // Tell the EH cleanup that we finished with the last element.
5180623d748SDimitry Andric     if (endOfInit.isValid()) Builder.CreateStore(nextElement, endOfInit);
519dff0c46cSDimitry Andric 
520dff0c46cSDimitry Andric     // Leave the loop if we're done.
521dff0c46cSDimitry Andric     llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
522dff0c46cSDimitry Andric                                              "arrayinit.done");
523dff0c46cSDimitry Andric     llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
524dff0c46cSDimitry Andric     Builder.CreateCondBr(done, endBB, bodyBB);
525dff0c46cSDimitry Andric     currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
526dff0c46cSDimitry Andric 
527dff0c46cSDimitry Andric     CGF.EmitBlock(endBB);
528dff0c46cSDimitry Andric   }
529dff0c46cSDimitry Andric 
530dff0c46cSDimitry Andric   // Leave the partial-array cleanup if we entered one.
531dff0c46cSDimitry Andric   if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator);
532f22ef01cSRoman Divacky }
533f22ef01cSRoman Divacky 
534f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
535f22ef01cSRoman Divacky //                            Visitor Methods
536f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
537f22ef01cSRoman Divacky 
53817a519f9SDimitry Andric void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
53917a519f9SDimitry Andric   Visit(E->GetTemporaryExpr());
54017a519f9SDimitry Andric }
54117a519f9SDimitry Andric 
5422754fe60SDimitry Andric void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
5437ae0e2c9SDimitry Andric   EmitFinalDestCopy(e->getType(), CGF.getOpaqueLValueMapping(e));
5442754fe60SDimitry Andric }
5452754fe60SDimitry Andric 
54617a519f9SDimitry Andric void
54717a519f9SDimitry Andric AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
548139f7f9bSDimitry Andric   if (Dest.isPotentiallyAliased() &&
549139f7f9bSDimitry Andric       E->getType().isPODType(CGF.getContext())) {
55017a519f9SDimitry Andric     // For a POD type, just emit a load of the lvalue + a copy, because our
55117a519f9SDimitry Andric     // compound literal might alias the destination.
55217a519f9SDimitry Andric     EmitAggLoadOfLValue(E);
55317a519f9SDimitry Andric     return;
55417a519f9SDimitry Andric   }
55517a519f9SDimitry Andric 
55617a519f9SDimitry Andric   AggValueSlot Slot = EnsureSlot(E->getType());
55717a519f9SDimitry Andric   CGF.EmitAggExpr(E->getInitializer(), Slot);
55817a519f9SDimitry Andric }
55917a519f9SDimitry Andric 
560139f7f9bSDimitry Andric /// Attempt to look through various unimportant expressions to find a
561139f7f9bSDimitry Andric /// cast of the given kind.
562139f7f9bSDimitry Andric static Expr *findPeephole(Expr *op, CastKind kind) {
563139f7f9bSDimitry Andric   while (true) {
564139f7f9bSDimitry Andric     op = op->IgnoreParens();
565139f7f9bSDimitry Andric     if (CastExpr *castE = dyn_cast<CastExpr>(op)) {
566139f7f9bSDimitry Andric       if (castE->getCastKind() == kind)
567139f7f9bSDimitry Andric         return castE->getSubExpr();
568139f7f9bSDimitry Andric       if (castE->getCastKind() == CK_NoOp)
569139f7f9bSDimitry Andric         continue;
570139f7f9bSDimitry Andric     }
57159d1ed5bSDimitry Andric     return nullptr;
572139f7f9bSDimitry Andric   }
573139f7f9bSDimitry Andric }
57417a519f9SDimitry Andric 
575f22ef01cSRoman Divacky void AggExprEmitter::VisitCastExpr(CastExpr *E) {
5760623d748SDimitry Andric   if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
5770623d748SDimitry Andric     CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
578f22ef01cSRoman Divacky   switch (E->getCastKind()) {
579e580952dSDimitry Andric   case CK_Dynamic: {
5803861d79fSDimitry Andric     // FIXME: Can this actually happen? We have no test coverage for it.
581f22ef01cSRoman Divacky     assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
5823861d79fSDimitry Andric     LValue LV = CGF.EmitCheckedLValue(E->getSubExpr(),
5833861d79fSDimitry Andric                                       CodeGenFunction::TCK_Load);
584f22ef01cSRoman Divacky     // FIXME: Do we also need to handle property references here?
585f22ef01cSRoman Divacky     if (LV.isSimple())
586f22ef01cSRoman Divacky       CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
587f22ef01cSRoman Divacky     else
588f22ef01cSRoman Divacky       CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
589f22ef01cSRoman Divacky 
5902754fe60SDimitry Andric     if (!Dest.isIgnored())
591f22ef01cSRoman Divacky       CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
592f22ef01cSRoman Divacky     break;
593f22ef01cSRoman Divacky   }
594f22ef01cSRoman Divacky 
595e580952dSDimitry Andric   case CK_ToUnion: {
59633956c43SDimitry Andric     // Evaluate even if the destination is ignored.
59733956c43SDimitry Andric     if (Dest.isIgnored()) {
59833956c43SDimitry Andric       CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(),
59933956c43SDimitry Andric                       /*ignoreResult=*/true);
60033956c43SDimitry Andric       break;
60133956c43SDimitry Andric     }
6023b0f4066SDimitry Andric 
603f22ef01cSRoman Divacky     // GCC union extension
604e580952dSDimitry Andric     QualType Ty = E->getSubExpr()->getType();
6050623d748SDimitry Andric     Address CastPtr =
6060623d748SDimitry Andric       Builder.CreateElementBitCast(Dest.getAddress(), CGF.ConvertType(Ty));
60717a519f9SDimitry Andric     EmitInitializationToLValue(E->getSubExpr(),
60817a519f9SDimitry Andric                                CGF.MakeAddrLValue(CastPtr, Ty));
609f22ef01cSRoman Divacky     break;
610f22ef01cSRoman Divacky   }
611f22ef01cSRoman Divacky 
612e580952dSDimitry Andric   case CK_DerivedToBase:
613e580952dSDimitry Andric   case CK_BaseToDerived:
614e580952dSDimitry Andric   case CK_UncheckedDerivedToBase: {
6156122f3e6SDimitry Andric     llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
616f22ef01cSRoman Divacky                 "should have been unpacked before we got here");
617f22ef01cSRoman Divacky   }
618f22ef01cSRoman Divacky 
619139f7f9bSDimitry Andric   case CK_NonAtomicToAtomic:
620139f7f9bSDimitry Andric   case CK_AtomicToNonAtomic: {
621139f7f9bSDimitry Andric     bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);
622139f7f9bSDimitry Andric 
623139f7f9bSDimitry Andric     // Determine the atomic and value types.
624139f7f9bSDimitry Andric     QualType atomicType = E->getSubExpr()->getType();
625139f7f9bSDimitry Andric     QualType valueType = E->getType();
626139f7f9bSDimitry Andric     if (isToAtomic) std::swap(atomicType, valueType);
627139f7f9bSDimitry Andric 
628139f7f9bSDimitry Andric     assert(atomicType->isAtomicType());
629139f7f9bSDimitry Andric     assert(CGF.getContext().hasSameUnqualifiedType(valueType,
630139f7f9bSDimitry Andric                           atomicType->castAs<AtomicType>()->getValueType()));
631139f7f9bSDimitry Andric 
632139f7f9bSDimitry Andric     // Just recurse normally if we're ignoring the result or the
633139f7f9bSDimitry Andric     // atomic type doesn't change representation.
634139f7f9bSDimitry Andric     if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {
635139f7f9bSDimitry Andric       return Visit(E->getSubExpr());
636139f7f9bSDimitry Andric     }
637139f7f9bSDimitry Andric 
638139f7f9bSDimitry Andric     CastKind peepholeTarget =
639139f7f9bSDimitry Andric       (isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic);
640139f7f9bSDimitry Andric 
641139f7f9bSDimitry Andric     // These two cases are reverses of each other; try to peephole them.
642139f7f9bSDimitry Andric     if (Expr *op = findPeephole(E->getSubExpr(), peepholeTarget)) {
643139f7f9bSDimitry Andric       assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),
644139f7f9bSDimitry Andric                                                      E->getType()) &&
645139f7f9bSDimitry Andric            "peephole significantly changed types?");
646139f7f9bSDimitry Andric       return Visit(op);
647139f7f9bSDimitry Andric     }
648139f7f9bSDimitry Andric 
649139f7f9bSDimitry Andric     // If we're converting an r-value of non-atomic type to an r-value
650f785676fSDimitry Andric     // of atomic type, just emit directly into the relevant sub-object.
651139f7f9bSDimitry Andric     if (isToAtomic) {
652f785676fSDimitry Andric       AggValueSlot valueDest = Dest;
653f785676fSDimitry Andric       if (!valueDest.isIgnored() && CGF.CGM.isPaddedAtomicType(atomicType)) {
654f785676fSDimitry Andric         // Zero-initialize.  (Strictly speaking, we only need to intialize
655f785676fSDimitry Andric         // the padding at the end, but this is simpler.)
656f785676fSDimitry Andric         if (!Dest.isZeroed())
6570623d748SDimitry Andric           CGF.EmitNullInitialization(Dest.getAddress(), atomicType);
658f785676fSDimitry Andric 
659f785676fSDimitry Andric         // Build a GEP to refer to the subobject.
6600623d748SDimitry Andric         Address valueAddr =
6610623d748SDimitry Andric             CGF.Builder.CreateStructGEP(valueDest.getAddress(), 0,
6620623d748SDimitry Andric                                         CharUnits());
663f785676fSDimitry Andric         valueDest = AggValueSlot::forAddr(valueAddr,
664f785676fSDimitry Andric                                           valueDest.getQualifiers(),
665f785676fSDimitry Andric                                           valueDest.isExternallyDestructed(),
666f785676fSDimitry Andric                                           valueDest.requiresGCollection(),
667f785676fSDimitry Andric                                           valueDest.isPotentiallyAliased(),
668f785676fSDimitry Andric                                           AggValueSlot::IsZeroed);
669f785676fSDimitry Andric       }
670f785676fSDimitry Andric 
671f785676fSDimitry Andric       CGF.EmitAggExpr(E->getSubExpr(), valueDest);
672139f7f9bSDimitry Andric       return;
673139f7f9bSDimitry Andric     }
674139f7f9bSDimitry Andric 
675139f7f9bSDimitry Andric     // Otherwise, we're converting an atomic type to a non-atomic type.
676f785676fSDimitry Andric     // Make an atomic temporary, emit into that, and then copy the value out.
677139f7f9bSDimitry Andric     AggValueSlot atomicSlot =
678139f7f9bSDimitry Andric       CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");
679139f7f9bSDimitry Andric     CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
680139f7f9bSDimitry Andric 
6810623d748SDimitry Andric     Address valueAddr =
6820623d748SDimitry Andric       Builder.CreateStructGEP(atomicSlot.getAddress(), 0, CharUnits());
683139f7f9bSDimitry Andric     RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());
684139f7f9bSDimitry Andric     return EmitFinalDestCopy(valueType, rvalue);
685139f7f9bSDimitry Andric   }
686139f7f9bSDimitry Andric 
6877ae0e2c9SDimitry Andric   case CK_LValueToRValue:
6887ae0e2c9SDimitry Andric     // If we're loading from a volatile type, force the destination
6897ae0e2c9SDimitry Andric     // into existence.
6907ae0e2c9SDimitry Andric     if (E->getSubExpr()->getType().isVolatileQualified()) {
6917ae0e2c9SDimitry Andric       EnsureDest(E->getType());
6927ae0e2c9SDimitry Andric       return Visit(E->getSubExpr());
6937ae0e2c9SDimitry Andric     }
694139f7f9bSDimitry Andric 
69513ddaa84SDimitry Andric     LLVM_FALLTHROUGH;
6967ae0e2c9SDimitry Andric 
697e580952dSDimitry Andric   case CK_NoOp:
698e580952dSDimitry Andric   case CK_UserDefinedConversion:
699e580952dSDimitry Andric   case CK_ConstructorConversion:
700f22ef01cSRoman Divacky     assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
701f22ef01cSRoman Divacky                                                    E->getType()) &&
702f22ef01cSRoman Divacky            "Implicit cast types must be compatible");
703f22ef01cSRoman Divacky     Visit(E->getSubExpr());
704f22ef01cSRoman Divacky     break;
705f22ef01cSRoman Divacky 
706e580952dSDimitry Andric   case CK_LValueBitCast:
7072754fe60SDimitry Andric     llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
7082754fe60SDimitry Andric 
7092754fe60SDimitry Andric   case CK_Dependent:
7102754fe60SDimitry Andric   case CK_BitCast:
7112754fe60SDimitry Andric   case CK_ArrayToPointerDecay:
7122754fe60SDimitry Andric   case CK_FunctionToPointerDecay:
7132754fe60SDimitry Andric   case CK_NullToPointer:
7142754fe60SDimitry Andric   case CK_NullToMemberPointer:
7152754fe60SDimitry Andric   case CK_BaseToDerivedMemberPointer:
7162754fe60SDimitry Andric   case CK_DerivedToBaseMemberPointer:
7172754fe60SDimitry Andric   case CK_MemberPointerToBoolean:
718dff0c46cSDimitry Andric   case CK_ReinterpretMemberPointer:
7192754fe60SDimitry Andric   case CK_IntegralToPointer:
7202754fe60SDimitry Andric   case CK_PointerToIntegral:
7212754fe60SDimitry Andric   case CK_PointerToBoolean:
7222754fe60SDimitry Andric   case CK_ToVoid:
7232754fe60SDimitry Andric   case CK_VectorSplat:
7242754fe60SDimitry Andric   case CK_IntegralCast:
725444ed5c5SDimitry Andric   case CK_BooleanToSignedIntegral:
7262754fe60SDimitry Andric   case CK_IntegralToBoolean:
7272754fe60SDimitry Andric   case CK_IntegralToFloating:
7282754fe60SDimitry Andric   case CK_FloatingToIntegral:
7292754fe60SDimitry Andric   case CK_FloatingToBoolean:
7302754fe60SDimitry Andric   case CK_FloatingCast:
7316122f3e6SDimitry Andric   case CK_CPointerToObjCPointerCast:
7326122f3e6SDimitry Andric   case CK_BlockPointerToObjCPointerCast:
7332754fe60SDimitry Andric   case CK_AnyPointerToBlockPointerCast:
7342754fe60SDimitry Andric   case CK_ObjCObjectLValueCast:
7352754fe60SDimitry Andric   case CK_FloatingRealToComplex:
7362754fe60SDimitry Andric   case CK_FloatingComplexToReal:
7372754fe60SDimitry Andric   case CK_FloatingComplexToBoolean:
7382754fe60SDimitry Andric   case CK_FloatingComplexCast:
7392754fe60SDimitry Andric   case CK_FloatingComplexToIntegralComplex:
7402754fe60SDimitry Andric   case CK_IntegralRealToComplex:
7412754fe60SDimitry Andric   case CK_IntegralComplexToReal:
7422754fe60SDimitry Andric   case CK_IntegralComplexToBoolean:
7432754fe60SDimitry Andric   case CK_IntegralComplexCast:
7442754fe60SDimitry Andric   case CK_IntegralComplexToFloatingComplex:
7456122f3e6SDimitry Andric   case CK_ARCProduceObject:
7466122f3e6SDimitry Andric   case CK_ARCConsumeObject:
7476122f3e6SDimitry Andric   case CK_ARCReclaimReturnedObject:
7486122f3e6SDimitry Andric   case CK_ARCExtendBlockObject:
749dff0c46cSDimitry Andric   case CK_CopyAndAutoreleaseBlockObject:
7503861d79fSDimitry Andric   case CK_BuiltinFnToFnPtr:
751139f7f9bSDimitry Andric   case CK_ZeroToOCLEvent:
75244290647SDimitry Andric   case CK_ZeroToOCLQueue:
75359d1ed5bSDimitry Andric   case CK_AddressSpaceConversion:
75444290647SDimitry Andric   case CK_IntToOCLSampler:
7552754fe60SDimitry Andric     llvm_unreachable("cast kind invalid for aggregate types");
756f22ef01cSRoman Divacky   }
757f22ef01cSRoman Divacky }
758f22ef01cSRoman Divacky 
759f22ef01cSRoman Divacky void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
76033956c43SDimitry Andric   if (E->getCallReturnType(CGF.getContext())->isReferenceType()) {
761f22ef01cSRoman Divacky     EmitAggLoadOfLValue(E);
762f22ef01cSRoman Divacky     return;
763f22ef01cSRoman Divacky   }
764f22ef01cSRoman Divacky 
765f22ef01cSRoman Divacky   RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
7666122f3e6SDimitry Andric   EmitMoveFromReturnSlot(E, RV);
767f22ef01cSRoman Divacky }
768f22ef01cSRoman Divacky 
769f22ef01cSRoman Divacky void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
770f22ef01cSRoman Divacky   RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
7716122f3e6SDimitry Andric   EmitMoveFromReturnSlot(E, RV);
772f22ef01cSRoman Divacky }
773f22ef01cSRoman Divacky 
774f22ef01cSRoman Divacky void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
7752754fe60SDimitry Andric   CGF.EmitIgnoredExpr(E->getLHS());
7762754fe60SDimitry Andric   Visit(E->getRHS());
777f22ef01cSRoman Divacky }
778f22ef01cSRoman Divacky 
779f22ef01cSRoman Divacky void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
7802754fe60SDimitry Andric   CodeGenFunction::StmtExprEvaluation eval(CGF);
7812754fe60SDimitry Andric   CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
782f22ef01cSRoman Divacky }
783f22ef01cSRoman Divacky 
784f22ef01cSRoman Divacky void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
785e580952dSDimitry Andric   if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
786f22ef01cSRoman Divacky     VisitPointerToDataMemberBinaryOperator(E);
787f22ef01cSRoman Divacky   else
788f22ef01cSRoman Divacky     CGF.ErrorUnsupported(E, "aggregate binary expression");
789f22ef01cSRoman Divacky }
790f22ef01cSRoman Divacky 
791f22ef01cSRoman Divacky void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
792f22ef01cSRoman Divacky                                                     const BinaryOperator *E) {
793f22ef01cSRoman Divacky   LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
7947ae0e2c9SDimitry Andric   EmitFinalDestCopy(E->getType(), LV);
7957ae0e2c9SDimitry Andric }
7967ae0e2c9SDimitry Andric 
7977ae0e2c9SDimitry Andric /// Is the value of the given expression possibly a reference to or
7987ae0e2c9SDimitry Andric /// into a __block variable?
7997ae0e2c9SDimitry Andric static bool isBlockVarRef(const Expr *E) {
8007ae0e2c9SDimitry Andric   // Make sure we look through parens.
8017ae0e2c9SDimitry Andric   E = E->IgnoreParens();
8027ae0e2c9SDimitry Andric 
8037ae0e2c9SDimitry Andric   // Check for a direct reference to a __block variable.
8047ae0e2c9SDimitry Andric   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8057ae0e2c9SDimitry Andric     const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8067ae0e2c9SDimitry Andric     return (var && var->hasAttr<BlocksAttr>());
8077ae0e2c9SDimitry Andric   }
8087ae0e2c9SDimitry Andric 
8097ae0e2c9SDimitry Andric   // More complicated stuff.
8107ae0e2c9SDimitry Andric 
8117ae0e2c9SDimitry Andric   // Binary operators.
8127ae0e2c9SDimitry Andric   if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {
8137ae0e2c9SDimitry Andric     // For an assignment or pointer-to-member operation, just care
8147ae0e2c9SDimitry Andric     // about the LHS.
8157ae0e2c9SDimitry Andric     if (op->isAssignmentOp() || op->isPtrMemOp())
8167ae0e2c9SDimitry Andric       return isBlockVarRef(op->getLHS());
8177ae0e2c9SDimitry Andric 
8187ae0e2c9SDimitry Andric     // For a comma, just care about the RHS.
8197ae0e2c9SDimitry Andric     if (op->getOpcode() == BO_Comma)
8207ae0e2c9SDimitry Andric       return isBlockVarRef(op->getRHS());
8217ae0e2c9SDimitry Andric 
8227ae0e2c9SDimitry Andric     // FIXME: pointer arithmetic?
8237ae0e2c9SDimitry Andric     return false;
8247ae0e2c9SDimitry Andric 
8257ae0e2c9SDimitry Andric   // Check both sides of a conditional operator.
8267ae0e2c9SDimitry Andric   } else if (const AbstractConditionalOperator *op
8277ae0e2c9SDimitry Andric                = dyn_cast<AbstractConditionalOperator>(E)) {
8287ae0e2c9SDimitry Andric     return isBlockVarRef(op->getTrueExpr())
8297ae0e2c9SDimitry Andric         || isBlockVarRef(op->getFalseExpr());
8307ae0e2c9SDimitry Andric 
8317ae0e2c9SDimitry Andric   // OVEs are required to support BinaryConditionalOperators.
8327ae0e2c9SDimitry Andric   } else if (const OpaqueValueExpr *op
8337ae0e2c9SDimitry Andric                = dyn_cast<OpaqueValueExpr>(E)) {
8347ae0e2c9SDimitry Andric     if (const Expr *src = op->getSourceExpr())
8357ae0e2c9SDimitry Andric       return isBlockVarRef(src);
8367ae0e2c9SDimitry Andric 
8377ae0e2c9SDimitry Andric   // Casts are necessary to get things like (*(int*)&var) = foo().
8387ae0e2c9SDimitry Andric   // We don't really care about the kind of cast here, except
8397ae0e2c9SDimitry Andric   // we don't want to look through l2r casts, because it's okay
8407ae0e2c9SDimitry Andric   // to get the *value* in a __block variable.
8417ae0e2c9SDimitry Andric   } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {
8427ae0e2c9SDimitry Andric     if (cast->getCastKind() == CK_LValueToRValue)
8437ae0e2c9SDimitry Andric       return false;
8447ae0e2c9SDimitry Andric     return isBlockVarRef(cast->getSubExpr());
8457ae0e2c9SDimitry Andric 
8467ae0e2c9SDimitry Andric   // Handle unary operators.  Again, just aggressively look through
8477ae0e2c9SDimitry Andric   // it, ignoring the operation.
8487ae0e2c9SDimitry Andric   } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {
8497ae0e2c9SDimitry Andric     return isBlockVarRef(uop->getSubExpr());
8507ae0e2c9SDimitry Andric 
8517ae0e2c9SDimitry Andric   // Look into the base of a field access.
8527ae0e2c9SDimitry Andric   } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
8537ae0e2c9SDimitry Andric     return isBlockVarRef(mem->getBase());
8547ae0e2c9SDimitry Andric 
8557ae0e2c9SDimitry Andric   // Look into the base of a subscript.
8567ae0e2c9SDimitry Andric   } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {
8577ae0e2c9SDimitry Andric     return isBlockVarRef(sub->getBase());
8587ae0e2c9SDimitry Andric   }
8597ae0e2c9SDimitry Andric 
8607ae0e2c9SDimitry Andric   return false;
861f22ef01cSRoman Divacky }
862f22ef01cSRoman Divacky 
863f22ef01cSRoman Divacky void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
864f22ef01cSRoman Divacky   // For an assignment to work, the value on the right has
865f22ef01cSRoman Divacky   // to be compatible with the value on the left.
866f22ef01cSRoman Divacky   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
867f22ef01cSRoman Divacky                                                  E->getRHS()->getType())
868f22ef01cSRoman Divacky          && "Invalid assignment");
8692754fe60SDimitry Andric 
8707ae0e2c9SDimitry Andric   // If the LHS might be a __block variable, and the RHS can
8717ae0e2c9SDimitry Andric   // potentially cause a block copy, we need to evaluate the RHS first
8727ae0e2c9SDimitry Andric   // so that the assignment goes the right place.
8737ae0e2c9SDimitry Andric   // This is pretty semantically fragile.
8747ae0e2c9SDimitry Andric   if (isBlockVarRef(E->getLHS()) &&
8753b0f4066SDimitry Andric       E->getRHS()->HasSideEffects(CGF.getContext())) {
8767ae0e2c9SDimitry Andric     // Ensure that we have a destination, and evaluate the RHS into that.
8777ae0e2c9SDimitry Andric     EnsureDest(E->getRHS()->getType());
8787ae0e2c9SDimitry Andric     Visit(E->getRHS());
8797ae0e2c9SDimitry Andric 
8807ae0e2c9SDimitry Andric     // Now emit the LHS and copy into it.
8813861d79fSDimitry Andric     LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
8827ae0e2c9SDimitry Andric 
883139f7f9bSDimitry Andric     // That copy is an atomic copy if the LHS is atomic.
88433956c43SDimitry Andric     if (LHS.getType()->isAtomicType() ||
88533956c43SDimitry Andric         CGF.LValueIsSuitableForInlineAtomic(LHS)) {
886139f7f9bSDimitry Andric       CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
887139f7f9bSDimitry Andric       return;
888139f7f9bSDimitry Andric     }
889139f7f9bSDimitry Andric 
8907ae0e2c9SDimitry Andric     EmitCopy(E->getLHS()->getType(),
8917ae0e2c9SDimitry Andric              AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
8926122f3e6SDimitry Andric                                      needsGC(E->getLHS()->getType()),
8937ae0e2c9SDimitry Andric                                      AggValueSlot::IsAliased),
8947ae0e2c9SDimitry Andric              Dest);
8953b0f4066SDimitry Andric     return;
8963b0f4066SDimitry Andric   }
8973b0f4066SDimitry Andric 
898f22ef01cSRoman Divacky   LValue LHS = CGF.EmitLValue(E->getLHS());
899f22ef01cSRoman Divacky 
900139f7f9bSDimitry Andric   // If we have an atomic type, evaluate into the destination and then
901139f7f9bSDimitry Andric   // do an atomic copy.
90233956c43SDimitry Andric   if (LHS.getType()->isAtomicType() ||
90333956c43SDimitry Andric       CGF.LValueIsSuitableForInlineAtomic(LHS)) {
904139f7f9bSDimitry Andric     EnsureDest(E->getRHS()->getType());
905139f7f9bSDimitry Andric     Visit(E->getRHS());
906139f7f9bSDimitry Andric     CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
907139f7f9bSDimitry Andric     return;
908139f7f9bSDimitry Andric   }
909139f7f9bSDimitry Andric 
910f22ef01cSRoman Divacky   // Codegen the RHS so that it stores directly into the LHS.
9116122f3e6SDimitry Andric   AggValueSlot LHSSlot =
9126122f3e6SDimitry Andric     AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
9136122f3e6SDimitry Andric                             needsGC(E->getLHS()->getType()),
9146122f3e6SDimitry Andric                             AggValueSlot::IsAliased);
915139f7f9bSDimitry Andric   // A non-volatile aggregate destination might have volatile member.
916139f7f9bSDimitry Andric   if (!LHSSlot.isVolatile() &&
917139f7f9bSDimitry Andric       CGF.hasVolatileMember(E->getLHS()->getType()))
918139f7f9bSDimitry Andric     LHSSlot.setVolatile(true);
919139f7f9bSDimitry Andric 
9207ae0e2c9SDimitry Andric   CGF.EmitAggExpr(E->getRHS(), LHSSlot);
9217ae0e2c9SDimitry Andric 
9227ae0e2c9SDimitry Andric   // Copy into the destination if the assignment isn't ignored.
9237ae0e2c9SDimitry Andric   EmitFinalDestCopy(E->getType(), LHS);
924f22ef01cSRoman Divacky }
925f22ef01cSRoman Divacky 
9262754fe60SDimitry Andric void AggExprEmitter::
9272754fe60SDimitry Andric VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
928f22ef01cSRoman Divacky   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
929f22ef01cSRoman Divacky   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
930f22ef01cSRoman Divacky   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
931f22ef01cSRoman Divacky 
9322754fe60SDimitry Andric   // Bind the common expression if necessary.
9332754fe60SDimitry Andric   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
9342754fe60SDimitry Andric 
9352754fe60SDimitry Andric   CodeGenFunction::ConditionalEvaluation eval(CGF);
93633956c43SDimitry Andric   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
93733956c43SDimitry Andric                            CGF.getProfileCount(E));
938f22ef01cSRoman Divacky 
9392754fe60SDimitry Andric   // Save whether the destination's lifetime is externally managed.
9406122f3e6SDimitry Andric   bool isExternallyDestructed = Dest.isExternallyDestructed();
9412754fe60SDimitry Andric 
9422754fe60SDimitry Andric   eval.begin(CGF);
943f22ef01cSRoman Divacky   CGF.EmitBlock(LHSBlock);
94433956c43SDimitry Andric   CGF.incrementProfileCounter(E);
9452754fe60SDimitry Andric   Visit(E->getTrueExpr());
9462754fe60SDimitry Andric   eval.end(CGF);
947f22ef01cSRoman Divacky 
9482754fe60SDimitry Andric   assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
9492754fe60SDimitry Andric   CGF.Builder.CreateBr(ContBlock);
950f22ef01cSRoman Divacky 
9512754fe60SDimitry Andric   // If the result of an agg expression is unused, then the emission
9522754fe60SDimitry Andric   // of the LHS might need to create a destination slot.  That's fine
9532754fe60SDimitry Andric   // with us, and we can safely emit the RHS into the same slot, but
9546122f3e6SDimitry Andric   // we shouldn't claim that it's already being destructed.
9556122f3e6SDimitry Andric   Dest.setExternallyDestructed(isExternallyDestructed);
956f22ef01cSRoman Divacky 
9572754fe60SDimitry Andric   eval.begin(CGF);
958f22ef01cSRoman Divacky   CGF.EmitBlock(RHSBlock);
9592754fe60SDimitry Andric   Visit(E->getFalseExpr());
9602754fe60SDimitry Andric   eval.end(CGF);
961f22ef01cSRoman Divacky 
962f22ef01cSRoman Divacky   CGF.EmitBlock(ContBlock);
963f22ef01cSRoman Divacky }
964f22ef01cSRoman Divacky 
965f22ef01cSRoman Divacky void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
966f785676fSDimitry Andric   Visit(CE->getChosenSubExpr());
967f22ef01cSRoman Divacky }
968f22ef01cSRoman Divacky 
969f22ef01cSRoman Divacky void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
9700623d748SDimitry Andric   Address ArgValue = Address::invalid();
9710623d748SDimitry Andric   Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
972f22ef01cSRoman Divacky 
973e7145dcbSDimitry Andric   // If EmitVAArg fails, emit an error.
9740623d748SDimitry Andric   if (!ArgPtr.isValid()) {
975e7145dcbSDimitry Andric     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
976f22ef01cSRoman Divacky     return;
977f22ef01cSRoman Divacky   }
978f22ef01cSRoman Divacky 
9797ae0e2c9SDimitry Andric   EmitFinalDestCopy(VE->getType(), CGF.MakeAddrLValue(ArgPtr, VE->getType()));
980f22ef01cSRoman Divacky }
981f22ef01cSRoman Divacky 
982f22ef01cSRoman Divacky void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
9832754fe60SDimitry Andric   // Ensure that we have a slot, but if we already do, remember
9846122f3e6SDimitry Andric   // whether it was externally destructed.
9856122f3e6SDimitry Andric   bool wasExternallyDestructed = Dest.isExternallyDestructed();
9867ae0e2c9SDimitry Andric   EnsureDest(E->getType());
9876122f3e6SDimitry Andric 
9886122f3e6SDimitry Andric   // We're going to push a destructor if there isn't already one.
9896122f3e6SDimitry Andric   Dest.setExternallyDestructed();
990f22ef01cSRoman Divacky 
991f22ef01cSRoman Divacky   Visit(E->getSubExpr());
992f22ef01cSRoman Divacky 
9936122f3e6SDimitry Andric   // Push that destructor we promised.
9946122f3e6SDimitry Andric   if (!wasExternallyDestructed)
9950623d748SDimitry Andric     CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddress());
996f22ef01cSRoman Divacky }
997f22ef01cSRoman Divacky 
998f22ef01cSRoman Divacky void
999f22ef01cSRoman Divacky AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10002754fe60SDimitry Andric   AggValueSlot Slot = EnsureSlot(E->getType());
10012754fe60SDimitry Andric   CGF.EmitCXXConstructExpr(E, Slot);
1002f22ef01cSRoman Divacky }
1003f22ef01cSRoman Divacky 
1004e7145dcbSDimitry Andric void AggExprEmitter::VisitCXXInheritedCtorInitExpr(
1005e7145dcbSDimitry Andric     const CXXInheritedCtorInitExpr *E) {
1006e7145dcbSDimitry Andric   AggValueSlot Slot = EnsureSlot(E->getType());
1007e7145dcbSDimitry Andric   CGF.EmitInheritedCXXConstructorCall(
1008e7145dcbSDimitry Andric       E->getConstructor(), E->constructsVBase(), Slot.getAddress(),
1009e7145dcbSDimitry Andric       E->inheritedFromVBase(), E);
1010e7145dcbSDimitry Andric }
1011e7145dcbSDimitry Andric 
1012dff0c46cSDimitry Andric void
1013dff0c46cSDimitry Andric AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
1014dff0c46cSDimitry Andric   AggValueSlot Slot = EnsureSlot(E->getType());
1015dff0c46cSDimitry Andric   CGF.EmitLambdaExpr(E, Slot);
1016dff0c46cSDimitry Andric }
1017dff0c46cSDimitry Andric 
10182754fe60SDimitry Andric void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
1019dff0c46cSDimitry Andric   CGF.enterFullExpression(E);
1020dff0c46cSDimitry Andric   CodeGenFunction::RunCleanupsScope cleanups(CGF);
1021dff0c46cSDimitry Andric   Visit(E->getSubExpr());
1022f22ef01cSRoman Divacky }
1023f22ef01cSRoman Divacky 
1024ffd1746dSEd Schouten void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
10252754fe60SDimitry Andric   QualType T = E->getType();
10262754fe60SDimitry Andric   AggValueSlot Slot = EnsureSlot(T);
10270623d748SDimitry Andric   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
1028f22ef01cSRoman Divacky }
1029f22ef01cSRoman Divacky 
1030f22ef01cSRoman Divacky void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
10312754fe60SDimitry Andric   QualType T = E->getType();
10322754fe60SDimitry Andric   AggValueSlot Slot = EnsureSlot(T);
10330623d748SDimitry Andric   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
10342754fe60SDimitry Andric }
1035f22ef01cSRoman Divacky 
10362754fe60SDimitry Andric /// isSimpleZero - If emitting this value will obviously just cause a store of
10372754fe60SDimitry Andric /// zero to memory, return true.  This can return false if uncertain, so it just
10382754fe60SDimitry Andric /// handles simple cases.
10392754fe60SDimitry Andric static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
10403b0f4066SDimitry Andric   E = E->IgnoreParens();
10413b0f4066SDimitry Andric 
10422754fe60SDimitry Andric   // 0
10432754fe60SDimitry Andric   if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
10442754fe60SDimitry Andric     return IL->getValue() == 0;
10452754fe60SDimitry Andric   // +0.0
10462754fe60SDimitry Andric   if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
10472754fe60SDimitry Andric     return FL->getValue().isPosZero();
10482754fe60SDimitry Andric   // int()
10492754fe60SDimitry Andric   if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
10502754fe60SDimitry Andric       CGF.getTypes().isZeroInitializable(E->getType()))
10512754fe60SDimitry Andric     return true;
10522754fe60SDimitry Andric   // (int*)0 - Null pointer expressions.
10532754fe60SDimitry Andric   if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
105444290647SDimitry Andric     return ICE->getCastKind() == CK_NullToPointer &&
105544290647SDimitry Andric         CGF.getTypes().isPointerZeroInitializable(E->getType());
10562754fe60SDimitry Andric   // '\0'
10572754fe60SDimitry Andric   if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
10582754fe60SDimitry Andric     return CL->getValue() == 0;
10592754fe60SDimitry Andric 
10602754fe60SDimitry Andric   // Otherwise, hard case: conservatively return false.
10612754fe60SDimitry Andric   return false;
1062f22ef01cSRoman Divacky }
10632754fe60SDimitry Andric 
1064f22ef01cSRoman Divacky 
1065f22ef01cSRoman Divacky void
106617a519f9SDimitry Andric AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) {
106717a519f9SDimitry Andric   QualType type = LV.getType();
1068f22ef01cSRoman Divacky   // FIXME: Ignore result?
1069f22ef01cSRoman Divacky   // FIXME: Are initializers affected by volatile?
10702754fe60SDimitry Andric   if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
10712754fe60SDimitry Andric     // Storing "i32 0" to a zero'd memory location is a noop.
1072139f7f9bSDimitry Andric     return;
1073139f7f9bSDimitry Andric   } else if (isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) {
1074139f7f9bSDimitry Andric     return EmitNullInitializationToLValue(LV);
10758f0fd8f6SDimitry Andric   } else if (isa<NoInitExpr>(E)) {
10768f0fd8f6SDimitry Andric     // Do nothing.
10778f0fd8f6SDimitry Andric     return;
107817a519f9SDimitry Andric   } else if (type->isReferenceType()) {
1079f785676fSDimitry Andric     RValue RV = CGF.EmitReferenceBindingToExpr(E);
1080139f7f9bSDimitry Andric     return CGF.EmitStoreThroughLValue(RV, LV);
1081139f7f9bSDimitry Andric   }
1082139f7f9bSDimitry Andric 
1083139f7f9bSDimitry Andric   switch (CGF.getEvaluationKind(type)) {
1084139f7f9bSDimitry Andric   case TEK_Complex:
1085139f7f9bSDimitry Andric     CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
1086139f7f9bSDimitry Andric     return;
1087139f7f9bSDimitry Andric   case TEK_Aggregate:
10886122f3e6SDimitry Andric     CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV,
10896122f3e6SDimitry Andric                                                AggValueSlot::IsDestructed,
10906122f3e6SDimitry Andric                                       AggValueSlot::DoesNotNeedGCBarriers,
10916122f3e6SDimitry Andric                                                AggValueSlot::IsNotAliased,
109217a519f9SDimitry Andric                                                Dest.isZeroed()));
1093139f7f9bSDimitry Andric     return;
1094139f7f9bSDimitry Andric   case TEK_Scalar:
1095139f7f9bSDimitry Andric     if (LV.isSimple()) {
109659d1ed5bSDimitry Andric       CGF.EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false);
1097f22ef01cSRoman Divacky     } else {
109817a519f9SDimitry Andric       CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
1099f22ef01cSRoman Divacky     }
1100139f7f9bSDimitry Andric     return;
1101139f7f9bSDimitry Andric   }
1102139f7f9bSDimitry Andric   llvm_unreachable("bad evaluation kind");
1103f22ef01cSRoman Divacky }
1104f22ef01cSRoman Divacky 
110517a519f9SDimitry Andric void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
110617a519f9SDimitry Andric   QualType type = lv.getType();
110717a519f9SDimitry Andric 
11082754fe60SDimitry Andric   // If the destination slot is already zeroed out before the aggregate is
11092754fe60SDimitry Andric   // copied into it, we don't have to emit any zeros here.
111017a519f9SDimitry Andric   if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
11112754fe60SDimitry Andric     return;
11122754fe60SDimitry Andric 
1113139f7f9bSDimitry Andric   if (CGF.hasScalarEvaluationKind(type)) {
1114139f7f9bSDimitry Andric     // For non-aggregates, we can store the appropriate null constant.
1115139f7f9bSDimitry Andric     llvm::Value *null = CGF.CGM.EmitNullConstant(type);
1116dff0c46cSDimitry Andric     // Note that the following is not equivalent to
1117dff0c46cSDimitry Andric     // EmitStoreThroughBitfieldLValue for ARC types.
1118dff0c46cSDimitry Andric     if (lv.isBitField()) {
1119dff0c46cSDimitry Andric       CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
1120dff0c46cSDimitry Andric     } else {
1121dff0c46cSDimitry Andric       assert(lv.isSimple());
1122dff0c46cSDimitry Andric       CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
1123dff0c46cSDimitry Andric     }
1124f22ef01cSRoman Divacky   } else {
1125f22ef01cSRoman Divacky     // There's a potential optimization opportunity in combining
1126f22ef01cSRoman Divacky     // memsets; that would be easy for arrays, but relatively
1127f22ef01cSRoman Divacky     // difficult for structures with the current code.
112817a519f9SDimitry Andric     CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
1129f22ef01cSRoman Divacky   }
1130f22ef01cSRoman Divacky }
1131f22ef01cSRoman Divacky 
1132f22ef01cSRoman Divacky void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
1133f22ef01cSRoman Divacky #if 0
1134f22ef01cSRoman Divacky   // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
1135f22ef01cSRoman Divacky   // (Length of globals? Chunks of zeroed-out space?).
1136f22ef01cSRoman Divacky   //
1137f22ef01cSRoman Divacky   // If we can, prefer a copy from a global; this is a lot less code for long
1138f22ef01cSRoman Divacky   // globals, and it's easier for the current optimizers to analyze.
1139f22ef01cSRoman Divacky   if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
1140f22ef01cSRoman Divacky     llvm::GlobalVariable* GV =
1141f22ef01cSRoman Divacky     new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
1142f22ef01cSRoman Divacky                              llvm::GlobalValue::InternalLinkage, C, "");
11437ae0e2c9SDimitry Andric     EmitFinalDestCopy(E->getType(), CGF.MakeAddrLValue(GV, E->getType()));
1144f22ef01cSRoman Divacky     return;
1145f22ef01cSRoman Divacky   }
1146f22ef01cSRoman Divacky #endif
11472754fe60SDimitry Andric   if (E->hadArrayRangeDesignator())
1148f22ef01cSRoman Divacky     CGF.ErrorUnsupported(E, "GNU array range designator extension");
11492754fe60SDimitry Andric 
115044290647SDimitry Andric   if (E->isTransparent())
115144290647SDimitry Andric     return Visit(E->getInit(0));
115244290647SDimitry Andric 
1153cb4dff85SDimitry Andric   AggValueSlot Dest = EnsureSlot(E->getType());
1154f785676fSDimitry Andric 
11550623d748SDimitry Andric   LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
1156f22ef01cSRoman Divacky 
1157f22ef01cSRoman Divacky   // Handle initialization of an array.
1158f22ef01cSRoman Divacky   if (E->getType()->isArrayType()) {
1159dff0c46cSDimitry Andric     QualType elementType =
1160dff0c46cSDimitry Andric         CGF.getContext().getAsArrayType(E->getType())->getElementType();
1161f22ef01cSRoman Divacky 
11620623d748SDimitry Andric     auto AType = cast<llvm::ArrayType>(Dest.getAddress().getElementType());
11630623d748SDimitry Andric     EmitArrayInit(Dest.getAddress(), AType, elementType, E);
1164f22ef01cSRoman Divacky     return;
1165f22ef01cSRoman Divacky   }
1166f22ef01cSRoman Divacky 
1167f22ef01cSRoman Divacky   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
1168f22ef01cSRoman Divacky 
1169f22ef01cSRoman Divacky   // Do struct initialization; this code just sets each individual member
1170f22ef01cSRoman Divacky   // to the approprate value.  This makes bitfield support automatic;
1171f22ef01cSRoman Divacky   // the disadvantage is that the generated code is more difficult for
1172f22ef01cSRoman Divacky   // the optimizer, especially with bitfields.
1173f22ef01cSRoman Divacky   unsigned NumInitElements = E->getNumInits();
117417a519f9SDimitry Andric   RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
1175e580952dSDimitry Andric 
1176e7145dcbSDimitry Andric   // We'll need to enter cleanup scopes in case any of the element
1177e7145dcbSDimitry Andric   // initializers throws an exception.
1178e7145dcbSDimitry Andric   SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
1179e7145dcbSDimitry Andric   llvm::Instruction *cleanupDominator = nullptr;
1180e7145dcbSDimitry Andric 
1181e7145dcbSDimitry Andric   unsigned curInitIndex = 0;
1182e7145dcbSDimitry Andric 
1183e7145dcbSDimitry Andric   // Emit initialization of base classes.
1184e7145dcbSDimitry Andric   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(record)) {
1185e7145dcbSDimitry Andric     assert(E->getNumInits() >= CXXRD->getNumBases() &&
1186e7145dcbSDimitry Andric            "missing initializer for base class");
1187e7145dcbSDimitry Andric     for (auto &Base : CXXRD->bases()) {
1188e7145dcbSDimitry Andric       assert(!Base.isVirtual() && "should not see vbases here");
1189e7145dcbSDimitry Andric       auto *BaseRD = Base.getType()->getAsCXXRecordDecl();
1190e7145dcbSDimitry Andric       Address V = CGF.GetAddressOfDirectBaseInCompleteClass(
1191e7145dcbSDimitry Andric           Dest.getAddress(), CXXRD, BaseRD,
1192e7145dcbSDimitry Andric           /*isBaseVirtual*/ false);
1193e7145dcbSDimitry Andric       AggValueSlot AggSlot =
1194e7145dcbSDimitry Andric         AggValueSlot::forAddr(V, Qualifiers(),
1195e7145dcbSDimitry Andric                               AggValueSlot::IsDestructed,
1196e7145dcbSDimitry Andric                               AggValueSlot::DoesNotNeedGCBarriers,
1197e7145dcbSDimitry Andric                               AggValueSlot::IsNotAliased);
1198e7145dcbSDimitry Andric       CGF.EmitAggExpr(E->getInit(curInitIndex++), AggSlot);
1199e7145dcbSDimitry Andric 
1200e7145dcbSDimitry Andric       if (QualType::DestructionKind dtorKind =
1201e7145dcbSDimitry Andric               Base.getType().isDestructedType()) {
1202e7145dcbSDimitry Andric         CGF.pushDestroy(dtorKind, V, Base.getType());
1203e7145dcbSDimitry Andric         cleanups.push_back(CGF.EHStack.stable_begin());
1204e7145dcbSDimitry Andric       }
1205e7145dcbSDimitry Andric     }
1206e7145dcbSDimitry Andric   }
1207e7145dcbSDimitry Andric 
1208284c1978SDimitry Andric   // Prepare a 'this' for CXXDefaultInitExprs.
12090623d748SDimitry Andric   CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddress());
1210284c1978SDimitry Andric 
121117a519f9SDimitry Andric   if (record->isUnion()) {
1212f22ef01cSRoman Divacky     // Only initialize one field of a union. The field itself is
1213f22ef01cSRoman Divacky     // specified by the initializer list.
1214f22ef01cSRoman Divacky     if (!E->getInitializedFieldInUnion()) {
1215f22ef01cSRoman Divacky       // Empty union; we have nothing to do.
1216f22ef01cSRoman Divacky 
1217f22ef01cSRoman Divacky #ifndef NDEBUG
1218f22ef01cSRoman Divacky       // Make sure that it's really an empty and not a failure of
1219f22ef01cSRoman Divacky       // semantic analysis.
122059d1ed5bSDimitry Andric       for (const auto *Field : record->fields())
1221f22ef01cSRoman Divacky         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
1222f22ef01cSRoman Divacky #endif
1223f22ef01cSRoman Divacky       return;
1224f22ef01cSRoman Divacky     }
1225f22ef01cSRoman Divacky 
1226f22ef01cSRoman Divacky     // FIXME: volatility
1227f22ef01cSRoman Divacky     FieldDecl *Field = E->getInitializedFieldInUnion();
1228f22ef01cSRoman Divacky 
1229cb4dff85SDimitry Andric     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
1230f22ef01cSRoman Divacky     if (NumInitElements) {
1231f22ef01cSRoman Divacky       // Store the initializer into the field
123217a519f9SDimitry Andric       EmitInitializationToLValue(E->getInit(0), FieldLoc);
1233f22ef01cSRoman Divacky     } else {
12342754fe60SDimitry Andric       // Default-initialize to null.
123517a519f9SDimitry Andric       EmitNullInitializationToLValue(FieldLoc);
1236f22ef01cSRoman Divacky     }
1237f22ef01cSRoman Divacky 
1238f22ef01cSRoman Divacky     return;
1239f22ef01cSRoman Divacky   }
1240f22ef01cSRoman Divacky 
1241f22ef01cSRoman Divacky   // Here we iterate over the fields; this makes it simpler to both
1242f22ef01cSRoman Divacky   // default-initialize fields and skip over unnamed fields.
124359d1ed5bSDimitry Andric   for (const auto *field : record->fields()) {
124417a519f9SDimitry Andric     // We're done once we hit the flexible array member.
124517a519f9SDimitry Andric     if (field->getType()->isIncompleteArrayType())
1246f22ef01cSRoman Divacky       break;
1247f22ef01cSRoman Divacky 
124817a519f9SDimitry Andric     // Always skip anonymous bitfields.
124917a519f9SDimitry Andric     if (field->isUnnamedBitfield())
1250f22ef01cSRoman Divacky       continue;
1251f22ef01cSRoman Divacky 
125217a519f9SDimitry Andric     // We're done if we reach the end of the explicit initializers, we
125317a519f9SDimitry Andric     // have a zeroed object, and the rest of the fields are
125417a519f9SDimitry Andric     // zero-initializable.
125517a519f9SDimitry Andric     if (curInitIndex == NumInitElements && Dest.isZeroed() &&
12562754fe60SDimitry Andric         CGF.getTypes().isZeroInitializable(E->getType()))
12572754fe60SDimitry Andric       break;
12582754fe60SDimitry Andric 
1259cb4dff85SDimitry Andric 
126059d1ed5bSDimitry Andric     LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field);
1261f22ef01cSRoman Divacky     // We never generate write-barries for initialized fields.
126217a519f9SDimitry Andric     LV.setNonGC(true);
12632754fe60SDimitry Andric 
126417a519f9SDimitry Andric     if (curInitIndex < NumInitElements) {
1265f22ef01cSRoman Divacky       // Store the initializer into the field.
126617a519f9SDimitry Andric       EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
1267f22ef01cSRoman Divacky     } else {
126820e90f04SDimitry Andric       // We're out of initializers; default-initialize to null
126917a519f9SDimitry Andric       EmitNullInitializationToLValue(LV);
127017a519f9SDimitry Andric     }
127117a519f9SDimitry Andric 
127217a519f9SDimitry Andric     // Push a destructor if necessary.
127317a519f9SDimitry Andric     // FIXME: if we have an array of structures, all explicitly
127417a519f9SDimitry Andric     // initialized, we can end up pushing a linear number of cleanups.
127517a519f9SDimitry Andric     bool pushedCleanup = false;
127617a519f9SDimitry Andric     if (QualType::DestructionKind dtorKind
127717a519f9SDimitry Andric           = field->getType().isDestructedType()) {
127817a519f9SDimitry Andric       assert(LV.isSimple());
127917a519f9SDimitry Andric       if (CGF.needsEHCleanup(dtorKind)) {
1280dff0c46cSDimitry Andric         if (!cleanupDominator)
12810623d748SDimitry Andric           cleanupDominator = CGF.Builder.CreateAlignedLoad(
12820623d748SDimitry Andric               CGF.Int8Ty,
12830623d748SDimitry Andric               llvm::Constant::getNullValue(CGF.Int8PtrTy),
12840623d748SDimitry Andric               CharUnits::One()); // placeholder
1285dff0c46cSDimitry Andric 
128617a519f9SDimitry Andric         CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
128717a519f9SDimitry Andric                         CGF.getDestroyer(dtorKind), false);
128817a519f9SDimitry Andric         cleanups.push_back(CGF.EHStack.stable_begin());
128917a519f9SDimitry Andric         pushedCleanup = true;
129017a519f9SDimitry Andric       }
1291f22ef01cSRoman Divacky     }
12922754fe60SDimitry Andric 
12932754fe60SDimitry Andric     // If the GEP didn't get used because of a dead zero init or something
12942754fe60SDimitry Andric     // else, clean it up for -O0 builds and general tidiness.
129517a519f9SDimitry Andric     if (!pushedCleanup && LV.isSimple())
12962754fe60SDimitry Andric       if (llvm::GetElementPtrInst *GEP =
12970623d748SDimitry Andric             dyn_cast<llvm::GetElementPtrInst>(LV.getPointer()))
12982754fe60SDimitry Andric         if (GEP->use_empty())
12992754fe60SDimitry Andric           GEP->eraseFromParent();
1300f22ef01cSRoman Divacky   }
130117a519f9SDimitry Andric 
130217a519f9SDimitry Andric   // Deactivate all the partial cleanups in reverse order, which
130317a519f9SDimitry Andric   // generally means popping them.
130417a519f9SDimitry Andric   for (unsigned i = cleanups.size(); i != 0; --i)
1305dff0c46cSDimitry Andric     CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
1306dff0c46cSDimitry Andric 
1307dff0c46cSDimitry Andric   // Destroy the placeholder if we made one.
1308dff0c46cSDimitry Andric   if (cleanupDominator)
1309dff0c46cSDimitry Andric     cleanupDominator->eraseFromParent();
1310f22ef01cSRoman Divacky }
1311f22ef01cSRoman Divacky 
131244290647SDimitry Andric void AggExprEmitter::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
131344290647SDimitry Andric                                             llvm::Value *outerBegin) {
131444290647SDimitry Andric   // Emit the common subexpression.
131544290647SDimitry Andric   CodeGenFunction::OpaqueValueMapping binding(CGF, E->getCommonExpr());
131644290647SDimitry Andric 
131744290647SDimitry Andric   Address destPtr = EnsureSlot(E->getType()).getAddress();
131844290647SDimitry Andric   uint64_t numElements = E->getArraySize().getZExtValue();
131944290647SDimitry Andric 
132044290647SDimitry Andric   if (!numElements)
132144290647SDimitry Andric     return;
132244290647SDimitry Andric 
132344290647SDimitry Andric   // destPtr is an array*. Construct an elementType* by drilling down a level.
132444290647SDimitry Andric   llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
132544290647SDimitry Andric   llvm::Value *indices[] = {zero, zero};
132644290647SDimitry Andric   llvm::Value *begin = Builder.CreateInBoundsGEP(destPtr.getPointer(), indices,
132744290647SDimitry Andric                                                  "arrayinit.begin");
132844290647SDimitry Andric 
132944290647SDimitry Andric   // Prepare to special-case multidimensional array initialization: we avoid
133044290647SDimitry Andric   // emitting multiple destructor loops in that case.
133144290647SDimitry Andric   if (!outerBegin)
133244290647SDimitry Andric     outerBegin = begin;
133344290647SDimitry Andric   ArrayInitLoopExpr *InnerLoop = dyn_cast<ArrayInitLoopExpr>(E->getSubExpr());
133444290647SDimitry Andric 
133544290647SDimitry Andric   QualType elementType =
133644290647SDimitry Andric       CGF.getContext().getAsArrayType(E->getType())->getElementType();
133744290647SDimitry Andric   CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
133844290647SDimitry Andric   CharUnits elementAlign =
133944290647SDimitry Andric       destPtr.getAlignment().alignmentOfArrayElement(elementSize);
134044290647SDimitry Andric 
134144290647SDimitry Andric   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
134244290647SDimitry Andric   llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
134344290647SDimitry Andric 
134444290647SDimitry Andric   // Jump into the body.
134544290647SDimitry Andric   CGF.EmitBlock(bodyBB);
134644290647SDimitry Andric   llvm::PHINode *index =
134744290647SDimitry Andric       Builder.CreatePHI(zero->getType(), 2, "arrayinit.index");
134844290647SDimitry Andric   index->addIncoming(zero, entryBB);
134944290647SDimitry Andric   llvm::Value *element = Builder.CreateInBoundsGEP(begin, index);
135044290647SDimitry Andric 
135144290647SDimitry Andric   // Prepare for a cleanup.
135244290647SDimitry Andric   QualType::DestructionKind dtorKind = elementType.isDestructedType();
135344290647SDimitry Andric   EHScopeStack::stable_iterator cleanup;
135444290647SDimitry Andric   if (CGF.needsEHCleanup(dtorKind) && !InnerLoop) {
135544290647SDimitry Andric     if (outerBegin->getType() != element->getType())
135644290647SDimitry Andric       outerBegin = Builder.CreateBitCast(outerBegin, element->getType());
135744290647SDimitry Andric     CGF.pushRegularPartialArrayCleanup(outerBegin, element, elementType,
135844290647SDimitry Andric                                        elementAlign,
135944290647SDimitry Andric                                        CGF.getDestroyer(dtorKind));
136044290647SDimitry Andric     cleanup = CGF.EHStack.stable_begin();
136144290647SDimitry Andric   } else {
136244290647SDimitry Andric     dtorKind = QualType::DK_none;
136344290647SDimitry Andric   }
136444290647SDimitry Andric 
136544290647SDimitry Andric   // Emit the actual filler expression.
136644290647SDimitry Andric   {
136744290647SDimitry Andric     // Temporaries created in an array initialization loop are destroyed
136844290647SDimitry Andric     // at the end of each iteration.
136944290647SDimitry Andric     CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
137044290647SDimitry Andric     CodeGenFunction::ArrayInitLoopExprScope Scope(CGF, index);
137144290647SDimitry Andric     LValue elementLV =
137244290647SDimitry Andric         CGF.MakeAddrLValue(Address(element, elementAlign), elementType);
137344290647SDimitry Andric 
137444290647SDimitry Andric     if (InnerLoop) {
137544290647SDimitry Andric       // If the subexpression is an ArrayInitLoopExpr, share its cleanup.
137644290647SDimitry Andric       auto elementSlot = AggValueSlot::forLValue(
137744290647SDimitry Andric           elementLV, AggValueSlot::IsDestructed,
137844290647SDimitry Andric           AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased);
137944290647SDimitry Andric       AggExprEmitter(CGF, elementSlot, false)
138044290647SDimitry Andric           .VisitArrayInitLoopExpr(InnerLoop, outerBegin);
138144290647SDimitry Andric     } else
138244290647SDimitry Andric       EmitInitializationToLValue(E->getSubExpr(), elementLV);
138344290647SDimitry Andric   }
138444290647SDimitry Andric 
138544290647SDimitry Andric   // Move on to the next element.
138644290647SDimitry Andric   llvm::Value *nextIndex = Builder.CreateNUWAdd(
138744290647SDimitry Andric       index, llvm::ConstantInt::get(CGF.SizeTy, 1), "arrayinit.next");
138844290647SDimitry Andric   index->addIncoming(nextIndex, Builder.GetInsertBlock());
138944290647SDimitry Andric 
139044290647SDimitry Andric   // Leave the loop if we're done.
139144290647SDimitry Andric   llvm::Value *done = Builder.CreateICmpEQ(
139244290647SDimitry Andric       nextIndex, llvm::ConstantInt::get(CGF.SizeTy, numElements),
139344290647SDimitry Andric       "arrayinit.done");
139444290647SDimitry Andric   llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
139544290647SDimitry Andric   Builder.CreateCondBr(done, endBB, bodyBB);
139644290647SDimitry Andric 
139744290647SDimitry Andric   CGF.EmitBlock(endBB);
139844290647SDimitry Andric 
139944290647SDimitry Andric   // Leave the partial-array cleanup if we entered one.
140044290647SDimitry Andric   if (dtorKind)
140144290647SDimitry Andric     CGF.DeactivateCleanupBlock(cleanup, index);
140244290647SDimitry Andric }
140344290647SDimitry Andric 
14048f0fd8f6SDimitry Andric void AggExprEmitter::VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) {
14058f0fd8f6SDimitry Andric   AggValueSlot Dest = EnsureSlot(E->getType());
14068f0fd8f6SDimitry Andric 
14070623d748SDimitry Andric   LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
14088f0fd8f6SDimitry Andric   EmitInitializationToLValue(E->getBase(), DestLV);
14098f0fd8f6SDimitry Andric   VisitInitListExpr(E->getUpdater());
14108f0fd8f6SDimitry Andric }
14118f0fd8f6SDimitry Andric 
1412f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
1413f22ef01cSRoman Divacky //                        Entry Points into this File
1414f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
1415f22ef01cSRoman Divacky 
14162754fe60SDimitry Andric /// GetNumNonZeroBytesInInit - Get an approximate count of the number of
14172754fe60SDimitry Andric /// non-zero bytes that will be stored when outputting the initializer for the
14182754fe60SDimitry Andric /// specified initializer expression.
14193b0f4066SDimitry Andric static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
14203b0f4066SDimitry Andric   E = E->IgnoreParens();
14212754fe60SDimitry Andric 
14222754fe60SDimitry Andric   // 0 and 0.0 won't require any non-zero stores!
14233b0f4066SDimitry Andric   if (isSimpleZero(E, CGF)) return CharUnits::Zero();
14242754fe60SDimitry Andric 
14252754fe60SDimitry Andric   // If this is an initlist expr, sum up the size of sizes of the (present)
14262754fe60SDimitry Andric   // elements.  If this is something weird, assume the whole thing is non-zero.
14272754fe60SDimitry Andric   const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
142859d1ed5bSDimitry Andric   if (!ILE || !CGF.getTypes().isZeroInitializable(ILE->getType()))
14293b0f4066SDimitry Andric     return CGF.getContext().getTypeSizeInChars(E->getType());
14302754fe60SDimitry Andric 
14312754fe60SDimitry Andric   // InitListExprs for structs have to be handled carefully.  If there are
14322754fe60SDimitry Andric   // reference members, we need to consider the size of the reference, not the
14332754fe60SDimitry Andric   // referencee.  InitListExprs for unions and arrays can't have references.
14342754fe60SDimitry Andric   if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
14352754fe60SDimitry Andric     if (!RT->isUnionType()) {
14362754fe60SDimitry Andric       RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
14373b0f4066SDimitry Andric       CharUnits NumNonZeroBytes = CharUnits::Zero();
14382754fe60SDimitry Andric 
14392754fe60SDimitry Andric       unsigned ILEElement = 0;
1440e7145dcbSDimitry Andric       if (auto *CXXRD = dyn_cast<CXXRecordDecl>(SD))
1441e7145dcbSDimitry Andric         while (ILEElement != CXXRD->getNumBases())
1442e7145dcbSDimitry Andric           NumNonZeroBytes +=
1443e7145dcbSDimitry Andric               GetNumNonZeroBytesInInit(ILE->getInit(ILEElement++), CGF);
144459d1ed5bSDimitry Andric       for (const auto *Field : SD->fields()) {
14452754fe60SDimitry Andric         // We're done once we hit the flexible array member or run out of
14462754fe60SDimitry Andric         // InitListExpr elements.
14472754fe60SDimitry Andric         if (Field->getType()->isIncompleteArrayType() ||
14482754fe60SDimitry Andric             ILEElement == ILE->getNumInits())
14492754fe60SDimitry Andric           break;
14502754fe60SDimitry Andric         if (Field->isUnnamedBitfield())
14512754fe60SDimitry Andric           continue;
14522754fe60SDimitry Andric 
14532754fe60SDimitry Andric         const Expr *E = ILE->getInit(ILEElement++);
14542754fe60SDimitry Andric 
14552754fe60SDimitry Andric         // Reference values are always non-null and have the width of a pointer.
14562754fe60SDimitry Andric         if (Field->getType()->isReferenceType())
14573b0f4066SDimitry Andric           NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
1458284c1978SDimitry Andric               CGF.getTarget().getPointerWidth(0));
14592754fe60SDimitry Andric         else
14602754fe60SDimitry Andric           NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
14612754fe60SDimitry Andric       }
14622754fe60SDimitry Andric 
14632754fe60SDimitry Andric       return NumNonZeroBytes;
14642754fe60SDimitry Andric     }
14652754fe60SDimitry Andric   }
14662754fe60SDimitry Andric 
14672754fe60SDimitry Andric 
14683b0f4066SDimitry Andric   CharUnits NumNonZeroBytes = CharUnits::Zero();
14692754fe60SDimitry Andric   for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
14702754fe60SDimitry Andric     NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
14712754fe60SDimitry Andric   return NumNonZeroBytes;
14722754fe60SDimitry Andric }
14732754fe60SDimitry Andric 
14742754fe60SDimitry Andric /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
14752754fe60SDimitry Andric /// zeros in it, emit a memset and avoid storing the individual zeros.
14762754fe60SDimitry Andric ///
14772754fe60SDimitry Andric static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
14782754fe60SDimitry Andric                                      CodeGenFunction &CGF) {
14792754fe60SDimitry Andric   // If the slot is already known to be zeroed, nothing to do.  Don't mess with
14802754fe60SDimitry Andric   // volatile stores.
14810623d748SDimitry Andric   if (Slot.isZeroed() || Slot.isVolatile() || !Slot.getAddress().isValid())
148259d1ed5bSDimitry Andric     return;
14832754fe60SDimitry Andric 
14843b0f4066SDimitry Andric   // C++ objects with a user-declared constructor don't need zero'ing.
14853861d79fSDimitry Andric   if (CGF.getLangOpts().CPlusPlus)
14863b0f4066SDimitry Andric     if (const RecordType *RT = CGF.getContext()
14873b0f4066SDimitry Andric                        .getBaseElementType(E->getType())->getAs<RecordType>()) {
14883b0f4066SDimitry Andric       const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
14893b0f4066SDimitry Andric       if (RD->hasUserDeclaredConstructor())
14903b0f4066SDimitry Andric         return;
14913b0f4066SDimitry Andric     }
14923b0f4066SDimitry Andric 
14932754fe60SDimitry Andric   // If the type is 16-bytes or smaller, prefer individual stores over memset.
14940623d748SDimitry Andric   CharUnits Size = CGF.getContext().getTypeSizeInChars(E->getType());
14950623d748SDimitry Andric   if (Size <= CharUnits::fromQuantity(16))
14962754fe60SDimitry Andric     return;
14972754fe60SDimitry Andric 
14982754fe60SDimitry Andric   // Check to see if over 3/4 of the initializer are known to be zero.  If so,
14992754fe60SDimitry Andric   // we prefer to emit memset + individual stores for the rest.
15003b0f4066SDimitry Andric   CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
15010623d748SDimitry Andric   if (NumNonZeroBytes*4 > Size)
15022754fe60SDimitry Andric     return;
15032754fe60SDimitry Andric 
15042754fe60SDimitry Andric   // Okay, it seems like a good idea to use an initial memset, emit the call.
15050623d748SDimitry Andric   llvm::Constant *SizeVal = CGF.Builder.getInt64(Size.getQuantity());
15062754fe60SDimitry Andric 
15070623d748SDimitry Andric   Address Loc = Slot.getAddress();
15080623d748SDimitry Andric   Loc = CGF.Builder.CreateElementBitCast(Loc, CGF.Int8Ty);
15090623d748SDimitry Andric   CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, false);
15102754fe60SDimitry Andric 
15112754fe60SDimitry Andric   // Tell the AggExprEmitter that the slot is known zero.
15122754fe60SDimitry Andric   Slot.setZeroed();
15132754fe60SDimitry Andric }
15142754fe60SDimitry Andric 
15152754fe60SDimitry Andric 
15162754fe60SDimitry Andric 
15172754fe60SDimitry Andric 
1518f22ef01cSRoman Divacky /// EmitAggExpr - Emit the computation of the specified expression of aggregate
1519f22ef01cSRoman Divacky /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
1520f22ef01cSRoman Divacky /// the value of the aggregate expression is not needed.  If VolatileDest is
1521f22ef01cSRoman Divacky /// true, DestPtr cannot be 0.
15227ae0e2c9SDimitry Andric void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) {
1523139f7f9bSDimitry Andric   assert(E && hasAggregateEvaluationKind(E->getType()) &&
1524f22ef01cSRoman Divacky          "Invalid aggregate expression to emit");
15250623d748SDimitry Andric   assert((Slot.getAddress().isValid() || Slot.isIgnored()) &&
15262754fe60SDimitry Andric          "slot has bits but no address");
1527f22ef01cSRoman Divacky 
15282754fe60SDimitry Andric   // Optimize the slot if possible.
15292754fe60SDimitry Andric   CheckAggExprForMemSetUse(Slot, E, *this);
15302754fe60SDimitry Andric 
153197bc6c73SDimitry Andric   AggExprEmitter(*this, Slot, Slot.isIgnored()).Visit(const_cast<Expr*>(E));
1532f22ef01cSRoman Divacky }
1533f22ef01cSRoman Divacky 
1534f22ef01cSRoman Divacky LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
1535139f7f9bSDimitry Andric   assert(hasAggregateEvaluationKind(E->getType()) && "Invalid argument!");
15360623d748SDimitry Andric   Address Temp = CreateMemTemp(E->getType());
1537e580952dSDimitry Andric   LValue LV = MakeAddrLValue(Temp, E->getType());
15386122f3e6SDimitry Andric   EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,
15396122f3e6SDimitry Andric                                          AggValueSlot::DoesNotNeedGCBarriers,
15406122f3e6SDimitry Andric                                          AggValueSlot::IsNotAliased));
1541e580952dSDimitry Andric   return LV;
1542f22ef01cSRoman Divacky }
1543f22ef01cSRoman Divacky 
15440623d748SDimitry Andric void CodeGenFunction::EmitAggregateCopy(Address DestPtr,
15450623d748SDimitry Andric                                         Address SrcPtr, QualType Ty,
15467ae0e2c9SDimitry Andric                                         bool isVolatile,
15473861d79fSDimitry Andric                                         bool isAssignment) {
1548f22ef01cSRoman Divacky   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
1549f22ef01cSRoman Divacky 
15503861d79fSDimitry Andric   if (getLangOpts().CPlusPlus) {
1551f22ef01cSRoman Divacky     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1552f22ef01cSRoman Divacky       CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
1553f22ef01cSRoman Divacky       assert((Record->hasTrivialCopyConstructor() ||
15546122f3e6SDimitry Andric               Record->hasTrivialCopyAssignment() ||
15556122f3e6SDimitry Andric               Record->hasTrivialMoveConstructor() ||
155633956c43SDimitry Andric               Record->hasTrivialMoveAssignment() ||
155733956c43SDimitry Andric               Record->isUnion()) &&
1558139f7f9bSDimitry Andric              "Trying to aggregate-copy a type without a trivial copy/move "
1559f22ef01cSRoman Divacky              "constructor or assignment operator");
1560f22ef01cSRoman Divacky       // Ignore empty classes in C++.
1561f22ef01cSRoman Divacky       if (Record->isEmpty())
1562f22ef01cSRoman Divacky         return;
1563f22ef01cSRoman Divacky     }
1564f22ef01cSRoman Divacky   }
1565f22ef01cSRoman Divacky 
1566f22ef01cSRoman Divacky   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
1567f22ef01cSRoman Divacky   // C99 6.5.16.1p3, which states "If the value being stored in an object is
1568f22ef01cSRoman Divacky   // read from another object that overlaps in anyway the storage of the first
1569f22ef01cSRoman Divacky   // object, then the overlap shall be exact and the two objects shall have
1570f22ef01cSRoman Divacky   // qualified or unqualified versions of a compatible type."
1571f22ef01cSRoman Divacky   //
1572f22ef01cSRoman Divacky   // memcpy is not defined if the source and destination pointers are exactly
1573f22ef01cSRoman Divacky   // equal, but other compilers do this optimization, and almost every memcpy
1574f22ef01cSRoman Divacky   // implementation handles this case safely.  If there is a libc that does not
1575f22ef01cSRoman Divacky   // safely handle this, we can add a target hook.
1576f22ef01cSRoman Divacky 
15770623d748SDimitry Andric   // Get data size info for this aggregate. If this is an assignment,
15780623d748SDimitry Andric   // don't copy the tail padding, because we might be assigning into a
15790623d748SDimitry Andric   // base subobject where the tail padding is claimed.  Otherwise,
15800623d748SDimitry Andric   // copying it is fine.
15813861d79fSDimitry Andric   std::pair<CharUnits, CharUnits> TypeInfo;
15823861d79fSDimitry Andric   if (isAssignment)
15833861d79fSDimitry Andric     TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);
15843861d79fSDimitry Andric   else
15853861d79fSDimitry Andric     TypeInfo = getContext().getTypeInfoInChars(Ty);
1586f22ef01cSRoman Divacky 
158733956c43SDimitry Andric   llvm::Value *SizeVal = nullptr;
158833956c43SDimitry Andric   if (TypeInfo.first.isZero()) {
158933956c43SDimitry Andric     // But note that getTypeInfo returns 0 for a VLA.
159033956c43SDimitry Andric     if (auto *VAT = dyn_cast_or_null<VariableArrayType>(
159133956c43SDimitry Andric             getContext().getAsArrayType(Ty))) {
159233956c43SDimitry Andric       QualType BaseEltTy;
159333956c43SDimitry Andric       SizeVal = emitArrayLength(VAT, BaseEltTy, DestPtr);
159433956c43SDimitry Andric       TypeInfo = getContext().getTypeInfoDataSizeInChars(BaseEltTy);
159533956c43SDimitry Andric       std::pair<CharUnits, CharUnits> LastElementTypeInfo;
159633956c43SDimitry Andric       if (!isAssignment)
159733956c43SDimitry Andric         LastElementTypeInfo = getContext().getTypeInfoInChars(BaseEltTy);
159833956c43SDimitry Andric       assert(!TypeInfo.first.isZero());
159933956c43SDimitry Andric       SizeVal = Builder.CreateNUWMul(
160033956c43SDimitry Andric           SizeVal,
160133956c43SDimitry Andric           llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()));
160233956c43SDimitry Andric       if (!isAssignment) {
160333956c43SDimitry Andric         SizeVal = Builder.CreateNUWSub(
160433956c43SDimitry Andric             SizeVal,
160533956c43SDimitry Andric             llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()));
160633956c43SDimitry Andric         SizeVal = Builder.CreateNUWAdd(
160733956c43SDimitry Andric             SizeVal, llvm::ConstantInt::get(
160833956c43SDimitry Andric                          SizeTy, LastElementTypeInfo.first.getQuantity()));
160933956c43SDimitry Andric       }
161033956c43SDimitry Andric     }
161133956c43SDimitry Andric   }
161233956c43SDimitry Andric   if (!SizeVal) {
161333956c43SDimitry Andric     SizeVal = llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity());
161433956c43SDimitry Andric   }
1615f22ef01cSRoman Divacky 
1616f22ef01cSRoman Divacky   // FIXME: If we have a volatile struct, the optimizer can remove what might
1617f22ef01cSRoman Divacky   // appear to be `extra' memory ops:
1618f22ef01cSRoman Divacky   //
1619f22ef01cSRoman Divacky   // volatile struct { int i; } a, b;
1620f22ef01cSRoman Divacky   //
1621f22ef01cSRoman Divacky   // int main() {
1622f22ef01cSRoman Divacky   //   a = b;
1623f22ef01cSRoman Divacky   //   a = b;
1624f22ef01cSRoman Divacky   // }
1625f22ef01cSRoman Divacky   //
1626f22ef01cSRoman Divacky   // we need to use a different call here.  We use isVolatile to indicate when
1627f22ef01cSRoman Divacky   // either the source or the destination is volatile.
1628f22ef01cSRoman Divacky 
16290623d748SDimitry Andric   DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
16300623d748SDimitry Andric   SrcPtr = Builder.CreateElementBitCast(SrcPtr, Int8Ty);
1631f22ef01cSRoman Divacky 
163217a519f9SDimitry Andric   // Don't do any of the memmove_collectable tests if GC isn't set.
1633dff0c46cSDimitry Andric   if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
163417a519f9SDimitry Andric     // fall through
163517a519f9SDimitry Andric   } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1636ffd1746dSEd Schouten     RecordDecl *Record = RecordTy->getDecl();
1637ffd1746dSEd Schouten     if (Record->hasObjectMember()) {
1638ffd1746dSEd Schouten       CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1639ffd1746dSEd Schouten                                                     SizeVal);
1640ffd1746dSEd Schouten       return;
1641ffd1746dSEd Schouten     }
164217a519f9SDimitry Andric   } else if (Ty->isArrayType()) {
1643ffd1746dSEd Schouten     QualType BaseType = getContext().getBaseElementType(Ty);
1644ffd1746dSEd Schouten     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
1645ffd1746dSEd Schouten       if (RecordTy->getDecl()->hasObjectMember()) {
1646ffd1746dSEd Schouten         CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1647ffd1746dSEd Schouten                                                       SizeVal);
1648ffd1746dSEd Schouten         return;
1649ffd1746dSEd Schouten       }
1650ffd1746dSEd Schouten     }
1651ffd1746dSEd Schouten   }
1652ffd1746dSEd Schouten 
16530623d748SDimitry Andric   auto Inst = Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, isVolatile);
16540623d748SDimitry Andric 
16553861d79fSDimitry Andric   // Determine the metadata to describe the position of any padding in this
16563861d79fSDimitry Andric   // memcpy, as well as the TBAA tags for the members of the struct, in case
16573861d79fSDimitry Andric   // the optimizer wishes to expand it in to scalar memory operations.
16580623d748SDimitry Andric   if (llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty))
16590623d748SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa_struct, TBAAStructTag);
1660dff0c46cSDimitry Andric }
1661