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.
127dff0c46cSDimitry Andric   void VisitDeclRefExpr(DeclRefExpr *E) {
128dff0c46cSDimitry Andric     // For aggregates, we should always be able to emit the variable
129dff0c46cSDimitry Andric     // as an l-value unless it's a reference.  This is due to the fact
130dff0c46cSDimitry Andric     // that we can't actually ever see a normal l2r conversion on an
131dff0c46cSDimitry Andric     // aggregate in C++, and in C there's no language standard
132dff0c46cSDimitry Andric     // actively preventing us from listing variables in the captures
133dff0c46cSDimitry Andric     // list of a block.
134dff0c46cSDimitry Andric     if (E->getDecl()->getType()->isReferenceType()) {
135dff0c46cSDimitry Andric       if (CodeGenFunction::ConstantEmission result
136dff0c46cSDimitry Andric             = CGF.tryEmitAsConstant(E)) {
1377ae0e2c9SDimitry Andric         EmitFinalDestCopy(E->getType(), result.getReferenceLValue(CGF, E));
138dff0c46cSDimitry Andric         return;
139dff0c46cSDimitry Andric       }
140dff0c46cSDimitry Andric     }
141dff0c46cSDimitry Andric 
142dff0c46cSDimitry Andric     EmitAggLoadOfLValue(E);
143dff0c46cSDimitry Andric   }
144dff0c46cSDimitry Andric 
145f22ef01cSRoman Divacky   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
146f22ef01cSRoman Divacky   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
147f22ef01cSRoman Divacky   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
14817a519f9SDimitry Andric   void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
149f22ef01cSRoman Divacky   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
150f22ef01cSRoman Divacky     EmitAggLoadOfLValue(E);
151f22ef01cSRoman Divacky   }
152f22ef01cSRoman Divacky   void VisitPredefinedExpr(const PredefinedExpr *E) {
153f22ef01cSRoman Divacky     EmitAggLoadOfLValue(E);
154f22ef01cSRoman Divacky   }
155f22ef01cSRoman Divacky 
156f22ef01cSRoman Divacky   // Operators.
157f22ef01cSRoman Divacky   void VisitCastExpr(CastExpr *E);
158f22ef01cSRoman Divacky   void VisitCallExpr(const CallExpr *E);
159f22ef01cSRoman Divacky   void VisitStmtExpr(const StmtExpr *E);
160f22ef01cSRoman Divacky   void VisitBinaryOperator(const BinaryOperator *BO);
161f22ef01cSRoman Divacky   void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
162f22ef01cSRoman Divacky   void VisitBinAssign(const BinaryOperator *E);
163f22ef01cSRoman Divacky   void VisitBinComma(const BinaryOperator *E);
164f22ef01cSRoman Divacky 
165f22ef01cSRoman Divacky   void VisitObjCMessageExpr(ObjCMessageExpr *E);
166f22ef01cSRoman Divacky   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
167f22ef01cSRoman Divacky     EmitAggLoadOfLValue(E);
168f22ef01cSRoman Divacky   }
169f22ef01cSRoman Divacky 
1708f0fd8f6SDimitry Andric   void VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E);
1712754fe60SDimitry Andric   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
172f22ef01cSRoman Divacky   void VisitChooseExpr(const ChooseExpr *CE);
173f22ef01cSRoman Divacky   void VisitInitListExpr(InitListExpr *E);
17444290647SDimitry Andric   void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
17544290647SDimitry Andric                               llvm::Value *outerBegin = nullptr);
176f22ef01cSRoman Divacky   void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
1778f0fd8f6SDimitry Andric   void VisitNoInitExpr(NoInitExpr *E) { } // Do nothing.
178f22ef01cSRoman Divacky   void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
179f22ef01cSRoman Divacky     Visit(DAE->getExpr());
180f22ef01cSRoman Divacky   }
181284c1978SDimitry Andric   void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
182284c1978SDimitry Andric     CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
183284c1978SDimitry Andric     Visit(DIE->getExpr());
184284c1978SDimitry Andric   }
185f22ef01cSRoman Divacky   void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
186f22ef01cSRoman Divacky   void VisitCXXConstructExpr(const CXXConstructExpr *E);
187e7145dcbSDimitry Andric   void VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
188dff0c46cSDimitry Andric   void VisitLambdaExpr(LambdaExpr *E);
189f785676fSDimitry Andric   void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
1902754fe60SDimitry Andric   void VisitExprWithCleanups(ExprWithCleanups *E);
191ffd1746dSEd Schouten   void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
192f22ef01cSRoman Divacky   void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
19317a519f9SDimitry Andric   void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
1942754fe60SDimitry Andric   void VisitOpaqueValueExpr(OpaqueValueExpr *E);
1952754fe60SDimitry Andric 
196dff0c46cSDimitry Andric   void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
197dff0c46cSDimitry Andric     if (E->isGLValue()) {
198dff0c46cSDimitry Andric       LValue LV = CGF.EmitPseudoObjectLValue(E);
1997ae0e2c9SDimitry Andric       return EmitFinalDestCopy(E->getType(), LV);
200dff0c46cSDimitry Andric     }
201dff0c46cSDimitry Andric 
202dff0c46cSDimitry Andric     CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
203dff0c46cSDimitry Andric   }
204dff0c46cSDimitry Andric 
205f22ef01cSRoman Divacky   void VisitVAArgExpr(VAArgExpr *E);
206f22ef01cSRoman Divacky 
20717a519f9SDimitry Andric   void EmitInitializationToLValue(Expr *E, LValue Address);
20817a519f9SDimitry Andric   void EmitNullInitializationToLValue(LValue Address);
209f22ef01cSRoman Divacky   //  case Expr::ChooseExprClass:
210f22ef01cSRoman Divacky   void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
2116122f3e6SDimitry Andric   void VisitAtomicExpr(AtomicExpr *E) {
2120623d748SDimitry Andric     RValue Res = CGF.EmitAtomicExpr(E);
2130623d748SDimitry Andric     EmitFinalDestCopy(E->getType(), Res);
2146122f3e6SDimitry Andric   }
215f22ef01cSRoman Divacky };
216f22ef01cSRoman Divacky }  // end anonymous namespace.
217f22ef01cSRoman Divacky 
218f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
219f22ef01cSRoman Divacky //                                Utilities
220f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
221f22ef01cSRoman Divacky 
222f22ef01cSRoman Divacky /// EmitAggLoadOfLValue - Given an expression with aggregate type that
223f22ef01cSRoman Divacky /// represents a value lvalue, this method emits the address of the lvalue,
224f22ef01cSRoman Divacky /// then loads the result into DestPtr.
225f22ef01cSRoman Divacky void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
226f22ef01cSRoman Divacky   LValue LV = CGF.EmitLValue(E);
227139f7f9bSDimitry Andric 
228139f7f9bSDimitry Andric   // If the type of the l-value is atomic, then do an atomic load.
22933956c43SDimitry Andric   if (LV.getType()->isAtomicType() || CGF.LValueIsSuitableForInlineAtomic(LV)) {
230f785676fSDimitry Andric     CGF.EmitAtomicLoad(LV, E->getExprLoc(), Dest);
231139f7f9bSDimitry Andric     return;
232139f7f9bSDimitry Andric   }
233139f7f9bSDimitry Andric 
2347ae0e2c9SDimitry Andric   EmitFinalDestCopy(E->getType(), LV);
235f22ef01cSRoman Divacky }
236f22ef01cSRoman Divacky 
237f22ef01cSRoman Divacky /// \brief True if the given aggregate type requires special GC API calls.
238f22ef01cSRoman Divacky bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
239f22ef01cSRoman Divacky   // Only record types have members that might require garbage collection.
240f22ef01cSRoman Divacky   const RecordType *RecordTy = T->getAs<RecordType>();
241f22ef01cSRoman Divacky   if (!RecordTy) return false;
242f22ef01cSRoman Divacky 
243f22ef01cSRoman Divacky   // Don't mess with non-trivial C++ types.
244f22ef01cSRoman Divacky   RecordDecl *Record = RecordTy->getDecl();
245f22ef01cSRoman Divacky   if (isa<CXXRecordDecl>(Record) &&
246139f7f9bSDimitry Andric       (cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() ||
247f22ef01cSRoman Divacky        !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
248f22ef01cSRoman Divacky     return false;
249f22ef01cSRoman Divacky 
250f22ef01cSRoman Divacky   // Check whether the type has an object member.
251f22ef01cSRoman Divacky   return Record->hasObjectMember();
252f22ef01cSRoman Divacky }
253f22ef01cSRoman Divacky 
2546122f3e6SDimitry Andric /// \brief Perform the final move to DestPtr if for some reason
2556122f3e6SDimitry Andric /// getReturnValueSlot() didn't use it directly.
256f22ef01cSRoman Divacky ///
257f22ef01cSRoman Divacky /// The idea is that you do something like this:
258f22ef01cSRoman Divacky ///   RValue Result = EmitSomething(..., getReturnValueSlot());
2596122f3e6SDimitry Andric ///   EmitMoveFromReturnSlot(E, Result);
2606122f3e6SDimitry Andric ///
2616122f3e6SDimitry Andric /// If nothing interferes, this will cause the result to be emitted
2626122f3e6SDimitry Andric /// directly into the return value slot.  Otherwise, a final move
2636122f3e6SDimitry Andric /// will be performed.
2647ae0e2c9SDimitry Andric void AggExprEmitter::EmitMoveFromReturnSlot(const Expr *E, RValue src) {
2656122f3e6SDimitry Andric   if (shouldUseDestForReturnSlot()) {
2666122f3e6SDimitry Andric     // Logically, Dest.getAddr() should equal Src.getAggregateAddr().
2676122f3e6SDimitry Andric     // The possibility of undef rvalues complicates that a lot,
2686122f3e6SDimitry Andric     // though, so we can't really assert.
2696122f3e6SDimitry Andric     return;
270ffd1746dSEd Schouten   }
2716122f3e6SDimitry Andric 
2727ae0e2c9SDimitry Andric   // Otherwise, copy from there to the destination.
2730623d748SDimitry Andric   assert(Dest.getPointer() != src.getAggregatePointer());
2740623d748SDimitry Andric   EmitFinalDestCopy(E->getType(), src);
275f22ef01cSRoman Divacky }
276f22ef01cSRoman Divacky 
277f22ef01cSRoman Divacky /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
2780623d748SDimitry Andric void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src) {
2797ae0e2c9SDimitry Andric   assert(src.isAggregate() && "value must be aggregate value!");
2800623d748SDimitry Andric   LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddress(), type);
2817ae0e2c9SDimitry Andric   EmitFinalDestCopy(type, srcLV);
2827ae0e2c9SDimitry Andric }
283f22ef01cSRoman Divacky 
2847ae0e2c9SDimitry Andric /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
2857ae0e2c9SDimitry Andric void AggExprEmitter::EmitFinalDestCopy(QualType type, const LValue &src) {
2862754fe60SDimitry Andric   // If Dest is ignored, then we're evaluating an aggregate expression
2877ae0e2c9SDimitry Andric   // in a context that doesn't care about the result.  Note that loads
2887ae0e2c9SDimitry Andric   // from volatile l-values force the existence of a non-ignored
2897ae0e2c9SDimitry Andric   // destination.
2907ae0e2c9SDimitry Andric   if (Dest.isIgnored())
291f22ef01cSRoman Divacky     return;
292e580952dSDimitry Andric 
2937ae0e2c9SDimitry Andric   AggValueSlot srcAgg =
2947ae0e2c9SDimitry Andric     AggValueSlot::forLValue(src, AggValueSlot::IsDestructed,
2957ae0e2c9SDimitry Andric                             needsGC(type), AggValueSlot::IsAliased);
2967ae0e2c9SDimitry Andric   EmitCopy(type, Dest, srcAgg);
297f22ef01cSRoman Divacky }
298f22ef01cSRoman Divacky 
2997ae0e2c9SDimitry Andric /// Perform a copy from the source into the destination.
3007ae0e2c9SDimitry Andric ///
3017ae0e2c9SDimitry Andric /// \param type - the type of the aggregate being copied; qualifiers are
3027ae0e2c9SDimitry Andric ///   ignored
3037ae0e2c9SDimitry Andric void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,
3047ae0e2c9SDimitry Andric                               const AggValueSlot &src) {
3057ae0e2c9SDimitry Andric   if (dest.requiresGCollection()) {
3067ae0e2c9SDimitry Andric     CharUnits sz = CGF.getContext().getTypeSizeInChars(type);
3077ae0e2c9SDimitry Andric     llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());
308f22ef01cSRoman Divacky     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
3090623d748SDimitry Andric                                                       dest.getAddress(),
3100623d748SDimitry Andric                                                       src.getAddress(),
3117ae0e2c9SDimitry Andric                                                       size);
312f22ef01cSRoman Divacky     return;
313f22ef01cSRoman Divacky   }
3147ae0e2c9SDimitry Andric 
315f22ef01cSRoman Divacky   // If the result of the assignment is used, copy the LHS there also.
3167ae0e2c9SDimitry Andric   // It's volatile if either side is.  Use the minimum alignment of
3177ae0e2c9SDimitry Andric   // the two sides.
3180623d748SDimitry Andric   CGF.EmitAggregateCopy(dest.getAddress(), src.getAddress(), type,
3190623d748SDimitry Andric                         dest.isVolatile() || src.isVolatile());
320dff0c46cSDimitry Andric }
321dff0c46cSDimitry Andric 
322dff0c46cSDimitry Andric /// \brief Emit the initializer for a std::initializer_list initialized with a
323dff0c46cSDimitry Andric /// real initializer list.
324f785676fSDimitry Andric void
325f785676fSDimitry Andric AggExprEmitter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
326f785676fSDimitry Andric   // Emit an array containing the elements.  The array is externally destructed
327f785676fSDimitry Andric   // if the std::initializer_list object is.
328f785676fSDimitry Andric   ASTContext &Ctx = CGF.getContext();
329f785676fSDimitry Andric   LValue Array = CGF.EmitLValue(E->getSubExpr());
330f785676fSDimitry Andric   assert(Array.isSimple() && "initializer_list array not a simple lvalue");
3310623d748SDimitry Andric   Address ArrayPtr = Array.getAddress();
332dff0c46cSDimitry Andric 
333f785676fSDimitry Andric   const ConstantArrayType *ArrayType =
334f785676fSDimitry Andric       Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
335f785676fSDimitry Andric   assert(ArrayType && "std::initializer_list constructed from non-array");
336dff0c46cSDimitry Andric 
337f785676fSDimitry Andric   // FIXME: Perform the checks on the field types in SemaInit.
338f785676fSDimitry Andric   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
339f785676fSDimitry Andric   RecordDecl::field_iterator Field = Record->field_begin();
340f785676fSDimitry Andric   if (Field == Record->field_end()) {
341f785676fSDimitry Andric     CGF.ErrorUnsupported(E, "weird std::initializer_list");
342dff0c46cSDimitry Andric     return;
343dff0c46cSDimitry Andric   }
344dff0c46cSDimitry Andric 
345dff0c46cSDimitry Andric   // Start pointer.
346f785676fSDimitry Andric   if (!Field->getType()->isPointerType() ||
347f785676fSDimitry Andric       !Ctx.hasSameType(Field->getType()->getPointeeType(),
348f785676fSDimitry Andric                        ArrayType->getElementType())) {
349f785676fSDimitry Andric     CGF.ErrorUnsupported(E, "weird std::initializer_list");
350dff0c46cSDimitry Andric     return;
351dff0c46cSDimitry Andric   }
352dff0c46cSDimitry Andric 
353f785676fSDimitry Andric   AggValueSlot Dest = EnsureSlot(E->getType());
3540623d748SDimitry Andric   LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
355f785676fSDimitry Andric   LValue Start = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
356f785676fSDimitry Andric   llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0);
357f785676fSDimitry Andric   llvm::Value *IdxStart[] = { Zero, Zero };
358f785676fSDimitry Andric   llvm::Value *ArrayStart =
3590623d748SDimitry Andric       Builder.CreateInBoundsGEP(ArrayPtr.getPointer(), IdxStart, "arraystart");
360f785676fSDimitry Andric   CGF.EmitStoreThroughLValue(RValue::get(ArrayStart), Start);
361f785676fSDimitry Andric   ++Field;
362f785676fSDimitry Andric 
363f785676fSDimitry Andric   if (Field == Record->field_end()) {
364f785676fSDimitry Andric     CGF.ErrorUnsupported(E, "weird std::initializer_list");
365dff0c46cSDimitry Andric     return;
366dff0c46cSDimitry Andric   }
367f785676fSDimitry Andric 
368f785676fSDimitry Andric   llvm::Value *Size = Builder.getInt(ArrayType->getSize());
369f785676fSDimitry Andric   LValue EndOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
370f785676fSDimitry Andric   if (Field->getType()->isPointerType() &&
371f785676fSDimitry Andric       Ctx.hasSameType(Field->getType()->getPointeeType(),
372f785676fSDimitry Andric                       ArrayType->getElementType())) {
373dff0c46cSDimitry Andric     // End pointer.
374f785676fSDimitry Andric     llvm::Value *IdxEnd[] = { Zero, Size };
375f785676fSDimitry Andric     llvm::Value *ArrayEnd =
3760623d748SDimitry Andric         Builder.CreateInBoundsGEP(ArrayPtr.getPointer(), IdxEnd, "arrayend");
377f785676fSDimitry Andric     CGF.EmitStoreThroughLValue(RValue::get(ArrayEnd), EndOrLength);
378f785676fSDimitry Andric   } else if (Ctx.hasSameType(Field->getType(), Ctx.getSizeType())) {
379dff0c46cSDimitry Andric     // Length.
380f785676fSDimitry Andric     CGF.EmitStoreThroughLValue(RValue::get(Size), EndOrLength);
381dff0c46cSDimitry Andric   } else {
382f785676fSDimitry Andric     CGF.ErrorUnsupported(E, "weird std::initializer_list");
383dff0c46cSDimitry Andric     return;
384dff0c46cSDimitry Andric   }
385dff0c46cSDimitry Andric }
386dff0c46cSDimitry Andric 
38759d1ed5bSDimitry Andric /// \brief Determine if E is a trivial array filler, that is, one that is
38859d1ed5bSDimitry Andric /// equivalent to zero-initialization.
38959d1ed5bSDimitry Andric static bool isTrivialFiller(Expr *E) {
39059d1ed5bSDimitry Andric   if (!E)
39159d1ed5bSDimitry Andric     return true;
39259d1ed5bSDimitry Andric 
39359d1ed5bSDimitry Andric   if (isa<ImplicitValueInitExpr>(E))
39459d1ed5bSDimitry Andric     return true;
39559d1ed5bSDimitry Andric 
39659d1ed5bSDimitry Andric   if (auto *ILE = dyn_cast<InitListExpr>(E)) {
39759d1ed5bSDimitry Andric     if (ILE->getNumInits())
39859d1ed5bSDimitry Andric       return false;
39959d1ed5bSDimitry Andric     return isTrivialFiller(ILE->getArrayFiller());
40059d1ed5bSDimitry Andric   }
40159d1ed5bSDimitry Andric 
40259d1ed5bSDimitry Andric   if (auto *Cons = dyn_cast_or_null<CXXConstructExpr>(E))
40359d1ed5bSDimitry Andric     return Cons->getConstructor()->isDefaultConstructor() &&
40459d1ed5bSDimitry Andric            Cons->getConstructor()->isTrivial();
40559d1ed5bSDimitry Andric 
40659d1ed5bSDimitry Andric   // FIXME: Are there other cases where we can avoid emitting an initializer?
40759d1ed5bSDimitry Andric   return false;
40859d1ed5bSDimitry Andric }
40959d1ed5bSDimitry Andric 
410dff0c46cSDimitry Andric /// \brief Emit initialization of an array from an initializer list.
4110623d748SDimitry Andric void AggExprEmitter::EmitArrayInit(Address DestPtr, llvm::ArrayType *AType,
412dff0c46cSDimitry Andric                                    QualType elementType, InitListExpr *E) {
413dff0c46cSDimitry Andric   uint64_t NumInitElements = E->getNumInits();
414dff0c46cSDimitry Andric 
415dff0c46cSDimitry Andric   uint64_t NumArrayElements = AType->getNumElements();
416dff0c46cSDimitry Andric   assert(NumInitElements <= NumArrayElements);
417dff0c46cSDimitry Andric 
418dff0c46cSDimitry Andric   // DestPtr is an array*.  Construct an elementType* by drilling
419dff0c46cSDimitry Andric   // down a level.
420dff0c46cSDimitry Andric   llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
421dff0c46cSDimitry Andric   llvm::Value *indices[] = { zero, zero };
422dff0c46cSDimitry Andric   llvm::Value *begin =
4230623d748SDimitry Andric     Builder.CreateInBoundsGEP(DestPtr.getPointer(), indices, "arrayinit.begin");
4240623d748SDimitry Andric 
4250623d748SDimitry Andric   CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
4260623d748SDimitry Andric   CharUnits elementAlign =
4270623d748SDimitry Andric     DestPtr.getAlignment().alignmentOfArrayElement(elementSize);
428dff0c46cSDimitry Andric 
429dff0c46cSDimitry Andric   // Exception safety requires us to destroy all the
430dff0c46cSDimitry Andric   // already-constructed members if an initializer throws.
431dff0c46cSDimitry Andric   // For that, we'll need an EH cleanup.
432dff0c46cSDimitry Andric   QualType::DestructionKind dtorKind = elementType.isDestructedType();
4330623d748SDimitry Andric   Address endOfInit = Address::invalid();
434dff0c46cSDimitry Andric   EHScopeStack::stable_iterator cleanup;
43559d1ed5bSDimitry Andric   llvm::Instruction *cleanupDominator = nullptr;
436dff0c46cSDimitry Andric   if (CGF.needsEHCleanup(dtorKind)) {
437dff0c46cSDimitry Andric     // In principle we could tell the cleanup where we are more
438dff0c46cSDimitry Andric     // directly, but the control flow can get so varied here that it
439dff0c46cSDimitry Andric     // would actually be quite complex.  Therefore we go through an
440dff0c46cSDimitry Andric     // alloca.
4410623d748SDimitry Andric     endOfInit = CGF.CreateTempAlloca(begin->getType(), CGF.getPointerAlign(),
442dff0c46cSDimitry Andric                                      "arrayinit.endOfInit");
443dff0c46cSDimitry Andric     cleanupDominator = Builder.CreateStore(begin, endOfInit);
444dff0c46cSDimitry Andric     CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
4450623d748SDimitry Andric                                          elementAlign,
446dff0c46cSDimitry Andric                                          CGF.getDestroyer(dtorKind));
447dff0c46cSDimitry Andric     cleanup = CGF.EHStack.stable_begin();
448dff0c46cSDimitry Andric 
449dff0c46cSDimitry Andric   // Otherwise, remember that we didn't need a cleanup.
450dff0c46cSDimitry Andric   } else {
451dff0c46cSDimitry Andric     dtorKind = QualType::DK_none;
452dff0c46cSDimitry Andric   }
453dff0c46cSDimitry Andric 
454dff0c46cSDimitry Andric   llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
455dff0c46cSDimitry Andric 
456dff0c46cSDimitry Andric   // The 'current element to initialize'.  The invariants on this
457dff0c46cSDimitry Andric   // variable are complicated.  Essentially, after each iteration of
458dff0c46cSDimitry Andric   // the loop, it points to the last initialized element, except
459dff0c46cSDimitry Andric   // that it points to the beginning of the array before any
460dff0c46cSDimitry Andric   // elements have been initialized.
461dff0c46cSDimitry Andric   llvm::Value *element = begin;
462dff0c46cSDimitry Andric 
463dff0c46cSDimitry Andric   // Emit the explicit initializers.
464dff0c46cSDimitry Andric   for (uint64_t i = 0; i != NumInitElements; ++i) {
465dff0c46cSDimitry Andric     // Advance to the next element.
466dff0c46cSDimitry Andric     if (i > 0) {
467dff0c46cSDimitry Andric       element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element");
468dff0c46cSDimitry Andric 
469dff0c46cSDimitry Andric       // Tell the cleanup that it needs to destroy up to this
470dff0c46cSDimitry Andric       // element.  TODO: some of these stores can be trivially
471dff0c46cSDimitry Andric       // observed to be unnecessary.
4720623d748SDimitry Andric       if (endOfInit.isValid()) Builder.CreateStore(element, endOfInit);
473dff0c46cSDimitry Andric     }
474dff0c46cSDimitry Andric 
4750623d748SDimitry Andric     LValue elementLV =
4760623d748SDimitry Andric       CGF.MakeAddrLValue(Address(element, elementAlign), elementType);
477dff0c46cSDimitry Andric     EmitInitializationToLValue(E->getInit(i), elementLV);
478dff0c46cSDimitry Andric   }
479dff0c46cSDimitry Andric 
480dff0c46cSDimitry Andric   // Check whether there's a non-trivial array-fill expression.
481dff0c46cSDimitry Andric   Expr *filler = E->getArrayFiller();
48259d1ed5bSDimitry Andric   bool hasTrivialFiller = isTrivialFiller(filler);
483dff0c46cSDimitry Andric 
484dff0c46cSDimitry Andric   // Any remaining elements need to be zero-initialized, possibly
485dff0c46cSDimitry Andric   // using the filler expression.  We can skip this if the we're
486dff0c46cSDimitry Andric   // emitting to zeroed memory.
487dff0c46cSDimitry Andric   if (NumInitElements != NumArrayElements &&
488dff0c46cSDimitry Andric       !(Dest.isZeroed() && hasTrivialFiller &&
489dff0c46cSDimitry Andric         CGF.getTypes().isZeroInitializable(elementType))) {
490dff0c46cSDimitry Andric 
491dff0c46cSDimitry Andric     // Use an actual loop.  This is basically
492dff0c46cSDimitry Andric     //   do { *array++ = filler; } while (array != end);
493dff0c46cSDimitry Andric 
494dff0c46cSDimitry Andric     // Advance to the start of the rest of the array.
495dff0c46cSDimitry Andric     if (NumInitElements) {
496dff0c46cSDimitry Andric       element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start");
4970623d748SDimitry Andric       if (endOfInit.isValid()) Builder.CreateStore(element, endOfInit);
498dff0c46cSDimitry Andric     }
499dff0c46cSDimitry Andric 
500dff0c46cSDimitry Andric     // Compute the end of the array.
501dff0c46cSDimitry Andric     llvm::Value *end = Builder.CreateInBoundsGEP(begin,
502dff0c46cSDimitry Andric                       llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
503dff0c46cSDimitry Andric                                                  "arrayinit.end");
504dff0c46cSDimitry Andric 
505dff0c46cSDimitry Andric     llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
506dff0c46cSDimitry Andric     llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
507dff0c46cSDimitry Andric 
508dff0c46cSDimitry Andric     // Jump into the body.
509dff0c46cSDimitry Andric     CGF.EmitBlock(bodyBB);
510dff0c46cSDimitry Andric     llvm::PHINode *currentElement =
511dff0c46cSDimitry Andric       Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
512dff0c46cSDimitry Andric     currentElement->addIncoming(element, entryBB);
513dff0c46cSDimitry Andric 
514dff0c46cSDimitry Andric     // Emit the actual filler expression.
5155517e702SDimitry Andric     {
5165517e702SDimitry Andric       // C++1z [class.temporary]p5:
5175517e702SDimitry Andric       //   when a default constructor is called to initialize an element of
5185517e702SDimitry Andric       //   an array with no corresponding initializer [...] the destruction of
5195517e702SDimitry Andric       //   every temporary created in a default argument is sequenced before
5205517e702SDimitry Andric       //   the construction of the next array element, if any
5215517e702SDimitry Andric       CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
5220623d748SDimitry Andric       LValue elementLV =
5230623d748SDimitry Andric         CGF.MakeAddrLValue(Address(currentElement, elementAlign), elementType);
524dff0c46cSDimitry Andric       if (filler)
525dff0c46cSDimitry Andric         EmitInitializationToLValue(filler, elementLV);
526dff0c46cSDimitry Andric       else
527dff0c46cSDimitry Andric         EmitNullInitializationToLValue(elementLV);
5285517e702SDimitry Andric     }
529dff0c46cSDimitry Andric 
530dff0c46cSDimitry Andric     // Move on to the next element.
531dff0c46cSDimitry Andric     llvm::Value *nextElement =
532dff0c46cSDimitry Andric       Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
533dff0c46cSDimitry Andric 
534dff0c46cSDimitry Andric     // Tell the EH cleanup that we finished with the last element.
5350623d748SDimitry Andric     if (endOfInit.isValid()) Builder.CreateStore(nextElement, endOfInit);
536dff0c46cSDimitry Andric 
537dff0c46cSDimitry Andric     // Leave the loop if we're done.
538dff0c46cSDimitry Andric     llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
539dff0c46cSDimitry Andric                                              "arrayinit.done");
540dff0c46cSDimitry Andric     llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
541dff0c46cSDimitry Andric     Builder.CreateCondBr(done, endBB, bodyBB);
542dff0c46cSDimitry Andric     currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
543dff0c46cSDimitry Andric 
544dff0c46cSDimitry Andric     CGF.EmitBlock(endBB);
545dff0c46cSDimitry Andric   }
546dff0c46cSDimitry Andric 
547dff0c46cSDimitry Andric   // Leave the partial-array cleanup if we entered one.
548dff0c46cSDimitry Andric   if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator);
549f22ef01cSRoman Divacky }
550f22ef01cSRoman Divacky 
551f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
552f22ef01cSRoman Divacky //                            Visitor Methods
553f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
554f22ef01cSRoman Divacky 
55517a519f9SDimitry Andric void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
55617a519f9SDimitry Andric   Visit(E->GetTemporaryExpr());
55717a519f9SDimitry Andric }
55817a519f9SDimitry Andric 
5592754fe60SDimitry Andric void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
5607ae0e2c9SDimitry Andric   EmitFinalDestCopy(e->getType(), CGF.getOpaqueLValueMapping(e));
5612754fe60SDimitry Andric }
5622754fe60SDimitry Andric 
56317a519f9SDimitry Andric void
56417a519f9SDimitry Andric AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
565139f7f9bSDimitry Andric   if (Dest.isPotentiallyAliased() &&
566139f7f9bSDimitry Andric       E->getType().isPODType(CGF.getContext())) {
56717a519f9SDimitry Andric     // For a POD type, just emit a load of the lvalue + a copy, because our
56817a519f9SDimitry Andric     // compound literal might alias the destination.
56917a519f9SDimitry Andric     EmitAggLoadOfLValue(E);
57017a519f9SDimitry Andric     return;
57117a519f9SDimitry Andric   }
57217a519f9SDimitry Andric 
57317a519f9SDimitry Andric   AggValueSlot Slot = EnsureSlot(E->getType());
57417a519f9SDimitry Andric   CGF.EmitAggExpr(E->getInitializer(), Slot);
57517a519f9SDimitry Andric }
57617a519f9SDimitry Andric 
577139f7f9bSDimitry Andric /// Attempt to look through various unimportant expressions to find a
578139f7f9bSDimitry Andric /// cast of the given kind.
579139f7f9bSDimitry Andric static Expr *findPeephole(Expr *op, CastKind kind) {
580139f7f9bSDimitry Andric   while (true) {
581139f7f9bSDimitry Andric     op = op->IgnoreParens();
582139f7f9bSDimitry Andric     if (CastExpr *castE = dyn_cast<CastExpr>(op)) {
583139f7f9bSDimitry Andric       if (castE->getCastKind() == kind)
584139f7f9bSDimitry Andric         return castE->getSubExpr();
585139f7f9bSDimitry Andric       if (castE->getCastKind() == CK_NoOp)
586139f7f9bSDimitry Andric         continue;
587139f7f9bSDimitry Andric     }
58859d1ed5bSDimitry Andric     return nullptr;
589139f7f9bSDimitry Andric   }
590139f7f9bSDimitry Andric }
59117a519f9SDimitry Andric 
592f22ef01cSRoman Divacky void AggExprEmitter::VisitCastExpr(CastExpr *E) {
5930623d748SDimitry Andric   if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
5940623d748SDimitry Andric     CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
595f22ef01cSRoman Divacky   switch (E->getCastKind()) {
596e580952dSDimitry Andric   case CK_Dynamic: {
5973861d79fSDimitry Andric     // FIXME: Can this actually happen? We have no test coverage for it.
598f22ef01cSRoman Divacky     assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
5993861d79fSDimitry Andric     LValue LV = CGF.EmitCheckedLValue(E->getSubExpr(),
6003861d79fSDimitry Andric                                       CodeGenFunction::TCK_Load);
601f22ef01cSRoman Divacky     // FIXME: Do we also need to handle property references here?
602f22ef01cSRoman Divacky     if (LV.isSimple())
603f22ef01cSRoman Divacky       CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
604f22ef01cSRoman Divacky     else
605f22ef01cSRoman Divacky       CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
606f22ef01cSRoman Divacky 
6072754fe60SDimitry Andric     if (!Dest.isIgnored())
608f22ef01cSRoman Divacky       CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
609f22ef01cSRoman Divacky     break;
610f22ef01cSRoman Divacky   }
611f22ef01cSRoman Divacky 
612e580952dSDimitry Andric   case CK_ToUnion: {
61333956c43SDimitry Andric     // Evaluate even if the destination is ignored.
61433956c43SDimitry Andric     if (Dest.isIgnored()) {
61533956c43SDimitry Andric       CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(),
61633956c43SDimitry Andric                       /*ignoreResult=*/true);
61733956c43SDimitry Andric       break;
61833956c43SDimitry Andric     }
6193b0f4066SDimitry Andric 
620f22ef01cSRoman Divacky     // GCC union extension
621e580952dSDimitry Andric     QualType Ty = E->getSubExpr()->getType();
6220623d748SDimitry Andric     Address CastPtr =
6230623d748SDimitry Andric       Builder.CreateElementBitCast(Dest.getAddress(), CGF.ConvertType(Ty));
62417a519f9SDimitry Andric     EmitInitializationToLValue(E->getSubExpr(),
62517a519f9SDimitry Andric                                CGF.MakeAddrLValue(CastPtr, Ty));
626f22ef01cSRoman Divacky     break;
627f22ef01cSRoman Divacky   }
628f22ef01cSRoman Divacky 
629e580952dSDimitry Andric   case CK_DerivedToBase:
630e580952dSDimitry Andric   case CK_BaseToDerived:
631e580952dSDimitry Andric   case CK_UncheckedDerivedToBase: {
6326122f3e6SDimitry Andric     llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
633f22ef01cSRoman Divacky                 "should have been unpacked before we got here");
634f22ef01cSRoman Divacky   }
635f22ef01cSRoman Divacky 
636139f7f9bSDimitry Andric   case CK_NonAtomicToAtomic:
637139f7f9bSDimitry Andric   case CK_AtomicToNonAtomic: {
638139f7f9bSDimitry Andric     bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);
639139f7f9bSDimitry Andric 
640139f7f9bSDimitry Andric     // Determine the atomic and value types.
641139f7f9bSDimitry Andric     QualType atomicType = E->getSubExpr()->getType();
642139f7f9bSDimitry Andric     QualType valueType = E->getType();
643139f7f9bSDimitry Andric     if (isToAtomic) std::swap(atomicType, valueType);
644139f7f9bSDimitry Andric 
645139f7f9bSDimitry Andric     assert(atomicType->isAtomicType());
646139f7f9bSDimitry Andric     assert(CGF.getContext().hasSameUnqualifiedType(valueType,
647139f7f9bSDimitry Andric                           atomicType->castAs<AtomicType>()->getValueType()));
648139f7f9bSDimitry Andric 
649139f7f9bSDimitry Andric     // Just recurse normally if we're ignoring the result or the
650139f7f9bSDimitry Andric     // atomic type doesn't change representation.
651139f7f9bSDimitry Andric     if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {
652139f7f9bSDimitry Andric       return Visit(E->getSubExpr());
653139f7f9bSDimitry Andric     }
654139f7f9bSDimitry Andric 
655139f7f9bSDimitry Andric     CastKind peepholeTarget =
656139f7f9bSDimitry Andric       (isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic);
657139f7f9bSDimitry Andric 
658139f7f9bSDimitry Andric     // These two cases are reverses of each other; try to peephole them.
659139f7f9bSDimitry Andric     if (Expr *op = findPeephole(E->getSubExpr(), peepholeTarget)) {
660139f7f9bSDimitry Andric       assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),
661139f7f9bSDimitry Andric                                                      E->getType()) &&
662139f7f9bSDimitry Andric            "peephole significantly changed types?");
663139f7f9bSDimitry Andric       return Visit(op);
664139f7f9bSDimitry Andric     }
665139f7f9bSDimitry Andric 
666139f7f9bSDimitry Andric     // If we're converting an r-value of non-atomic type to an r-value
667f785676fSDimitry Andric     // of atomic type, just emit directly into the relevant sub-object.
668139f7f9bSDimitry Andric     if (isToAtomic) {
669f785676fSDimitry Andric       AggValueSlot valueDest = Dest;
670f785676fSDimitry Andric       if (!valueDest.isIgnored() && CGF.CGM.isPaddedAtomicType(atomicType)) {
671f785676fSDimitry Andric         // Zero-initialize.  (Strictly speaking, we only need to intialize
672f785676fSDimitry Andric         // the padding at the end, but this is simpler.)
673f785676fSDimitry Andric         if (!Dest.isZeroed())
6740623d748SDimitry Andric           CGF.EmitNullInitialization(Dest.getAddress(), atomicType);
675f785676fSDimitry Andric 
676f785676fSDimitry Andric         // Build a GEP to refer to the subobject.
6770623d748SDimitry Andric         Address valueAddr =
6780623d748SDimitry Andric             CGF.Builder.CreateStructGEP(valueDest.getAddress(), 0,
6790623d748SDimitry Andric                                         CharUnits());
680f785676fSDimitry Andric         valueDest = AggValueSlot::forAddr(valueAddr,
681f785676fSDimitry Andric                                           valueDest.getQualifiers(),
682f785676fSDimitry Andric                                           valueDest.isExternallyDestructed(),
683f785676fSDimitry Andric                                           valueDest.requiresGCollection(),
684f785676fSDimitry Andric                                           valueDest.isPotentiallyAliased(),
685f785676fSDimitry Andric                                           AggValueSlot::IsZeroed);
686f785676fSDimitry Andric       }
687f785676fSDimitry Andric 
688f785676fSDimitry Andric       CGF.EmitAggExpr(E->getSubExpr(), valueDest);
689139f7f9bSDimitry Andric       return;
690139f7f9bSDimitry Andric     }
691139f7f9bSDimitry Andric 
692139f7f9bSDimitry Andric     // Otherwise, we're converting an atomic type to a non-atomic type.
693f785676fSDimitry Andric     // Make an atomic temporary, emit into that, and then copy the value out.
694139f7f9bSDimitry Andric     AggValueSlot atomicSlot =
695139f7f9bSDimitry Andric       CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");
696139f7f9bSDimitry Andric     CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
697139f7f9bSDimitry Andric 
6980623d748SDimitry Andric     Address valueAddr =
6990623d748SDimitry Andric       Builder.CreateStructGEP(atomicSlot.getAddress(), 0, CharUnits());
700139f7f9bSDimitry Andric     RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());
701139f7f9bSDimitry Andric     return EmitFinalDestCopy(valueType, rvalue);
702139f7f9bSDimitry Andric   }
703139f7f9bSDimitry Andric 
7047ae0e2c9SDimitry Andric   case CK_LValueToRValue:
7057ae0e2c9SDimitry Andric     // If we're loading from a volatile type, force the destination
7067ae0e2c9SDimitry Andric     // into existence.
7077ae0e2c9SDimitry Andric     if (E->getSubExpr()->getType().isVolatileQualified()) {
7087ae0e2c9SDimitry Andric       EnsureDest(E->getType());
7097ae0e2c9SDimitry Andric       return Visit(E->getSubExpr());
7107ae0e2c9SDimitry Andric     }
711139f7f9bSDimitry Andric 
7127ae0e2c9SDimitry Andric     // fallthrough
7137ae0e2c9SDimitry Andric 
714e580952dSDimitry Andric   case CK_NoOp:
715e580952dSDimitry Andric   case CK_UserDefinedConversion:
716e580952dSDimitry Andric   case CK_ConstructorConversion:
717f22ef01cSRoman Divacky     assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
718f22ef01cSRoman Divacky                                                    E->getType()) &&
719f22ef01cSRoman Divacky            "Implicit cast types must be compatible");
720f22ef01cSRoman Divacky     Visit(E->getSubExpr());
721f22ef01cSRoman Divacky     break;
722f22ef01cSRoman Divacky 
723e580952dSDimitry Andric   case CK_LValueBitCast:
7242754fe60SDimitry Andric     llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
7252754fe60SDimitry Andric 
7262754fe60SDimitry Andric   case CK_Dependent:
7272754fe60SDimitry Andric   case CK_BitCast:
7282754fe60SDimitry Andric   case CK_ArrayToPointerDecay:
7292754fe60SDimitry Andric   case CK_FunctionToPointerDecay:
7302754fe60SDimitry Andric   case CK_NullToPointer:
7312754fe60SDimitry Andric   case CK_NullToMemberPointer:
7322754fe60SDimitry Andric   case CK_BaseToDerivedMemberPointer:
7332754fe60SDimitry Andric   case CK_DerivedToBaseMemberPointer:
7342754fe60SDimitry Andric   case CK_MemberPointerToBoolean:
735dff0c46cSDimitry Andric   case CK_ReinterpretMemberPointer:
7362754fe60SDimitry Andric   case CK_IntegralToPointer:
7372754fe60SDimitry Andric   case CK_PointerToIntegral:
7382754fe60SDimitry Andric   case CK_PointerToBoolean:
7392754fe60SDimitry Andric   case CK_ToVoid:
7402754fe60SDimitry Andric   case CK_VectorSplat:
7412754fe60SDimitry Andric   case CK_IntegralCast:
742444ed5c5SDimitry Andric   case CK_BooleanToSignedIntegral:
7432754fe60SDimitry Andric   case CK_IntegralToBoolean:
7442754fe60SDimitry Andric   case CK_IntegralToFloating:
7452754fe60SDimitry Andric   case CK_FloatingToIntegral:
7462754fe60SDimitry Andric   case CK_FloatingToBoolean:
7472754fe60SDimitry Andric   case CK_FloatingCast:
7486122f3e6SDimitry Andric   case CK_CPointerToObjCPointerCast:
7496122f3e6SDimitry Andric   case CK_BlockPointerToObjCPointerCast:
7502754fe60SDimitry Andric   case CK_AnyPointerToBlockPointerCast:
7512754fe60SDimitry Andric   case CK_ObjCObjectLValueCast:
7522754fe60SDimitry Andric   case CK_FloatingRealToComplex:
7532754fe60SDimitry Andric   case CK_FloatingComplexToReal:
7542754fe60SDimitry Andric   case CK_FloatingComplexToBoolean:
7552754fe60SDimitry Andric   case CK_FloatingComplexCast:
7562754fe60SDimitry Andric   case CK_FloatingComplexToIntegralComplex:
7572754fe60SDimitry Andric   case CK_IntegralRealToComplex:
7582754fe60SDimitry Andric   case CK_IntegralComplexToReal:
7592754fe60SDimitry Andric   case CK_IntegralComplexToBoolean:
7602754fe60SDimitry Andric   case CK_IntegralComplexCast:
7612754fe60SDimitry Andric   case CK_IntegralComplexToFloatingComplex:
7626122f3e6SDimitry Andric   case CK_ARCProduceObject:
7636122f3e6SDimitry Andric   case CK_ARCConsumeObject:
7646122f3e6SDimitry Andric   case CK_ARCReclaimReturnedObject:
7656122f3e6SDimitry Andric   case CK_ARCExtendBlockObject:
766dff0c46cSDimitry Andric   case CK_CopyAndAutoreleaseBlockObject:
7673861d79fSDimitry Andric   case CK_BuiltinFnToFnPtr:
768139f7f9bSDimitry Andric   case CK_ZeroToOCLEvent:
76944290647SDimitry Andric   case CK_ZeroToOCLQueue:
77059d1ed5bSDimitry Andric   case CK_AddressSpaceConversion:
77144290647SDimitry Andric   case CK_IntToOCLSampler:
7722754fe60SDimitry Andric     llvm_unreachable("cast kind invalid for aggregate types");
773f22ef01cSRoman Divacky   }
774f22ef01cSRoman Divacky }
775f22ef01cSRoman Divacky 
776f22ef01cSRoman Divacky void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
77733956c43SDimitry Andric   if (E->getCallReturnType(CGF.getContext())->isReferenceType()) {
778f22ef01cSRoman Divacky     EmitAggLoadOfLValue(E);
779f22ef01cSRoman Divacky     return;
780f22ef01cSRoman Divacky   }
781f22ef01cSRoman Divacky 
782f22ef01cSRoman Divacky   RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
7836122f3e6SDimitry Andric   EmitMoveFromReturnSlot(E, RV);
784f22ef01cSRoman Divacky }
785f22ef01cSRoman Divacky 
786f22ef01cSRoman Divacky void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
787f22ef01cSRoman Divacky   RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
7886122f3e6SDimitry Andric   EmitMoveFromReturnSlot(E, RV);
789f22ef01cSRoman Divacky }
790f22ef01cSRoman Divacky 
791f22ef01cSRoman Divacky void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
7922754fe60SDimitry Andric   CGF.EmitIgnoredExpr(E->getLHS());
7932754fe60SDimitry Andric   Visit(E->getRHS());
794f22ef01cSRoman Divacky }
795f22ef01cSRoman Divacky 
796f22ef01cSRoman Divacky void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
7972754fe60SDimitry Andric   CodeGenFunction::StmtExprEvaluation eval(CGF);
7982754fe60SDimitry Andric   CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
799f22ef01cSRoman Divacky }
800f22ef01cSRoman Divacky 
801f22ef01cSRoman Divacky void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
802e580952dSDimitry Andric   if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
803f22ef01cSRoman Divacky     VisitPointerToDataMemberBinaryOperator(E);
804f22ef01cSRoman Divacky   else
805f22ef01cSRoman Divacky     CGF.ErrorUnsupported(E, "aggregate binary expression");
806f22ef01cSRoman Divacky }
807f22ef01cSRoman Divacky 
808f22ef01cSRoman Divacky void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
809f22ef01cSRoman Divacky                                                     const BinaryOperator *E) {
810f22ef01cSRoman Divacky   LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
8117ae0e2c9SDimitry Andric   EmitFinalDestCopy(E->getType(), LV);
8127ae0e2c9SDimitry Andric }
8137ae0e2c9SDimitry Andric 
8147ae0e2c9SDimitry Andric /// Is the value of the given expression possibly a reference to or
8157ae0e2c9SDimitry Andric /// into a __block variable?
8167ae0e2c9SDimitry Andric static bool isBlockVarRef(const Expr *E) {
8177ae0e2c9SDimitry Andric   // Make sure we look through parens.
8187ae0e2c9SDimitry Andric   E = E->IgnoreParens();
8197ae0e2c9SDimitry Andric 
8207ae0e2c9SDimitry Andric   // Check for a direct reference to a __block variable.
8217ae0e2c9SDimitry Andric   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8227ae0e2c9SDimitry Andric     const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8237ae0e2c9SDimitry Andric     return (var && var->hasAttr<BlocksAttr>());
8247ae0e2c9SDimitry Andric   }
8257ae0e2c9SDimitry Andric 
8267ae0e2c9SDimitry Andric   // More complicated stuff.
8277ae0e2c9SDimitry Andric 
8287ae0e2c9SDimitry Andric   // Binary operators.
8297ae0e2c9SDimitry Andric   if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {
8307ae0e2c9SDimitry Andric     // For an assignment or pointer-to-member operation, just care
8317ae0e2c9SDimitry Andric     // about the LHS.
8327ae0e2c9SDimitry Andric     if (op->isAssignmentOp() || op->isPtrMemOp())
8337ae0e2c9SDimitry Andric       return isBlockVarRef(op->getLHS());
8347ae0e2c9SDimitry Andric 
8357ae0e2c9SDimitry Andric     // For a comma, just care about the RHS.
8367ae0e2c9SDimitry Andric     if (op->getOpcode() == BO_Comma)
8377ae0e2c9SDimitry Andric       return isBlockVarRef(op->getRHS());
8387ae0e2c9SDimitry Andric 
8397ae0e2c9SDimitry Andric     // FIXME: pointer arithmetic?
8407ae0e2c9SDimitry Andric     return false;
8417ae0e2c9SDimitry Andric 
8427ae0e2c9SDimitry Andric   // Check both sides of a conditional operator.
8437ae0e2c9SDimitry Andric   } else if (const AbstractConditionalOperator *op
8447ae0e2c9SDimitry Andric                = dyn_cast<AbstractConditionalOperator>(E)) {
8457ae0e2c9SDimitry Andric     return isBlockVarRef(op->getTrueExpr())
8467ae0e2c9SDimitry Andric         || isBlockVarRef(op->getFalseExpr());
8477ae0e2c9SDimitry Andric 
8487ae0e2c9SDimitry Andric   // OVEs are required to support BinaryConditionalOperators.
8497ae0e2c9SDimitry Andric   } else if (const OpaqueValueExpr *op
8507ae0e2c9SDimitry Andric                = dyn_cast<OpaqueValueExpr>(E)) {
8517ae0e2c9SDimitry Andric     if (const Expr *src = op->getSourceExpr())
8527ae0e2c9SDimitry Andric       return isBlockVarRef(src);
8537ae0e2c9SDimitry Andric 
8547ae0e2c9SDimitry Andric   // Casts are necessary to get things like (*(int*)&var) = foo().
8557ae0e2c9SDimitry Andric   // We don't really care about the kind of cast here, except
8567ae0e2c9SDimitry Andric   // we don't want to look through l2r casts, because it's okay
8577ae0e2c9SDimitry Andric   // to get the *value* in a __block variable.
8587ae0e2c9SDimitry Andric   } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {
8597ae0e2c9SDimitry Andric     if (cast->getCastKind() == CK_LValueToRValue)
8607ae0e2c9SDimitry Andric       return false;
8617ae0e2c9SDimitry Andric     return isBlockVarRef(cast->getSubExpr());
8627ae0e2c9SDimitry Andric 
8637ae0e2c9SDimitry Andric   // Handle unary operators.  Again, just aggressively look through
8647ae0e2c9SDimitry Andric   // it, ignoring the operation.
8657ae0e2c9SDimitry Andric   } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {
8667ae0e2c9SDimitry Andric     return isBlockVarRef(uop->getSubExpr());
8677ae0e2c9SDimitry Andric 
8687ae0e2c9SDimitry Andric   // Look into the base of a field access.
8697ae0e2c9SDimitry Andric   } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
8707ae0e2c9SDimitry Andric     return isBlockVarRef(mem->getBase());
8717ae0e2c9SDimitry Andric 
8727ae0e2c9SDimitry Andric   // Look into the base of a subscript.
8737ae0e2c9SDimitry Andric   } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {
8747ae0e2c9SDimitry Andric     return isBlockVarRef(sub->getBase());
8757ae0e2c9SDimitry Andric   }
8767ae0e2c9SDimitry Andric 
8777ae0e2c9SDimitry Andric   return false;
878f22ef01cSRoman Divacky }
879f22ef01cSRoman Divacky 
880f22ef01cSRoman Divacky void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
881f22ef01cSRoman Divacky   // For an assignment to work, the value on the right has
882f22ef01cSRoman Divacky   // to be compatible with the value on the left.
883f22ef01cSRoman Divacky   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
884f22ef01cSRoman Divacky                                                  E->getRHS()->getType())
885f22ef01cSRoman Divacky          && "Invalid assignment");
8862754fe60SDimitry Andric 
8877ae0e2c9SDimitry Andric   // If the LHS might be a __block variable, and the RHS can
8887ae0e2c9SDimitry Andric   // potentially cause a block copy, we need to evaluate the RHS first
8897ae0e2c9SDimitry Andric   // so that the assignment goes the right place.
8907ae0e2c9SDimitry Andric   // This is pretty semantically fragile.
8917ae0e2c9SDimitry Andric   if (isBlockVarRef(E->getLHS()) &&
8923b0f4066SDimitry Andric       E->getRHS()->HasSideEffects(CGF.getContext())) {
8937ae0e2c9SDimitry Andric     // Ensure that we have a destination, and evaluate the RHS into that.
8947ae0e2c9SDimitry Andric     EnsureDest(E->getRHS()->getType());
8957ae0e2c9SDimitry Andric     Visit(E->getRHS());
8967ae0e2c9SDimitry Andric 
8977ae0e2c9SDimitry Andric     // Now emit the LHS and copy into it.
8983861d79fSDimitry Andric     LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
8997ae0e2c9SDimitry Andric 
900139f7f9bSDimitry Andric     // That copy is an atomic copy if the LHS is atomic.
90133956c43SDimitry Andric     if (LHS.getType()->isAtomicType() ||
90233956c43SDimitry Andric         CGF.LValueIsSuitableForInlineAtomic(LHS)) {
903139f7f9bSDimitry Andric       CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
904139f7f9bSDimitry Andric       return;
905139f7f9bSDimitry Andric     }
906139f7f9bSDimitry Andric 
9077ae0e2c9SDimitry Andric     EmitCopy(E->getLHS()->getType(),
9087ae0e2c9SDimitry Andric              AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
9096122f3e6SDimitry Andric                                      needsGC(E->getLHS()->getType()),
9107ae0e2c9SDimitry Andric                                      AggValueSlot::IsAliased),
9117ae0e2c9SDimitry Andric              Dest);
9123b0f4066SDimitry Andric     return;
9133b0f4066SDimitry Andric   }
9143b0f4066SDimitry Andric 
915f22ef01cSRoman Divacky   LValue LHS = CGF.EmitLValue(E->getLHS());
916f22ef01cSRoman Divacky 
917139f7f9bSDimitry Andric   // If we have an atomic type, evaluate into the destination and then
918139f7f9bSDimitry Andric   // do an atomic copy.
91933956c43SDimitry Andric   if (LHS.getType()->isAtomicType() ||
92033956c43SDimitry Andric       CGF.LValueIsSuitableForInlineAtomic(LHS)) {
921139f7f9bSDimitry Andric     EnsureDest(E->getRHS()->getType());
922139f7f9bSDimitry Andric     Visit(E->getRHS());
923139f7f9bSDimitry Andric     CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
924139f7f9bSDimitry Andric     return;
925139f7f9bSDimitry Andric   }
926139f7f9bSDimitry Andric 
927f22ef01cSRoman Divacky   // Codegen the RHS so that it stores directly into the LHS.
9286122f3e6SDimitry Andric   AggValueSlot LHSSlot =
9296122f3e6SDimitry Andric     AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
9306122f3e6SDimitry Andric                             needsGC(E->getLHS()->getType()),
9316122f3e6SDimitry Andric                             AggValueSlot::IsAliased);
932139f7f9bSDimitry Andric   // A non-volatile aggregate destination might have volatile member.
933139f7f9bSDimitry Andric   if (!LHSSlot.isVolatile() &&
934139f7f9bSDimitry Andric       CGF.hasVolatileMember(E->getLHS()->getType()))
935139f7f9bSDimitry Andric     LHSSlot.setVolatile(true);
936139f7f9bSDimitry Andric 
9377ae0e2c9SDimitry Andric   CGF.EmitAggExpr(E->getRHS(), LHSSlot);
9387ae0e2c9SDimitry Andric 
9397ae0e2c9SDimitry Andric   // Copy into the destination if the assignment isn't ignored.
9407ae0e2c9SDimitry Andric   EmitFinalDestCopy(E->getType(), LHS);
941f22ef01cSRoman Divacky }
942f22ef01cSRoman Divacky 
9432754fe60SDimitry Andric void AggExprEmitter::
9442754fe60SDimitry Andric VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
945f22ef01cSRoman Divacky   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
946f22ef01cSRoman Divacky   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
947f22ef01cSRoman Divacky   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
948f22ef01cSRoman Divacky 
9492754fe60SDimitry Andric   // Bind the common expression if necessary.
9502754fe60SDimitry Andric   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
9512754fe60SDimitry Andric 
9522754fe60SDimitry Andric   CodeGenFunction::ConditionalEvaluation eval(CGF);
95333956c43SDimitry Andric   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
95433956c43SDimitry Andric                            CGF.getProfileCount(E));
955f22ef01cSRoman Divacky 
9562754fe60SDimitry Andric   // Save whether the destination's lifetime is externally managed.
9576122f3e6SDimitry Andric   bool isExternallyDestructed = Dest.isExternallyDestructed();
9582754fe60SDimitry Andric 
9592754fe60SDimitry Andric   eval.begin(CGF);
960f22ef01cSRoman Divacky   CGF.EmitBlock(LHSBlock);
96133956c43SDimitry Andric   CGF.incrementProfileCounter(E);
9622754fe60SDimitry Andric   Visit(E->getTrueExpr());
9632754fe60SDimitry Andric   eval.end(CGF);
964f22ef01cSRoman Divacky 
9652754fe60SDimitry Andric   assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
9662754fe60SDimitry Andric   CGF.Builder.CreateBr(ContBlock);
967f22ef01cSRoman Divacky 
9682754fe60SDimitry Andric   // If the result of an agg expression is unused, then the emission
9692754fe60SDimitry Andric   // of the LHS might need to create a destination slot.  That's fine
9702754fe60SDimitry Andric   // with us, and we can safely emit the RHS into the same slot, but
9716122f3e6SDimitry Andric   // we shouldn't claim that it's already being destructed.
9726122f3e6SDimitry Andric   Dest.setExternallyDestructed(isExternallyDestructed);
973f22ef01cSRoman Divacky 
9742754fe60SDimitry Andric   eval.begin(CGF);
975f22ef01cSRoman Divacky   CGF.EmitBlock(RHSBlock);
9762754fe60SDimitry Andric   Visit(E->getFalseExpr());
9772754fe60SDimitry Andric   eval.end(CGF);
978f22ef01cSRoman Divacky 
979f22ef01cSRoman Divacky   CGF.EmitBlock(ContBlock);
980f22ef01cSRoman Divacky }
981f22ef01cSRoman Divacky 
982f22ef01cSRoman Divacky void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
983f785676fSDimitry Andric   Visit(CE->getChosenSubExpr());
984f22ef01cSRoman Divacky }
985f22ef01cSRoman Divacky 
986f22ef01cSRoman Divacky void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
9870623d748SDimitry Andric   Address ArgValue = Address::invalid();
9880623d748SDimitry Andric   Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
989f22ef01cSRoman Divacky 
990e7145dcbSDimitry Andric   // If EmitVAArg fails, emit an error.
9910623d748SDimitry Andric   if (!ArgPtr.isValid()) {
992e7145dcbSDimitry Andric     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
993f22ef01cSRoman Divacky     return;
994f22ef01cSRoman Divacky   }
995f22ef01cSRoman Divacky 
9967ae0e2c9SDimitry Andric   EmitFinalDestCopy(VE->getType(), CGF.MakeAddrLValue(ArgPtr, VE->getType()));
997f22ef01cSRoman Divacky }
998f22ef01cSRoman Divacky 
999f22ef01cSRoman Divacky void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
10002754fe60SDimitry Andric   // Ensure that we have a slot, but if we already do, remember
10016122f3e6SDimitry Andric   // whether it was externally destructed.
10026122f3e6SDimitry Andric   bool wasExternallyDestructed = Dest.isExternallyDestructed();
10037ae0e2c9SDimitry Andric   EnsureDest(E->getType());
10046122f3e6SDimitry Andric 
10056122f3e6SDimitry Andric   // We're going to push a destructor if there isn't already one.
10066122f3e6SDimitry Andric   Dest.setExternallyDestructed();
1007f22ef01cSRoman Divacky 
1008f22ef01cSRoman Divacky   Visit(E->getSubExpr());
1009f22ef01cSRoman Divacky 
10106122f3e6SDimitry Andric   // Push that destructor we promised.
10116122f3e6SDimitry Andric   if (!wasExternallyDestructed)
10120623d748SDimitry Andric     CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddress());
1013f22ef01cSRoman Divacky }
1014f22ef01cSRoman Divacky 
1015f22ef01cSRoman Divacky void
1016f22ef01cSRoman Divacky AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10172754fe60SDimitry Andric   AggValueSlot Slot = EnsureSlot(E->getType());
10182754fe60SDimitry Andric   CGF.EmitCXXConstructExpr(E, Slot);
1019f22ef01cSRoman Divacky }
1020f22ef01cSRoman Divacky 
1021e7145dcbSDimitry Andric void AggExprEmitter::VisitCXXInheritedCtorInitExpr(
1022e7145dcbSDimitry Andric     const CXXInheritedCtorInitExpr *E) {
1023e7145dcbSDimitry Andric   AggValueSlot Slot = EnsureSlot(E->getType());
1024e7145dcbSDimitry Andric   CGF.EmitInheritedCXXConstructorCall(
1025e7145dcbSDimitry Andric       E->getConstructor(), E->constructsVBase(), Slot.getAddress(),
1026e7145dcbSDimitry Andric       E->inheritedFromVBase(), E);
1027e7145dcbSDimitry Andric }
1028e7145dcbSDimitry Andric 
1029dff0c46cSDimitry Andric void
1030dff0c46cSDimitry Andric AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
1031dff0c46cSDimitry Andric   AggValueSlot Slot = EnsureSlot(E->getType());
1032dff0c46cSDimitry Andric   CGF.EmitLambdaExpr(E, Slot);
1033dff0c46cSDimitry Andric }
1034dff0c46cSDimitry Andric 
10352754fe60SDimitry Andric void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
1036dff0c46cSDimitry Andric   CGF.enterFullExpression(E);
1037dff0c46cSDimitry Andric   CodeGenFunction::RunCleanupsScope cleanups(CGF);
1038dff0c46cSDimitry Andric   Visit(E->getSubExpr());
1039f22ef01cSRoman Divacky }
1040f22ef01cSRoman Divacky 
1041ffd1746dSEd Schouten void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
10422754fe60SDimitry Andric   QualType T = E->getType();
10432754fe60SDimitry Andric   AggValueSlot Slot = EnsureSlot(T);
10440623d748SDimitry Andric   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
1045f22ef01cSRoman Divacky }
1046f22ef01cSRoman Divacky 
1047f22ef01cSRoman Divacky void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
10482754fe60SDimitry Andric   QualType T = E->getType();
10492754fe60SDimitry Andric   AggValueSlot Slot = EnsureSlot(T);
10500623d748SDimitry Andric   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
10512754fe60SDimitry Andric }
1052f22ef01cSRoman Divacky 
10532754fe60SDimitry Andric /// isSimpleZero - If emitting this value will obviously just cause a store of
10542754fe60SDimitry Andric /// zero to memory, return true.  This can return false if uncertain, so it just
10552754fe60SDimitry Andric /// handles simple cases.
10562754fe60SDimitry Andric static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
10573b0f4066SDimitry Andric   E = E->IgnoreParens();
10583b0f4066SDimitry Andric 
10592754fe60SDimitry Andric   // 0
10602754fe60SDimitry Andric   if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
10612754fe60SDimitry Andric     return IL->getValue() == 0;
10622754fe60SDimitry Andric   // +0.0
10632754fe60SDimitry Andric   if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
10642754fe60SDimitry Andric     return FL->getValue().isPosZero();
10652754fe60SDimitry Andric   // int()
10662754fe60SDimitry Andric   if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
10672754fe60SDimitry Andric       CGF.getTypes().isZeroInitializable(E->getType()))
10682754fe60SDimitry Andric     return true;
10692754fe60SDimitry Andric   // (int*)0 - Null pointer expressions.
10702754fe60SDimitry Andric   if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
107144290647SDimitry Andric     return ICE->getCastKind() == CK_NullToPointer &&
107244290647SDimitry Andric         CGF.getTypes().isPointerZeroInitializable(E->getType());
10732754fe60SDimitry Andric   // '\0'
10742754fe60SDimitry Andric   if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
10752754fe60SDimitry Andric     return CL->getValue() == 0;
10762754fe60SDimitry Andric 
10772754fe60SDimitry Andric   // Otherwise, hard case: conservatively return false.
10782754fe60SDimitry Andric   return false;
1079f22ef01cSRoman Divacky }
10802754fe60SDimitry Andric 
1081f22ef01cSRoman Divacky 
1082f22ef01cSRoman Divacky void
108317a519f9SDimitry Andric AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) {
108417a519f9SDimitry Andric   QualType type = LV.getType();
1085f22ef01cSRoman Divacky   // FIXME: Ignore result?
1086f22ef01cSRoman Divacky   // FIXME: Are initializers affected by volatile?
10872754fe60SDimitry Andric   if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
10882754fe60SDimitry Andric     // Storing "i32 0" to a zero'd memory location is a noop.
1089139f7f9bSDimitry Andric     return;
1090139f7f9bSDimitry Andric   } else if (isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) {
1091139f7f9bSDimitry Andric     return EmitNullInitializationToLValue(LV);
10928f0fd8f6SDimitry Andric   } else if (isa<NoInitExpr>(E)) {
10938f0fd8f6SDimitry Andric     // Do nothing.
10948f0fd8f6SDimitry Andric     return;
109517a519f9SDimitry Andric   } else if (type->isReferenceType()) {
1096f785676fSDimitry Andric     RValue RV = CGF.EmitReferenceBindingToExpr(E);
1097139f7f9bSDimitry Andric     return CGF.EmitStoreThroughLValue(RV, LV);
1098139f7f9bSDimitry Andric   }
1099139f7f9bSDimitry Andric 
1100139f7f9bSDimitry Andric   switch (CGF.getEvaluationKind(type)) {
1101139f7f9bSDimitry Andric   case TEK_Complex:
1102139f7f9bSDimitry Andric     CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
1103139f7f9bSDimitry Andric     return;
1104139f7f9bSDimitry Andric   case TEK_Aggregate:
11056122f3e6SDimitry Andric     CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV,
11066122f3e6SDimitry Andric                                                AggValueSlot::IsDestructed,
11076122f3e6SDimitry Andric                                       AggValueSlot::DoesNotNeedGCBarriers,
11086122f3e6SDimitry Andric                                                AggValueSlot::IsNotAliased,
110917a519f9SDimitry Andric                                                Dest.isZeroed()));
1110139f7f9bSDimitry Andric     return;
1111139f7f9bSDimitry Andric   case TEK_Scalar:
1112139f7f9bSDimitry Andric     if (LV.isSimple()) {
111359d1ed5bSDimitry Andric       CGF.EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false);
1114f22ef01cSRoman Divacky     } else {
111517a519f9SDimitry Andric       CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
1116f22ef01cSRoman Divacky     }
1117139f7f9bSDimitry Andric     return;
1118139f7f9bSDimitry Andric   }
1119139f7f9bSDimitry Andric   llvm_unreachable("bad evaluation kind");
1120f22ef01cSRoman Divacky }
1121f22ef01cSRoman Divacky 
112217a519f9SDimitry Andric void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
112317a519f9SDimitry Andric   QualType type = lv.getType();
112417a519f9SDimitry Andric 
11252754fe60SDimitry Andric   // If the destination slot is already zeroed out before the aggregate is
11262754fe60SDimitry Andric   // copied into it, we don't have to emit any zeros here.
112717a519f9SDimitry Andric   if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
11282754fe60SDimitry Andric     return;
11292754fe60SDimitry Andric 
1130139f7f9bSDimitry Andric   if (CGF.hasScalarEvaluationKind(type)) {
1131139f7f9bSDimitry Andric     // For non-aggregates, we can store the appropriate null constant.
1132139f7f9bSDimitry Andric     llvm::Value *null = CGF.CGM.EmitNullConstant(type);
1133dff0c46cSDimitry Andric     // Note that the following is not equivalent to
1134dff0c46cSDimitry Andric     // EmitStoreThroughBitfieldLValue for ARC types.
1135dff0c46cSDimitry Andric     if (lv.isBitField()) {
1136dff0c46cSDimitry Andric       CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
1137dff0c46cSDimitry Andric     } else {
1138dff0c46cSDimitry Andric       assert(lv.isSimple());
1139dff0c46cSDimitry Andric       CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
1140dff0c46cSDimitry Andric     }
1141f22ef01cSRoman Divacky   } else {
1142f22ef01cSRoman Divacky     // There's a potential optimization opportunity in combining
1143f22ef01cSRoman Divacky     // memsets; that would be easy for arrays, but relatively
1144f22ef01cSRoman Divacky     // difficult for structures with the current code.
114517a519f9SDimitry Andric     CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
1146f22ef01cSRoman Divacky   }
1147f22ef01cSRoman Divacky }
1148f22ef01cSRoman Divacky 
1149f22ef01cSRoman Divacky void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
1150f22ef01cSRoman Divacky #if 0
1151f22ef01cSRoman Divacky   // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
1152f22ef01cSRoman Divacky   // (Length of globals? Chunks of zeroed-out space?).
1153f22ef01cSRoman Divacky   //
1154f22ef01cSRoman Divacky   // If we can, prefer a copy from a global; this is a lot less code for long
1155f22ef01cSRoman Divacky   // globals, and it's easier for the current optimizers to analyze.
1156f22ef01cSRoman Divacky   if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
1157f22ef01cSRoman Divacky     llvm::GlobalVariable* GV =
1158f22ef01cSRoman Divacky     new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
1159f22ef01cSRoman Divacky                              llvm::GlobalValue::InternalLinkage, C, "");
11607ae0e2c9SDimitry Andric     EmitFinalDestCopy(E->getType(), CGF.MakeAddrLValue(GV, E->getType()));
1161f22ef01cSRoman Divacky     return;
1162f22ef01cSRoman Divacky   }
1163f22ef01cSRoman Divacky #endif
11642754fe60SDimitry Andric   if (E->hadArrayRangeDesignator())
1165f22ef01cSRoman Divacky     CGF.ErrorUnsupported(E, "GNU array range designator extension");
11662754fe60SDimitry Andric 
116744290647SDimitry Andric   if (E->isTransparent())
116844290647SDimitry Andric     return Visit(E->getInit(0));
116944290647SDimitry Andric 
1170cb4dff85SDimitry Andric   AggValueSlot Dest = EnsureSlot(E->getType());
1171f785676fSDimitry Andric 
11720623d748SDimitry Andric   LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
1173f22ef01cSRoman Divacky 
1174f22ef01cSRoman Divacky   // Handle initialization of an array.
1175f22ef01cSRoman Divacky   if (E->getType()->isArrayType()) {
1176dff0c46cSDimitry Andric     QualType elementType =
1177dff0c46cSDimitry Andric         CGF.getContext().getAsArrayType(E->getType())->getElementType();
1178f22ef01cSRoman Divacky 
11790623d748SDimitry Andric     auto AType = cast<llvm::ArrayType>(Dest.getAddress().getElementType());
11800623d748SDimitry Andric     EmitArrayInit(Dest.getAddress(), AType, elementType, E);
1181f22ef01cSRoman Divacky     return;
1182f22ef01cSRoman Divacky   }
1183f22ef01cSRoman Divacky 
1184f22ef01cSRoman Divacky   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
1185f22ef01cSRoman Divacky 
1186f22ef01cSRoman Divacky   // Do struct initialization; this code just sets each individual member
1187f22ef01cSRoman Divacky   // to the approprate value.  This makes bitfield support automatic;
1188f22ef01cSRoman Divacky   // the disadvantage is that the generated code is more difficult for
1189f22ef01cSRoman Divacky   // the optimizer, especially with bitfields.
1190f22ef01cSRoman Divacky   unsigned NumInitElements = E->getNumInits();
119117a519f9SDimitry Andric   RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
1192e580952dSDimitry Andric 
1193e7145dcbSDimitry Andric   // We'll need to enter cleanup scopes in case any of the element
1194e7145dcbSDimitry Andric   // initializers throws an exception.
1195e7145dcbSDimitry Andric   SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
1196e7145dcbSDimitry Andric   llvm::Instruction *cleanupDominator = nullptr;
1197e7145dcbSDimitry Andric 
1198e7145dcbSDimitry Andric   unsigned curInitIndex = 0;
1199e7145dcbSDimitry Andric 
1200e7145dcbSDimitry Andric   // Emit initialization of base classes.
1201e7145dcbSDimitry Andric   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(record)) {
1202e7145dcbSDimitry Andric     assert(E->getNumInits() >= CXXRD->getNumBases() &&
1203e7145dcbSDimitry Andric            "missing initializer for base class");
1204e7145dcbSDimitry Andric     for (auto &Base : CXXRD->bases()) {
1205e7145dcbSDimitry Andric       assert(!Base.isVirtual() && "should not see vbases here");
1206e7145dcbSDimitry Andric       auto *BaseRD = Base.getType()->getAsCXXRecordDecl();
1207e7145dcbSDimitry Andric       Address V = CGF.GetAddressOfDirectBaseInCompleteClass(
1208e7145dcbSDimitry Andric           Dest.getAddress(), CXXRD, BaseRD,
1209e7145dcbSDimitry Andric           /*isBaseVirtual*/ false);
1210e7145dcbSDimitry Andric       AggValueSlot AggSlot =
1211e7145dcbSDimitry Andric         AggValueSlot::forAddr(V, Qualifiers(),
1212e7145dcbSDimitry Andric                               AggValueSlot::IsDestructed,
1213e7145dcbSDimitry Andric                               AggValueSlot::DoesNotNeedGCBarriers,
1214e7145dcbSDimitry Andric                               AggValueSlot::IsNotAliased);
1215e7145dcbSDimitry Andric       CGF.EmitAggExpr(E->getInit(curInitIndex++), AggSlot);
1216e7145dcbSDimitry Andric 
1217e7145dcbSDimitry Andric       if (QualType::DestructionKind dtorKind =
1218e7145dcbSDimitry Andric               Base.getType().isDestructedType()) {
1219e7145dcbSDimitry Andric         CGF.pushDestroy(dtorKind, V, Base.getType());
1220e7145dcbSDimitry Andric         cleanups.push_back(CGF.EHStack.stable_begin());
1221e7145dcbSDimitry Andric       }
1222e7145dcbSDimitry Andric     }
1223e7145dcbSDimitry Andric   }
1224e7145dcbSDimitry Andric 
1225284c1978SDimitry Andric   // Prepare a 'this' for CXXDefaultInitExprs.
12260623d748SDimitry Andric   CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddress());
1227284c1978SDimitry Andric 
122817a519f9SDimitry Andric   if (record->isUnion()) {
1229f22ef01cSRoman Divacky     // Only initialize one field of a union. The field itself is
1230f22ef01cSRoman Divacky     // specified by the initializer list.
1231f22ef01cSRoman Divacky     if (!E->getInitializedFieldInUnion()) {
1232f22ef01cSRoman Divacky       // Empty union; we have nothing to do.
1233f22ef01cSRoman Divacky 
1234f22ef01cSRoman Divacky #ifndef NDEBUG
1235f22ef01cSRoman Divacky       // Make sure that it's really an empty and not a failure of
1236f22ef01cSRoman Divacky       // semantic analysis.
123759d1ed5bSDimitry Andric       for (const auto *Field : record->fields())
1238f22ef01cSRoman Divacky         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
1239f22ef01cSRoman Divacky #endif
1240f22ef01cSRoman Divacky       return;
1241f22ef01cSRoman Divacky     }
1242f22ef01cSRoman Divacky 
1243f22ef01cSRoman Divacky     // FIXME: volatility
1244f22ef01cSRoman Divacky     FieldDecl *Field = E->getInitializedFieldInUnion();
1245f22ef01cSRoman Divacky 
1246cb4dff85SDimitry Andric     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
1247f22ef01cSRoman Divacky     if (NumInitElements) {
1248f22ef01cSRoman Divacky       // Store the initializer into the field
124917a519f9SDimitry Andric       EmitInitializationToLValue(E->getInit(0), FieldLoc);
1250f22ef01cSRoman Divacky     } else {
12512754fe60SDimitry Andric       // Default-initialize to null.
125217a519f9SDimitry Andric       EmitNullInitializationToLValue(FieldLoc);
1253f22ef01cSRoman Divacky     }
1254f22ef01cSRoman Divacky 
1255f22ef01cSRoman Divacky     return;
1256f22ef01cSRoman Divacky   }
1257f22ef01cSRoman Divacky 
1258f22ef01cSRoman Divacky   // Here we iterate over the fields; this makes it simpler to both
1259f22ef01cSRoman Divacky   // default-initialize fields and skip over unnamed fields.
126059d1ed5bSDimitry Andric   for (const auto *field : record->fields()) {
126117a519f9SDimitry Andric     // We're done once we hit the flexible array member.
126217a519f9SDimitry Andric     if (field->getType()->isIncompleteArrayType())
1263f22ef01cSRoman Divacky       break;
1264f22ef01cSRoman Divacky 
126517a519f9SDimitry Andric     // Always skip anonymous bitfields.
126617a519f9SDimitry Andric     if (field->isUnnamedBitfield())
1267f22ef01cSRoman Divacky       continue;
1268f22ef01cSRoman Divacky 
126917a519f9SDimitry Andric     // We're done if we reach the end of the explicit initializers, we
127017a519f9SDimitry Andric     // have a zeroed object, and the rest of the fields are
127117a519f9SDimitry Andric     // zero-initializable.
127217a519f9SDimitry Andric     if (curInitIndex == NumInitElements && Dest.isZeroed() &&
12732754fe60SDimitry Andric         CGF.getTypes().isZeroInitializable(E->getType()))
12742754fe60SDimitry Andric       break;
12752754fe60SDimitry Andric 
1276cb4dff85SDimitry Andric 
127759d1ed5bSDimitry Andric     LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field);
1278f22ef01cSRoman Divacky     // We never generate write-barries for initialized fields.
127917a519f9SDimitry Andric     LV.setNonGC(true);
12802754fe60SDimitry Andric 
128117a519f9SDimitry Andric     if (curInitIndex < NumInitElements) {
1282f22ef01cSRoman Divacky       // Store the initializer into the field.
128317a519f9SDimitry Andric       EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
1284f22ef01cSRoman Divacky     } else {
128520e90f04SDimitry Andric       // We're out of initializers; default-initialize to null
128617a519f9SDimitry Andric       EmitNullInitializationToLValue(LV);
128717a519f9SDimitry Andric     }
128817a519f9SDimitry Andric 
128917a519f9SDimitry Andric     // Push a destructor if necessary.
129017a519f9SDimitry Andric     // FIXME: if we have an array of structures, all explicitly
129117a519f9SDimitry Andric     // initialized, we can end up pushing a linear number of cleanups.
129217a519f9SDimitry Andric     bool pushedCleanup = false;
129317a519f9SDimitry Andric     if (QualType::DestructionKind dtorKind
129417a519f9SDimitry Andric           = field->getType().isDestructedType()) {
129517a519f9SDimitry Andric       assert(LV.isSimple());
129617a519f9SDimitry Andric       if (CGF.needsEHCleanup(dtorKind)) {
1297dff0c46cSDimitry Andric         if (!cleanupDominator)
12980623d748SDimitry Andric           cleanupDominator = CGF.Builder.CreateAlignedLoad(
12990623d748SDimitry Andric               CGF.Int8Ty,
13000623d748SDimitry Andric               llvm::Constant::getNullValue(CGF.Int8PtrTy),
13010623d748SDimitry Andric               CharUnits::One()); // placeholder
1302dff0c46cSDimitry Andric 
130317a519f9SDimitry Andric         CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
130417a519f9SDimitry Andric                         CGF.getDestroyer(dtorKind), false);
130517a519f9SDimitry Andric         cleanups.push_back(CGF.EHStack.stable_begin());
130617a519f9SDimitry Andric         pushedCleanup = true;
130717a519f9SDimitry Andric       }
1308f22ef01cSRoman Divacky     }
13092754fe60SDimitry Andric 
13102754fe60SDimitry Andric     // If the GEP didn't get used because of a dead zero init or something
13112754fe60SDimitry Andric     // else, clean it up for -O0 builds and general tidiness.
131217a519f9SDimitry Andric     if (!pushedCleanup && LV.isSimple())
13132754fe60SDimitry Andric       if (llvm::GetElementPtrInst *GEP =
13140623d748SDimitry Andric             dyn_cast<llvm::GetElementPtrInst>(LV.getPointer()))
13152754fe60SDimitry Andric         if (GEP->use_empty())
13162754fe60SDimitry Andric           GEP->eraseFromParent();
1317f22ef01cSRoman Divacky   }
131817a519f9SDimitry Andric 
131917a519f9SDimitry Andric   // Deactivate all the partial cleanups in reverse order, which
132017a519f9SDimitry Andric   // generally means popping them.
132117a519f9SDimitry Andric   for (unsigned i = cleanups.size(); i != 0; --i)
1322dff0c46cSDimitry Andric     CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
1323dff0c46cSDimitry Andric 
1324dff0c46cSDimitry Andric   // Destroy the placeholder if we made one.
1325dff0c46cSDimitry Andric   if (cleanupDominator)
1326dff0c46cSDimitry Andric     cleanupDominator->eraseFromParent();
1327f22ef01cSRoman Divacky }
1328f22ef01cSRoman Divacky 
132944290647SDimitry Andric void AggExprEmitter::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
133044290647SDimitry Andric                                             llvm::Value *outerBegin) {
133144290647SDimitry Andric   // Emit the common subexpression.
133244290647SDimitry Andric   CodeGenFunction::OpaqueValueMapping binding(CGF, E->getCommonExpr());
133344290647SDimitry Andric 
133444290647SDimitry Andric   Address destPtr = EnsureSlot(E->getType()).getAddress();
133544290647SDimitry Andric   uint64_t numElements = E->getArraySize().getZExtValue();
133644290647SDimitry Andric 
133744290647SDimitry Andric   if (!numElements)
133844290647SDimitry Andric     return;
133944290647SDimitry Andric 
134044290647SDimitry Andric   // destPtr is an array*. Construct an elementType* by drilling down a level.
134144290647SDimitry Andric   llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
134244290647SDimitry Andric   llvm::Value *indices[] = {zero, zero};
134344290647SDimitry Andric   llvm::Value *begin = Builder.CreateInBoundsGEP(destPtr.getPointer(), indices,
134444290647SDimitry Andric                                                  "arrayinit.begin");
134544290647SDimitry Andric 
134644290647SDimitry Andric   // Prepare to special-case multidimensional array initialization: we avoid
134744290647SDimitry Andric   // emitting multiple destructor loops in that case.
134844290647SDimitry Andric   if (!outerBegin)
134944290647SDimitry Andric     outerBegin = begin;
135044290647SDimitry Andric   ArrayInitLoopExpr *InnerLoop = dyn_cast<ArrayInitLoopExpr>(E->getSubExpr());
135144290647SDimitry Andric 
135244290647SDimitry Andric   QualType elementType =
135344290647SDimitry Andric       CGF.getContext().getAsArrayType(E->getType())->getElementType();
135444290647SDimitry Andric   CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
135544290647SDimitry Andric   CharUnits elementAlign =
135644290647SDimitry Andric       destPtr.getAlignment().alignmentOfArrayElement(elementSize);
135744290647SDimitry Andric 
135844290647SDimitry Andric   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
135944290647SDimitry Andric   llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
136044290647SDimitry Andric 
136144290647SDimitry Andric   // Jump into the body.
136244290647SDimitry Andric   CGF.EmitBlock(bodyBB);
136344290647SDimitry Andric   llvm::PHINode *index =
136444290647SDimitry Andric       Builder.CreatePHI(zero->getType(), 2, "arrayinit.index");
136544290647SDimitry Andric   index->addIncoming(zero, entryBB);
136644290647SDimitry Andric   llvm::Value *element = Builder.CreateInBoundsGEP(begin, index);
136744290647SDimitry Andric 
136844290647SDimitry Andric   // Prepare for a cleanup.
136944290647SDimitry Andric   QualType::DestructionKind dtorKind = elementType.isDestructedType();
137044290647SDimitry Andric   EHScopeStack::stable_iterator cleanup;
137144290647SDimitry Andric   if (CGF.needsEHCleanup(dtorKind) && !InnerLoop) {
137244290647SDimitry Andric     if (outerBegin->getType() != element->getType())
137344290647SDimitry Andric       outerBegin = Builder.CreateBitCast(outerBegin, element->getType());
137444290647SDimitry Andric     CGF.pushRegularPartialArrayCleanup(outerBegin, element, elementType,
137544290647SDimitry Andric                                        elementAlign,
137644290647SDimitry Andric                                        CGF.getDestroyer(dtorKind));
137744290647SDimitry Andric     cleanup = CGF.EHStack.stable_begin();
137844290647SDimitry Andric   } else {
137944290647SDimitry Andric     dtorKind = QualType::DK_none;
138044290647SDimitry Andric   }
138144290647SDimitry Andric 
138244290647SDimitry Andric   // Emit the actual filler expression.
138344290647SDimitry Andric   {
138444290647SDimitry Andric     // Temporaries created in an array initialization loop are destroyed
138544290647SDimitry Andric     // at the end of each iteration.
138644290647SDimitry Andric     CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
138744290647SDimitry Andric     CodeGenFunction::ArrayInitLoopExprScope Scope(CGF, index);
138844290647SDimitry Andric     LValue elementLV =
138944290647SDimitry Andric         CGF.MakeAddrLValue(Address(element, elementAlign), elementType);
139044290647SDimitry Andric 
139144290647SDimitry Andric     if (InnerLoop) {
139244290647SDimitry Andric       // If the subexpression is an ArrayInitLoopExpr, share its cleanup.
139344290647SDimitry Andric       auto elementSlot = AggValueSlot::forLValue(
139444290647SDimitry Andric           elementLV, AggValueSlot::IsDestructed,
139544290647SDimitry Andric           AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased);
139644290647SDimitry Andric       AggExprEmitter(CGF, elementSlot, false)
139744290647SDimitry Andric           .VisitArrayInitLoopExpr(InnerLoop, outerBegin);
139844290647SDimitry Andric     } else
139944290647SDimitry Andric       EmitInitializationToLValue(E->getSubExpr(), elementLV);
140044290647SDimitry Andric   }
140144290647SDimitry Andric 
140244290647SDimitry Andric   // Move on to the next element.
140344290647SDimitry Andric   llvm::Value *nextIndex = Builder.CreateNUWAdd(
140444290647SDimitry Andric       index, llvm::ConstantInt::get(CGF.SizeTy, 1), "arrayinit.next");
140544290647SDimitry Andric   index->addIncoming(nextIndex, Builder.GetInsertBlock());
140644290647SDimitry Andric 
140744290647SDimitry Andric   // Leave the loop if we're done.
140844290647SDimitry Andric   llvm::Value *done = Builder.CreateICmpEQ(
140944290647SDimitry Andric       nextIndex, llvm::ConstantInt::get(CGF.SizeTy, numElements),
141044290647SDimitry Andric       "arrayinit.done");
141144290647SDimitry Andric   llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
141244290647SDimitry Andric   Builder.CreateCondBr(done, endBB, bodyBB);
141344290647SDimitry Andric 
141444290647SDimitry Andric   CGF.EmitBlock(endBB);
141544290647SDimitry Andric 
141644290647SDimitry Andric   // Leave the partial-array cleanup if we entered one.
141744290647SDimitry Andric   if (dtorKind)
141844290647SDimitry Andric     CGF.DeactivateCleanupBlock(cleanup, index);
141944290647SDimitry Andric }
142044290647SDimitry Andric 
14218f0fd8f6SDimitry Andric void AggExprEmitter::VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) {
14228f0fd8f6SDimitry Andric   AggValueSlot Dest = EnsureSlot(E->getType());
14238f0fd8f6SDimitry Andric 
14240623d748SDimitry Andric   LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
14258f0fd8f6SDimitry Andric   EmitInitializationToLValue(E->getBase(), DestLV);
14268f0fd8f6SDimitry Andric   VisitInitListExpr(E->getUpdater());
14278f0fd8f6SDimitry Andric }
14288f0fd8f6SDimitry Andric 
1429f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
1430f22ef01cSRoman Divacky //                        Entry Points into this File
1431f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
1432f22ef01cSRoman Divacky 
14332754fe60SDimitry Andric /// GetNumNonZeroBytesInInit - Get an approximate count of the number of
14342754fe60SDimitry Andric /// non-zero bytes that will be stored when outputting the initializer for the
14352754fe60SDimitry Andric /// specified initializer expression.
14363b0f4066SDimitry Andric static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
14373b0f4066SDimitry Andric   E = E->IgnoreParens();
14382754fe60SDimitry Andric 
14392754fe60SDimitry Andric   // 0 and 0.0 won't require any non-zero stores!
14403b0f4066SDimitry Andric   if (isSimpleZero(E, CGF)) return CharUnits::Zero();
14412754fe60SDimitry Andric 
14422754fe60SDimitry Andric   // If this is an initlist expr, sum up the size of sizes of the (present)
14432754fe60SDimitry Andric   // elements.  If this is something weird, assume the whole thing is non-zero.
14442754fe60SDimitry Andric   const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
144559d1ed5bSDimitry Andric   if (!ILE || !CGF.getTypes().isZeroInitializable(ILE->getType()))
14463b0f4066SDimitry Andric     return CGF.getContext().getTypeSizeInChars(E->getType());
14472754fe60SDimitry Andric 
14482754fe60SDimitry Andric   // InitListExprs for structs have to be handled carefully.  If there are
14492754fe60SDimitry Andric   // reference members, we need to consider the size of the reference, not the
14502754fe60SDimitry Andric   // referencee.  InitListExprs for unions and arrays can't have references.
14512754fe60SDimitry Andric   if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
14522754fe60SDimitry Andric     if (!RT->isUnionType()) {
14532754fe60SDimitry Andric       RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
14543b0f4066SDimitry Andric       CharUnits NumNonZeroBytes = CharUnits::Zero();
14552754fe60SDimitry Andric 
14562754fe60SDimitry Andric       unsigned ILEElement = 0;
1457e7145dcbSDimitry Andric       if (auto *CXXRD = dyn_cast<CXXRecordDecl>(SD))
1458e7145dcbSDimitry Andric         while (ILEElement != CXXRD->getNumBases())
1459e7145dcbSDimitry Andric           NumNonZeroBytes +=
1460e7145dcbSDimitry Andric               GetNumNonZeroBytesInInit(ILE->getInit(ILEElement++), CGF);
146159d1ed5bSDimitry Andric       for (const auto *Field : SD->fields()) {
14622754fe60SDimitry Andric         // We're done once we hit the flexible array member or run out of
14632754fe60SDimitry Andric         // InitListExpr elements.
14642754fe60SDimitry Andric         if (Field->getType()->isIncompleteArrayType() ||
14652754fe60SDimitry Andric             ILEElement == ILE->getNumInits())
14662754fe60SDimitry Andric           break;
14672754fe60SDimitry Andric         if (Field->isUnnamedBitfield())
14682754fe60SDimitry Andric           continue;
14692754fe60SDimitry Andric 
14702754fe60SDimitry Andric         const Expr *E = ILE->getInit(ILEElement++);
14712754fe60SDimitry Andric 
14722754fe60SDimitry Andric         // Reference values are always non-null and have the width of a pointer.
14732754fe60SDimitry Andric         if (Field->getType()->isReferenceType())
14743b0f4066SDimitry Andric           NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
1475284c1978SDimitry Andric               CGF.getTarget().getPointerWidth(0));
14762754fe60SDimitry Andric         else
14772754fe60SDimitry Andric           NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
14782754fe60SDimitry Andric       }
14792754fe60SDimitry Andric 
14802754fe60SDimitry Andric       return NumNonZeroBytes;
14812754fe60SDimitry Andric     }
14822754fe60SDimitry Andric   }
14832754fe60SDimitry Andric 
14842754fe60SDimitry Andric 
14853b0f4066SDimitry Andric   CharUnits NumNonZeroBytes = CharUnits::Zero();
14862754fe60SDimitry Andric   for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
14872754fe60SDimitry Andric     NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
14882754fe60SDimitry Andric   return NumNonZeroBytes;
14892754fe60SDimitry Andric }
14902754fe60SDimitry Andric 
14912754fe60SDimitry Andric /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
14922754fe60SDimitry Andric /// zeros in it, emit a memset and avoid storing the individual zeros.
14932754fe60SDimitry Andric ///
14942754fe60SDimitry Andric static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
14952754fe60SDimitry Andric                                      CodeGenFunction &CGF) {
14962754fe60SDimitry Andric   // If the slot is already known to be zeroed, nothing to do.  Don't mess with
14972754fe60SDimitry Andric   // volatile stores.
14980623d748SDimitry Andric   if (Slot.isZeroed() || Slot.isVolatile() || !Slot.getAddress().isValid())
149959d1ed5bSDimitry Andric     return;
15002754fe60SDimitry Andric 
15013b0f4066SDimitry Andric   // C++ objects with a user-declared constructor don't need zero'ing.
15023861d79fSDimitry Andric   if (CGF.getLangOpts().CPlusPlus)
15033b0f4066SDimitry Andric     if (const RecordType *RT = CGF.getContext()
15043b0f4066SDimitry Andric                        .getBaseElementType(E->getType())->getAs<RecordType>()) {
15053b0f4066SDimitry Andric       const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
15063b0f4066SDimitry Andric       if (RD->hasUserDeclaredConstructor())
15073b0f4066SDimitry Andric         return;
15083b0f4066SDimitry Andric     }
15093b0f4066SDimitry Andric 
15102754fe60SDimitry Andric   // If the type is 16-bytes or smaller, prefer individual stores over memset.
15110623d748SDimitry Andric   CharUnits Size = CGF.getContext().getTypeSizeInChars(E->getType());
15120623d748SDimitry Andric   if (Size <= CharUnits::fromQuantity(16))
15132754fe60SDimitry Andric     return;
15142754fe60SDimitry Andric 
15152754fe60SDimitry Andric   // Check to see if over 3/4 of the initializer are known to be zero.  If so,
15162754fe60SDimitry Andric   // we prefer to emit memset + individual stores for the rest.
15173b0f4066SDimitry Andric   CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
15180623d748SDimitry Andric   if (NumNonZeroBytes*4 > Size)
15192754fe60SDimitry Andric     return;
15202754fe60SDimitry Andric 
15212754fe60SDimitry Andric   // Okay, it seems like a good idea to use an initial memset, emit the call.
15220623d748SDimitry Andric   llvm::Constant *SizeVal = CGF.Builder.getInt64(Size.getQuantity());
15232754fe60SDimitry Andric 
15240623d748SDimitry Andric   Address Loc = Slot.getAddress();
15250623d748SDimitry Andric   Loc = CGF.Builder.CreateElementBitCast(Loc, CGF.Int8Ty);
15260623d748SDimitry Andric   CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, false);
15272754fe60SDimitry Andric 
15282754fe60SDimitry Andric   // Tell the AggExprEmitter that the slot is known zero.
15292754fe60SDimitry Andric   Slot.setZeroed();
15302754fe60SDimitry Andric }
15312754fe60SDimitry Andric 
15322754fe60SDimitry Andric 
15332754fe60SDimitry Andric 
15342754fe60SDimitry Andric 
1535f22ef01cSRoman Divacky /// EmitAggExpr - Emit the computation of the specified expression of aggregate
1536f22ef01cSRoman Divacky /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
1537f22ef01cSRoman Divacky /// the value of the aggregate expression is not needed.  If VolatileDest is
1538f22ef01cSRoman Divacky /// true, DestPtr cannot be 0.
15397ae0e2c9SDimitry Andric void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) {
1540139f7f9bSDimitry Andric   assert(E && hasAggregateEvaluationKind(E->getType()) &&
1541f22ef01cSRoman Divacky          "Invalid aggregate expression to emit");
15420623d748SDimitry Andric   assert((Slot.getAddress().isValid() || Slot.isIgnored()) &&
15432754fe60SDimitry Andric          "slot has bits but no address");
1544f22ef01cSRoman Divacky 
15452754fe60SDimitry Andric   // Optimize the slot if possible.
15462754fe60SDimitry Andric   CheckAggExprForMemSetUse(Slot, E, *this);
15472754fe60SDimitry Andric 
154897bc6c73SDimitry Andric   AggExprEmitter(*this, Slot, Slot.isIgnored()).Visit(const_cast<Expr*>(E));
1549f22ef01cSRoman Divacky }
1550f22ef01cSRoman Divacky 
1551f22ef01cSRoman Divacky LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
1552139f7f9bSDimitry Andric   assert(hasAggregateEvaluationKind(E->getType()) && "Invalid argument!");
15530623d748SDimitry Andric   Address Temp = CreateMemTemp(E->getType());
1554e580952dSDimitry Andric   LValue LV = MakeAddrLValue(Temp, E->getType());
15556122f3e6SDimitry Andric   EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,
15566122f3e6SDimitry Andric                                          AggValueSlot::DoesNotNeedGCBarriers,
15576122f3e6SDimitry Andric                                          AggValueSlot::IsNotAliased));
1558e580952dSDimitry Andric   return LV;
1559f22ef01cSRoman Divacky }
1560f22ef01cSRoman Divacky 
15610623d748SDimitry Andric void CodeGenFunction::EmitAggregateCopy(Address DestPtr,
15620623d748SDimitry Andric                                         Address SrcPtr, QualType Ty,
15637ae0e2c9SDimitry Andric                                         bool isVolatile,
15643861d79fSDimitry Andric                                         bool isAssignment) {
1565f22ef01cSRoman Divacky   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
1566f22ef01cSRoman Divacky 
15673861d79fSDimitry Andric   if (getLangOpts().CPlusPlus) {
1568f22ef01cSRoman Divacky     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1569f22ef01cSRoman Divacky       CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
1570f22ef01cSRoman Divacky       assert((Record->hasTrivialCopyConstructor() ||
15716122f3e6SDimitry Andric               Record->hasTrivialCopyAssignment() ||
15726122f3e6SDimitry Andric               Record->hasTrivialMoveConstructor() ||
157333956c43SDimitry Andric               Record->hasTrivialMoveAssignment() ||
157433956c43SDimitry Andric               Record->isUnion()) &&
1575139f7f9bSDimitry Andric              "Trying to aggregate-copy a type without a trivial copy/move "
1576f22ef01cSRoman Divacky              "constructor or assignment operator");
1577f22ef01cSRoman Divacky       // Ignore empty classes in C++.
1578f22ef01cSRoman Divacky       if (Record->isEmpty())
1579f22ef01cSRoman Divacky         return;
1580f22ef01cSRoman Divacky     }
1581f22ef01cSRoman Divacky   }
1582f22ef01cSRoman Divacky 
1583f22ef01cSRoman Divacky   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
1584f22ef01cSRoman Divacky   // C99 6.5.16.1p3, which states "If the value being stored in an object is
1585f22ef01cSRoman Divacky   // read from another object that overlaps in anyway the storage of the first
1586f22ef01cSRoman Divacky   // object, then the overlap shall be exact and the two objects shall have
1587f22ef01cSRoman Divacky   // qualified or unqualified versions of a compatible type."
1588f22ef01cSRoman Divacky   //
1589f22ef01cSRoman Divacky   // memcpy is not defined if the source and destination pointers are exactly
1590f22ef01cSRoman Divacky   // equal, but other compilers do this optimization, and almost every memcpy
1591f22ef01cSRoman Divacky   // implementation handles this case safely.  If there is a libc that does not
1592f22ef01cSRoman Divacky   // safely handle this, we can add a target hook.
1593f22ef01cSRoman Divacky 
15940623d748SDimitry Andric   // Get data size info for this aggregate. If this is an assignment,
15950623d748SDimitry Andric   // don't copy the tail padding, because we might be assigning into a
15960623d748SDimitry Andric   // base subobject where the tail padding is claimed.  Otherwise,
15970623d748SDimitry Andric   // copying it is fine.
15983861d79fSDimitry Andric   std::pair<CharUnits, CharUnits> TypeInfo;
15993861d79fSDimitry Andric   if (isAssignment)
16003861d79fSDimitry Andric     TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);
16013861d79fSDimitry Andric   else
16023861d79fSDimitry Andric     TypeInfo = getContext().getTypeInfoInChars(Ty);
1603f22ef01cSRoman Divacky 
160433956c43SDimitry Andric   llvm::Value *SizeVal = nullptr;
160533956c43SDimitry Andric   if (TypeInfo.first.isZero()) {
160633956c43SDimitry Andric     // But note that getTypeInfo returns 0 for a VLA.
160733956c43SDimitry Andric     if (auto *VAT = dyn_cast_or_null<VariableArrayType>(
160833956c43SDimitry Andric             getContext().getAsArrayType(Ty))) {
160933956c43SDimitry Andric       QualType BaseEltTy;
161033956c43SDimitry Andric       SizeVal = emitArrayLength(VAT, BaseEltTy, DestPtr);
161133956c43SDimitry Andric       TypeInfo = getContext().getTypeInfoDataSizeInChars(BaseEltTy);
161233956c43SDimitry Andric       std::pair<CharUnits, CharUnits> LastElementTypeInfo;
161333956c43SDimitry Andric       if (!isAssignment)
161433956c43SDimitry Andric         LastElementTypeInfo = getContext().getTypeInfoInChars(BaseEltTy);
161533956c43SDimitry Andric       assert(!TypeInfo.first.isZero());
161633956c43SDimitry Andric       SizeVal = Builder.CreateNUWMul(
161733956c43SDimitry Andric           SizeVal,
161833956c43SDimitry Andric           llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()));
161933956c43SDimitry Andric       if (!isAssignment) {
162033956c43SDimitry Andric         SizeVal = Builder.CreateNUWSub(
162133956c43SDimitry Andric             SizeVal,
162233956c43SDimitry Andric             llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()));
162333956c43SDimitry Andric         SizeVal = Builder.CreateNUWAdd(
162433956c43SDimitry Andric             SizeVal, llvm::ConstantInt::get(
162533956c43SDimitry Andric                          SizeTy, LastElementTypeInfo.first.getQuantity()));
162633956c43SDimitry Andric       }
162733956c43SDimitry Andric     }
162833956c43SDimitry Andric   }
162933956c43SDimitry Andric   if (!SizeVal) {
163033956c43SDimitry Andric     SizeVal = llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity());
163133956c43SDimitry Andric   }
1632f22ef01cSRoman Divacky 
1633f22ef01cSRoman Divacky   // FIXME: If we have a volatile struct, the optimizer can remove what might
1634f22ef01cSRoman Divacky   // appear to be `extra' memory ops:
1635f22ef01cSRoman Divacky   //
1636f22ef01cSRoman Divacky   // volatile struct { int i; } a, b;
1637f22ef01cSRoman Divacky   //
1638f22ef01cSRoman Divacky   // int main() {
1639f22ef01cSRoman Divacky   //   a = b;
1640f22ef01cSRoman Divacky   //   a = b;
1641f22ef01cSRoman Divacky   // }
1642f22ef01cSRoman Divacky   //
1643f22ef01cSRoman Divacky   // we need to use a different call here.  We use isVolatile to indicate when
1644f22ef01cSRoman Divacky   // either the source or the destination is volatile.
1645f22ef01cSRoman Divacky 
16460623d748SDimitry Andric   DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
16470623d748SDimitry Andric   SrcPtr = Builder.CreateElementBitCast(SrcPtr, Int8Ty);
1648f22ef01cSRoman Divacky 
164917a519f9SDimitry Andric   // Don't do any of the memmove_collectable tests if GC isn't set.
1650dff0c46cSDimitry Andric   if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
165117a519f9SDimitry Andric     // fall through
165217a519f9SDimitry Andric   } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1653ffd1746dSEd Schouten     RecordDecl *Record = RecordTy->getDecl();
1654ffd1746dSEd Schouten     if (Record->hasObjectMember()) {
1655ffd1746dSEd Schouten       CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1656ffd1746dSEd Schouten                                                     SizeVal);
1657ffd1746dSEd Schouten       return;
1658ffd1746dSEd Schouten     }
165917a519f9SDimitry Andric   } else if (Ty->isArrayType()) {
1660ffd1746dSEd Schouten     QualType BaseType = getContext().getBaseElementType(Ty);
1661ffd1746dSEd Schouten     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
1662ffd1746dSEd Schouten       if (RecordTy->getDecl()->hasObjectMember()) {
1663ffd1746dSEd Schouten         CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1664ffd1746dSEd Schouten                                                       SizeVal);
1665ffd1746dSEd Schouten         return;
1666ffd1746dSEd Schouten       }
1667ffd1746dSEd Schouten     }
1668ffd1746dSEd Schouten   }
1669ffd1746dSEd Schouten 
16700623d748SDimitry Andric   auto Inst = Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, isVolatile);
16710623d748SDimitry Andric 
16723861d79fSDimitry Andric   // Determine the metadata to describe the position of any padding in this
16733861d79fSDimitry Andric   // memcpy, as well as the TBAA tags for the members of the struct, in case
16743861d79fSDimitry Andric   // the optimizer wishes to expand it in to scalar memory operations.
16750623d748SDimitry Andric   if (llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty))
16760623d748SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa_struct, TBAAStructTag);
1677dff0c46cSDimitry Andric }
1678