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 
5297bc6c73SDimitry Andric     return ReturnValueSlot(Dest.getAddr(), Dest.isVolatile(), IsResultUnused);
532754fe60SDimitry Andric   }
542754fe60SDimitry Andric 
552754fe60SDimitry Andric   AggValueSlot EnsureSlot(QualType T) {
562754fe60SDimitry Andric     if (!Dest.isIgnored()) return Dest;
572754fe60SDimitry Andric     return CGF.CreateAggTemp(T, "agg.tmp.ensured");
58f22ef01cSRoman Divacky   }
597ae0e2c9SDimitry Andric   void EnsureDest(QualType T) {
607ae0e2c9SDimitry Andric     if (!Dest.isIgnored()) return;
617ae0e2c9SDimitry Andric     Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured");
627ae0e2c9SDimitry Andric   }
63f22ef01cSRoman Divacky 
64f22ef01cSRoman Divacky public:
6597bc6c73SDimitry Andric   AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest, bool IsResultUnused)
6697bc6c73SDimitry Andric     : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
6797bc6c73SDimitry Andric     IsResultUnused(IsResultUnused) { }
68f22ef01cSRoman Divacky 
69f22ef01cSRoman Divacky   //===--------------------------------------------------------------------===//
70f22ef01cSRoman Divacky   //                               Utilities
71f22ef01cSRoman Divacky   //===--------------------------------------------------------------------===//
72f22ef01cSRoman Divacky 
73f22ef01cSRoman Divacky   /// EmitAggLoadOfLValue - Given an expression with aggregate type that
74f22ef01cSRoman Divacky   /// represents a value lvalue, this method emits the address of the lvalue,
75f22ef01cSRoman Divacky   /// then loads the result into DestPtr.
76f22ef01cSRoman Divacky   void EmitAggLoadOfLValue(const Expr *E);
77f22ef01cSRoman Divacky 
78f22ef01cSRoman Divacky   /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
797ae0e2c9SDimitry Andric   void EmitFinalDestCopy(QualType type, const LValue &src);
807ae0e2c9SDimitry Andric   void EmitFinalDestCopy(QualType type, RValue src,
817ae0e2c9SDimitry Andric                          CharUnits srcAlignment = CharUnits::Zero());
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 
87dff0c46cSDimitry Andric   void EmitArrayInit(llvm::Value *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   }
114f22ef01cSRoman Divacky   void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
11517a519f9SDimitry Andric   void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
11617a519f9SDimitry Andric     return Visit(E->getReplacement());
11717a519f9SDimitry Andric   }
118f22ef01cSRoman Divacky 
119f22ef01cSRoman Divacky   // l-values.
120dff0c46cSDimitry Andric   void VisitDeclRefExpr(DeclRefExpr *E) {
121dff0c46cSDimitry Andric     // For aggregates, we should always be able to emit the variable
122dff0c46cSDimitry Andric     // as an l-value unless it's a reference.  This is due to the fact
123dff0c46cSDimitry Andric     // that we can't actually ever see a normal l2r conversion on an
124dff0c46cSDimitry Andric     // aggregate in C++, and in C there's no language standard
125dff0c46cSDimitry Andric     // actively preventing us from listing variables in the captures
126dff0c46cSDimitry Andric     // list of a block.
127dff0c46cSDimitry Andric     if (E->getDecl()->getType()->isReferenceType()) {
128dff0c46cSDimitry Andric       if (CodeGenFunction::ConstantEmission result
129dff0c46cSDimitry Andric             = CGF.tryEmitAsConstant(E)) {
1307ae0e2c9SDimitry Andric         EmitFinalDestCopy(E->getType(), result.getReferenceLValue(CGF, E));
131dff0c46cSDimitry Andric         return;
132dff0c46cSDimitry Andric       }
133dff0c46cSDimitry Andric     }
134dff0c46cSDimitry Andric 
135dff0c46cSDimitry Andric     EmitAggLoadOfLValue(E);
136dff0c46cSDimitry Andric   }
137dff0c46cSDimitry Andric 
138f22ef01cSRoman Divacky   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
139f22ef01cSRoman Divacky   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
140f22ef01cSRoman Divacky   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
14117a519f9SDimitry Andric   void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
142f22ef01cSRoman Divacky   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
143f22ef01cSRoman Divacky     EmitAggLoadOfLValue(E);
144f22ef01cSRoman Divacky   }
145f22ef01cSRoman Divacky   void VisitPredefinedExpr(const PredefinedExpr *E) {
146f22ef01cSRoman Divacky     EmitAggLoadOfLValue(E);
147f22ef01cSRoman Divacky   }
148f22ef01cSRoman Divacky 
149f22ef01cSRoman Divacky   // Operators.
150f22ef01cSRoman Divacky   void VisitCastExpr(CastExpr *E);
151f22ef01cSRoman Divacky   void VisitCallExpr(const CallExpr *E);
152f22ef01cSRoman Divacky   void VisitStmtExpr(const StmtExpr *E);
153f22ef01cSRoman Divacky   void VisitBinaryOperator(const BinaryOperator *BO);
154f22ef01cSRoman Divacky   void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
155f22ef01cSRoman Divacky   void VisitBinAssign(const BinaryOperator *E);
156f22ef01cSRoman Divacky   void VisitBinComma(const BinaryOperator *E);
157f22ef01cSRoman Divacky 
158f22ef01cSRoman Divacky   void VisitObjCMessageExpr(ObjCMessageExpr *E);
159f22ef01cSRoman Divacky   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
160f22ef01cSRoman Divacky     EmitAggLoadOfLValue(E);
161f22ef01cSRoman Divacky   }
162f22ef01cSRoman Divacky 
1632754fe60SDimitry Andric   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
164f22ef01cSRoman Divacky   void VisitChooseExpr(const ChooseExpr *CE);
165f22ef01cSRoman Divacky   void VisitInitListExpr(InitListExpr *E);
166f22ef01cSRoman Divacky   void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
167f22ef01cSRoman Divacky   void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
168f22ef01cSRoman Divacky     Visit(DAE->getExpr());
169f22ef01cSRoman Divacky   }
170284c1978SDimitry Andric   void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
171284c1978SDimitry Andric     CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
172284c1978SDimitry Andric     Visit(DIE->getExpr());
173284c1978SDimitry Andric   }
174f22ef01cSRoman Divacky   void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
175f22ef01cSRoman Divacky   void VisitCXXConstructExpr(const CXXConstructExpr *E);
176dff0c46cSDimitry Andric   void VisitLambdaExpr(LambdaExpr *E);
177f785676fSDimitry Andric   void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
1782754fe60SDimitry Andric   void VisitExprWithCleanups(ExprWithCleanups *E);
179ffd1746dSEd Schouten   void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
180f22ef01cSRoman Divacky   void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
18117a519f9SDimitry Andric   void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
1822754fe60SDimitry Andric   void VisitOpaqueValueExpr(OpaqueValueExpr *E);
1832754fe60SDimitry Andric 
184dff0c46cSDimitry Andric   void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
185dff0c46cSDimitry Andric     if (E->isGLValue()) {
186dff0c46cSDimitry Andric       LValue LV = CGF.EmitPseudoObjectLValue(E);
1877ae0e2c9SDimitry Andric       return EmitFinalDestCopy(E->getType(), LV);
188dff0c46cSDimitry Andric     }
189dff0c46cSDimitry Andric 
190dff0c46cSDimitry Andric     CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
191dff0c46cSDimitry Andric   }
192dff0c46cSDimitry Andric 
193f22ef01cSRoman Divacky   void VisitVAArgExpr(VAArgExpr *E);
194f22ef01cSRoman Divacky 
19517a519f9SDimitry Andric   void EmitInitializationToLValue(Expr *E, LValue Address);
19617a519f9SDimitry Andric   void EmitNullInitializationToLValue(LValue Address);
197f22ef01cSRoman Divacky   //  case Expr::ChooseExprClass:
198f22ef01cSRoman Divacky   void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
1996122f3e6SDimitry Andric   void VisitAtomicExpr(AtomicExpr *E) {
2006122f3e6SDimitry Andric     CGF.EmitAtomicExpr(E, EnsureSlot(E->getType()).getAddr());
2016122f3e6SDimitry Andric   }
202f22ef01cSRoman Divacky };
203f22ef01cSRoman Divacky }  // end anonymous namespace.
204f22ef01cSRoman Divacky 
205f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
206f22ef01cSRoman Divacky //                                Utilities
207f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
208f22ef01cSRoman Divacky 
209f22ef01cSRoman Divacky /// EmitAggLoadOfLValue - Given an expression with aggregate type that
210f22ef01cSRoman Divacky /// represents a value lvalue, this method emits the address of the lvalue,
211f22ef01cSRoman Divacky /// then loads the result into DestPtr.
212f22ef01cSRoman Divacky void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
213f22ef01cSRoman Divacky   LValue LV = CGF.EmitLValue(E);
214139f7f9bSDimitry Andric 
215139f7f9bSDimitry Andric   // If the type of the l-value is atomic, then do an atomic load.
21633956c43SDimitry Andric   if (LV.getType()->isAtomicType() || CGF.LValueIsSuitableForInlineAtomic(LV)) {
217f785676fSDimitry Andric     CGF.EmitAtomicLoad(LV, E->getExprLoc(), Dest);
218139f7f9bSDimitry Andric     return;
219139f7f9bSDimitry Andric   }
220139f7f9bSDimitry Andric 
2217ae0e2c9SDimitry Andric   EmitFinalDestCopy(E->getType(), LV);
222f22ef01cSRoman Divacky }
223f22ef01cSRoman Divacky 
224f22ef01cSRoman Divacky /// \brief True if the given aggregate type requires special GC API calls.
225f22ef01cSRoman Divacky bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
226f22ef01cSRoman Divacky   // Only record types have members that might require garbage collection.
227f22ef01cSRoman Divacky   const RecordType *RecordTy = T->getAs<RecordType>();
228f22ef01cSRoman Divacky   if (!RecordTy) return false;
229f22ef01cSRoman Divacky 
230f22ef01cSRoman Divacky   // Don't mess with non-trivial C++ types.
231f22ef01cSRoman Divacky   RecordDecl *Record = RecordTy->getDecl();
232f22ef01cSRoman Divacky   if (isa<CXXRecordDecl>(Record) &&
233139f7f9bSDimitry Andric       (cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() ||
234f22ef01cSRoman Divacky        !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
235f22ef01cSRoman Divacky     return false;
236f22ef01cSRoman Divacky 
237f22ef01cSRoman Divacky   // Check whether the type has an object member.
238f22ef01cSRoman Divacky   return Record->hasObjectMember();
239f22ef01cSRoman Divacky }
240f22ef01cSRoman Divacky 
2416122f3e6SDimitry Andric /// \brief Perform the final move to DestPtr if for some reason
2426122f3e6SDimitry Andric /// getReturnValueSlot() didn't use it directly.
243f22ef01cSRoman Divacky ///
244f22ef01cSRoman Divacky /// The idea is that you do something like this:
245f22ef01cSRoman Divacky ///   RValue Result = EmitSomething(..., getReturnValueSlot());
2466122f3e6SDimitry Andric ///   EmitMoveFromReturnSlot(E, Result);
2476122f3e6SDimitry Andric ///
2486122f3e6SDimitry Andric /// If nothing interferes, this will cause the result to be emitted
2496122f3e6SDimitry Andric /// directly into the return value slot.  Otherwise, a final move
2506122f3e6SDimitry Andric /// will be performed.
2517ae0e2c9SDimitry Andric void AggExprEmitter::EmitMoveFromReturnSlot(const Expr *E, RValue src) {
2526122f3e6SDimitry Andric   if (shouldUseDestForReturnSlot()) {
2536122f3e6SDimitry Andric     // Logically, Dest.getAddr() should equal Src.getAggregateAddr().
2546122f3e6SDimitry Andric     // The possibility of undef rvalues complicates that a lot,
2556122f3e6SDimitry Andric     // though, so we can't really assert.
2566122f3e6SDimitry Andric     return;
257ffd1746dSEd Schouten   }
2586122f3e6SDimitry Andric 
2597ae0e2c9SDimitry Andric   // Otherwise, copy from there to the destination.
2607ae0e2c9SDimitry Andric   assert(Dest.getAddr() != src.getAggregateAddr());
2617ae0e2c9SDimitry Andric   std::pair<CharUnits, CharUnits> typeInfo =
262cb4dff85SDimitry Andric     CGF.getContext().getTypeInfoInChars(E->getType());
2637ae0e2c9SDimitry Andric   EmitFinalDestCopy(E->getType(), src, typeInfo.second);
264f22ef01cSRoman Divacky }
265f22ef01cSRoman Divacky 
266f22ef01cSRoman Divacky /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
2677ae0e2c9SDimitry Andric void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src,
2687ae0e2c9SDimitry Andric                                        CharUnits srcAlign) {
2697ae0e2c9SDimitry Andric   assert(src.isAggregate() && "value must be aggregate value!");
2707ae0e2c9SDimitry Andric   LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddr(), type, srcAlign);
2717ae0e2c9SDimitry Andric   EmitFinalDestCopy(type, srcLV);
2727ae0e2c9SDimitry Andric }
273f22ef01cSRoman Divacky 
2747ae0e2c9SDimitry Andric /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
2757ae0e2c9SDimitry Andric void AggExprEmitter::EmitFinalDestCopy(QualType type, const LValue &src) {
2762754fe60SDimitry Andric   // If Dest is ignored, then we're evaluating an aggregate expression
2777ae0e2c9SDimitry Andric   // in a context that doesn't care about the result.  Note that loads
2787ae0e2c9SDimitry Andric   // from volatile l-values force the existence of a non-ignored
2797ae0e2c9SDimitry Andric   // destination.
2807ae0e2c9SDimitry Andric   if (Dest.isIgnored())
281f22ef01cSRoman Divacky     return;
282e580952dSDimitry Andric 
2837ae0e2c9SDimitry Andric   AggValueSlot srcAgg =
2847ae0e2c9SDimitry Andric     AggValueSlot::forLValue(src, AggValueSlot::IsDestructed,
2857ae0e2c9SDimitry Andric                             needsGC(type), AggValueSlot::IsAliased);
2867ae0e2c9SDimitry Andric   EmitCopy(type, Dest, srcAgg);
287f22ef01cSRoman Divacky }
288f22ef01cSRoman Divacky 
2897ae0e2c9SDimitry Andric /// Perform a copy from the source into the destination.
2907ae0e2c9SDimitry Andric ///
2917ae0e2c9SDimitry Andric /// \param type - the type of the aggregate being copied; qualifiers are
2927ae0e2c9SDimitry Andric ///   ignored
2937ae0e2c9SDimitry Andric void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,
2947ae0e2c9SDimitry Andric                               const AggValueSlot &src) {
2957ae0e2c9SDimitry Andric   if (dest.requiresGCollection()) {
2967ae0e2c9SDimitry Andric     CharUnits sz = CGF.getContext().getTypeSizeInChars(type);
2977ae0e2c9SDimitry Andric     llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());
298f22ef01cSRoman Divacky     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
2997ae0e2c9SDimitry Andric                                                       dest.getAddr(),
3007ae0e2c9SDimitry Andric                                                       src.getAddr(),
3017ae0e2c9SDimitry Andric                                                       size);
302f22ef01cSRoman Divacky     return;
303f22ef01cSRoman Divacky   }
3047ae0e2c9SDimitry Andric 
305f22ef01cSRoman Divacky   // If the result of the assignment is used, copy the LHS there also.
3067ae0e2c9SDimitry Andric   // It's volatile if either side is.  Use the minimum alignment of
3077ae0e2c9SDimitry Andric   // the two sides.
3087ae0e2c9SDimitry Andric   CGF.EmitAggregateCopy(dest.getAddr(), src.getAddr(), type,
3097ae0e2c9SDimitry Andric                         dest.isVolatile() || src.isVolatile(),
3107ae0e2c9SDimitry Andric                         std::min(dest.getAlignment(), src.getAlignment()));
311dff0c46cSDimitry Andric }
312dff0c46cSDimitry Andric 
313dff0c46cSDimitry Andric /// \brief Emit the initializer for a std::initializer_list initialized with a
314dff0c46cSDimitry Andric /// real initializer list.
315f785676fSDimitry Andric void
316f785676fSDimitry Andric AggExprEmitter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
317f785676fSDimitry Andric   // Emit an array containing the elements.  The array is externally destructed
318f785676fSDimitry Andric   // if the std::initializer_list object is.
319f785676fSDimitry Andric   ASTContext &Ctx = CGF.getContext();
320f785676fSDimitry Andric   LValue Array = CGF.EmitLValue(E->getSubExpr());
321f785676fSDimitry Andric   assert(Array.isSimple() && "initializer_list array not a simple lvalue");
322f785676fSDimitry Andric   llvm::Value *ArrayPtr = Array.getAddress();
323dff0c46cSDimitry Andric 
324f785676fSDimitry Andric   const ConstantArrayType *ArrayType =
325f785676fSDimitry Andric       Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
326f785676fSDimitry Andric   assert(ArrayType && "std::initializer_list constructed from non-array");
327dff0c46cSDimitry Andric 
328f785676fSDimitry Andric   // FIXME: Perform the checks on the field types in SemaInit.
329f785676fSDimitry Andric   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
330f785676fSDimitry Andric   RecordDecl::field_iterator Field = Record->field_begin();
331f785676fSDimitry Andric   if (Field == Record->field_end()) {
332f785676fSDimitry Andric     CGF.ErrorUnsupported(E, "weird std::initializer_list");
333dff0c46cSDimitry Andric     return;
334dff0c46cSDimitry Andric   }
335dff0c46cSDimitry Andric 
336dff0c46cSDimitry Andric   // Start pointer.
337f785676fSDimitry Andric   if (!Field->getType()->isPointerType() ||
338f785676fSDimitry Andric       !Ctx.hasSameType(Field->getType()->getPointeeType(),
339f785676fSDimitry Andric                        ArrayType->getElementType())) {
340f785676fSDimitry Andric     CGF.ErrorUnsupported(E, "weird std::initializer_list");
341dff0c46cSDimitry Andric     return;
342dff0c46cSDimitry Andric   }
343dff0c46cSDimitry Andric 
344f785676fSDimitry Andric   AggValueSlot Dest = EnsureSlot(E->getType());
345f785676fSDimitry Andric   LValue DestLV = CGF.MakeAddrLValue(Dest.getAddr(), E->getType(),
346f785676fSDimitry Andric                                      Dest.getAlignment());
347f785676fSDimitry Andric   LValue Start = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
348f785676fSDimitry Andric   llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0);
349f785676fSDimitry Andric   llvm::Value *IdxStart[] = { Zero, Zero };
350f785676fSDimitry Andric   llvm::Value *ArrayStart =
351f785676fSDimitry Andric       Builder.CreateInBoundsGEP(ArrayPtr, IdxStart, "arraystart");
352f785676fSDimitry Andric   CGF.EmitStoreThroughLValue(RValue::get(ArrayStart), Start);
353f785676fSDimitry Andric   ++Field;
354f785676fSDimitry Andric 
355f785676fSDimitry Andric   if (Field == Record->field_end()) {
356f785676fSDimitry Andric     CGF.ErrorUnsupported(E, "weird std::initializer_list");
357dff0c46cSDimitry Andric     return;
358dff0c46cSDimitry Andric   }
359f785676fSDimitry Andric 
360f785676fSDimitry Andric   llvm::Value *Size = Builder.getInt(ArrayType->getSize());
361f785676fSDimitry Andric   LValue EndOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
362f785676fSDimitry Andric   if (Field->getType()->isPointerType() &&
363f785676fSDimitry Andric       Ctx.hasSameType(Field->getType()->getPointeeType(),
364f785676fSDimitry Andric                       ArrayType->getElementType())) {
365dff0c46cSDimitry Andric     // End pointer.
366f785676fSDimitry Andric     llvm::Value *IdxEnd[] = { Zero, Size };
367f785676fSDimitry Andric     llvm::Value *ArrayEnd =
368f785676fSDimitry Andric         Builder.CreateInBoundsGEP(ArrayPtr, IdxEnd, "arrayend");
369f785676fSDimitry Andric     CGF.EmitStoreThroughLValue(RValue::get(ArrayEnd), EndOrLength);
370f785676fSDimitry Andric   } else if (Ctx.hasSameType(Field->getType(), Ctx.getSizeType())) {
371dff0c46cSDimitry Andric     // Length.
372f785676fSDimitry Andric     CGF.EmitStoreThroughLValue(RValue::get(Size), EndOrLength);
373dff0c46cSDimitry Andric   } else {
374f785676fSDimitry Andric     CGF.ErrorUnsupported(E, "weird std::initializer_list");
375dff0c46cSDimitry Andric     return;
376dff0c46cSDimitry Andric   }
377dff0c46cSDimitry Andric }
378dff0c46cSDimitry Andric 
37959d1ed5bSDimitry Andric /// \brief Determine if E is a trivial array filler, that is, one that is
38059d1ed5bSDimitry Andric /// equivalent to zero-initialization.
38159d1ed5bSDimitry Andric static bool isTrivialFiller(Expr *E) {
38259d1ed5bSDimitry Andric   if (!E)
38359d1ed5bSDimitry Andric     return true;
38459d1ed5bSDimitry Andric 
38559d1ed5bSDimitry Andric   if (isa<ImplicitValueInitExpr>(E))
38659d1ed5bSDimitry Andric     return true;
38759d1ed5bSDimitry Andric 
38859d1ed5bSDimitry Andric   if (auto *ILE = dyn_cast<InitListExpr>(E)) {
38959d1ed5bSDimitry Andric     if (ILE->getNumInits())
39059d1ed5bSDimitry Andric       return false;
39159d1ed5bSDimitry Andric     return isTrivialFiller(ILE->getArrayFiller());
39259d1ed5bSDimitry Andric   }
39359d1ed5bSDimitry Andric 
39459d1ed5bSDimitry Andric   if (auto *Cons = dyn_cast_or_null<CXXConstructExpr>(E))
39559d1ed5bSDimitry Andric     return Cons->getConstructor()->isDefaultConstructor() &&
39659d1ed5bSDimitry Andric            Cons->getConstructor()->isTrivial();
39759d1ed5bSDimitry Andric 
39859d1ed5bSDimitry Andric   // FIXME: Are there other cases where we can avoid emitting an initializer?
39959d1ed5bSDimitry Andric   return false;
40059d1ed5bSDimitry Andric }
40159d1ed5bSDimitry Andric 
402dff0c46cSDimitry Andric /// \brief Emit initialization of an array from an initializer list.
403dff0c46cSDimitry Andric void AggExprEmitter::EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
404dff0c46cSDimitry Andric                                    QualType elementType, InitListExpr *E) {
405dff0c46cSDimitry Andric   uint64_t NumInitElements = E->getNumInits();
406dff0c46cSDimitry Andric 
407dff0c46cSDimitry Andric   uint64_t NumArrayElements = AType->getNumElements();
408dff0c46cSDimitry Andric   assert(NumInitElements <= NumArrayElements);
409dff0c46cSDimitry Andric 
410dff0c46cSDimitry Andric   // DestPtr is an array*.  Construct an elementType* by drilling
411dff0c46cSDimitry Andric   // down a level.
412dff0c46cSDimitry Andric   llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
413dff0c46cSDimitry Andric   llvm::Value *indices[] = { zero, zero };
414dff0c46cSDimitry Andric   llvm::Value *begin =
415dff0c46cSDimitry Andric     Builder.CreateInBoundsGEP(DestPtr, indices, "arrayinit.begin");
416dff0c46cSDimitry Andric 
417dff0c46cSDimitry Andric   // Exception safety requires us to destroy all the
418dff0c46cSDimitry Andric   // already-constructed members if an initializer throws.
419dff0c46cSDimitry Andric   // For that, we'll need an EH cleanup.
420dff0c46cSDimitry Andric   QualType::DestructionKind dtorKind = elementType.isDestructedType();
42159d1ed5bSDimitry Andric   llvm::AllocaInst *endOfInit = nullptr;
422dff0c46cSDimitry Andric   EHScopeStack::stable_iterator cleanup;
42359d1ed5bSDimitry Andric   llvm::Instruction *cleanupDominator = nullptr;
424dff0c46cSDimitry Andric   if (CGF.needsEHCleanup(dtorKind)) {
425dff0c46cSDimitry Andric     // In principle we could tell the cleanup where we are more
426dff0c46cSDimitry Andric     // directly, but the control flow can get so varied here that it
427dff0c46cSDimitry Andric     // would actually be quite complex.  Therefore we go through an
428dff0c46cSDimitry Andric     // alloca.
429dff0c46cSDimitry Andric     endOfInit = CGF.CreateTempAlloca(begin->getType(),
430dff0c46cSDimitry Andric                                      "arrayinit.endOfInit");
431dff0c46cSDimitry Andric     cleanupDominator = Builder.CreateStore(begin, endOfInit);
432dff0c46cSDimitry Andric     CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
433dff0c46cSDimitry Andric                                          CGF.getDestroyer(dtorKind));
434dff0c46cSDimitry Andric     cleanup = CGF.EHStack.stable_begin();
435dff0c46cSDimitry Andric 
436dff0c46cSDimitry Andric   // Otherwise, remember that we didn't need a cleanup.
437dff0c46cSDimitry Andric   } else {
438dff0c46cSDimitry Andric     dtorKind = QualType::DK_none;
439dff0c46cSDimitry Andric   }
440dff0c46cSDimitry Andric 
441dff0c46cSDimitry Andric   llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
442dff0c46cSDimitry Andric 
443dff0c46cSDimitry Andric   // The 'current element to initialize'.  The invariants on this
444dff0c46cSDimitry Andric   // variable are complicated.  Essentially, after each iteration of
445dff0c46cSDimitry Andric   // the loop, it points to the last initialized element, except
446dff0c46cSDimitry Andric   // that it points to the beginning of the array before any
447dff0c46cSDimitry Andric   // elements have been initialized.
448dff0c46cSDimitry Andric   llvm::Value *element = begin;
449dff0c46cSDimitry Andric 
450dff0c46cSDimitry Andric   // Emit the explicit initializers.
451dff0c46cSDimitry Andric   for (uint64_t i = 0; i != NumInitElements; ++i) {
452dff0c46cSDimitry Andric     // Advance to the next element.
453dff0c46cSDimitry Andric     if (i > 0) {
454dff0c46cSDimitry Andric       element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element");
455dff0c46cSDimitry Andric 
456dff0c46cSDimitry Andric       // Tell the cleanup that it needs to destroy up to this
457dff0c46cSDimitry Andric       // element.  TODO: some of these stores can be trivially
458dff0c46cSDimitry Andric       // observed to be unnecessary.
459dff0c46cSDimitry Andric       if (endOfInit) Builder.CreateStore(element, endOfInit);
460dff0c46cSDimitry Andric     }
461dff0c46cSDimitry Andric 
462dff0c46cSDimitry Andric     LValue elementLV = CGF.MakeAddrLValue(element, elementType);
463dff0c46cSDimitry Andric     EmitInitializationToLValue(E->getInit(i), elementLV);
464dff0c46cSDimitry Andric   }
465dff0c46cSDimitry Andric 
466dff0c46cSDimitry Andric   // Check whether there's a non-trivial array-fill expression.
467dff0c46cSDimitry Andric   Expr *filler = E->getArrayFiller();
46859d1ed5bSDimitry Andric   bool hasTrivialFiller = isTrivialFiller(filler);
469dff0c46cSDimitry Andric 
470dff0c46cSDimitry Andric   // Any remaining elements need to be zero-initialized, possibly
471dff0c46cSDimitry Andric   // using the filler expression.  We can skip this if the we're
472dff0c46cSDimitry Andric   // emitting to zeroed memory.
473dff0c46cSDimitry Andric   if (NumInitElements != NumArrayElements &&
474dff0c46cSDimitry Andric       !(Dest.isZeroed() && hasTrivialFiller &&
475dff0c46cSDimitry Andric         CGF.getTypes().isZeroInitializable(elementType))) {
476dff0c46cSDimitry Andric 
477dff0c46cSDimitry Andric     // Use an actual loop.  This is basically
478dff0c46cSDimitry Andric     //   do { *array++ = filler; } while (array != end);
479dff0c46cSDimitry Andric 
480dff0c46cSDimitry Andric     // Advance to the start of the rest of the array.
481dff0c46cSDimitry Andric     if (NumInitElements) {
482dff0c46cSDimitry Andric       element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start");
483dff0c46cSDimitry Andric       if (endOfInit) Builder.CreateStore(element, endOfInit);
484dff0c46cSDimitry Andric     }
485dff0c46cSDimitry Andric 
486dff0c46cSDimitry Andric     // Compute the end of the array.
487dff0c46cSDimitry Andric     llvm::Value *end = Builder.CreateInBoundsGEP(begin,
488dff0c46cSDimitry Andric                       llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
489dff0c46cSDimitry Andric                                                  "arrayinit.end");
490dff0c46cSDimitry Andric 
491dff0c46cSDimitry Andric     llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
492dff0c46cSDimitry Andric     llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
493dff0c46cSDimitry Andric 
494dff0c46cSDimitry Andric     // Jump into the body.
495dff0c46cSDimitry Andric     CGF.EmitBlock(bodyBB);
496dff0c46cSDimitry Andric     llvm::PHINode *currentElement =
497dff0c46cSDimitry Andric       Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
498dff0c46cSDimitry Andric     currentElement->addIncoming(element, entryBB);
499dff0c46cSDimitry Andric 
500dff0c46cSDimitry Andric     // Emit the actual filler expression.
501dff0c46cSDimitry Andric     LValue elementLV = CGF.MakeAddrLValue(currentElement, elementType);
502dff0c46cSDimitry Andric     if (filler)
503dff0c46cSDimitry Andric       EmitInitializationToLValue(filler, elementLV);
504dff0c46cSDimitry Andric     else
505dff0c46cSDimitry Andric       EmitNullInitializationToLValue(elementLV);
506dff0c46cSDimitry Andric 
507dff0c46cSDimitry Andric     // Move on to the next element.
508dff0c46cSDimitry Andric     llvm::Value *nextElement =
509dff0c46cSDimitry Andric       Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
510dff0c46cSDimitry Andric 
511dff0c46cSDimitry Andric     // Tell the EH cleanup that we finished with the last element.
512dff0c46cSDimitry Andric     if (endOfInit) Builder.CreateStore(nextElement, endOfInit);
513dff0c46cSDimitry Andric 
514dff0c46cSDimitry Andric     // Leave the loop if we're done.
515dff0c46cSDimitry Andric     llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
516dff0c46cSDimitry Andric                                              "arrayinit.done");
517dff0c46cSDimitry Andric     llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
518dff0c46cSDimitry Andric     Builder.CreateCondBr(done, endBB, bodyBB);
519dff0c46cSDimitry Andric     currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
520dff0c46cSDimitry Andric 
521dff0c46cSDimitry Andric     CGF.EmitBlock(endBB);
522dff0c46cSDimitry Andric   }
523dff0c46cSDimitry Andric 
524dff0c46cSDimitry Andric   // Leave the partial-array cleanup if we entered one.
525dff0c46cSDimitry Andric   if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator);
526f22ef01cSRoman Divacky }
527f22ef01cSRoman Divacky 
528f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
529f22ef01cSRoman Divacky //                            Visitor Methods
530f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
531f22ef01cSRoman Divacky 
53217a519f9SDimitry Andric void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
53317a519f9SDimitry Andric   Visit(E->GetTemporaryExpr());
53417a519f9SDimitry Andric }
53517a519f9SDimitry Andric 
5362754fe60SDimitry Andric void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
5377ae0e2c9SDimitry Andric   EmitFinalDestCopy(e->getType(), CGF.getOpaqueLValueMapping(e));
5382754fe60SDimitry Andric }
5392754fe60SDimitry Andric 
54017a519f9SDimitry Andric void
54117a519f9SDimitry Andric AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
542139f7f9bSDimitry Andric   if (Dest.isPotentiallyAliased() &&
543139f7f9bSDimitry Andric       E->getType().isPODType(CGF.getContext())) {
54417a519f9SDimitry Andric     // For a POD type, just emit a load of the lvalue + a copy, because our
54517a519f9SDimitry Andric     // compound literal might alias the destination.
54617a519f9SDimitry Andric     EmitAggLoadOfLValue(E);
54717a519f9SDimitry Andric     return;
54817a519f9SDimitry Andric   }
54917a519f9SDimitry Andric 
55017a519f9SDimitry Andric   AggValueSlot Slot = EnsureSlot(E->getType());
55117a519f9SDimitry Andric   CGF.EmitAggExpr(E->getInitializer(), Slot);
55217a519f9SDimitry Andric }
55317a519f9SDimitry Andric 
554139f7f9bSDimitry Andric /// Attempt to look through various unimportant expressions to find a
555139f7f9bSDimitry Andric /// cast of the given kind.
556139f7f9bSDimitry Andric static Expr *findPeephole(Expr *op, CastKind kind) {
557139f7f9bSDimitry Andric   while (true) {
558139f7f9bSDimitry Andric     op = op->IgnoreParens();
559139f7f9bSDimitry Andric     if (CastExpr *castE = dyn_cast<CastExpr>(op)) {
560139f7f9bSDimitry Andric       if (castE->getCastKind() == kind)
561139f7f9bSDimitry Andric         return castE->getSubExpr();
562139f7f9bSDimitry Andric       if (castE->getCastKind() == CK_NoOp)
563139f7f9bSDimitry Andric         continue;
564139f7f9bSDimitry Andric     }
56559d1ed5bSDimitry Andric     return nullptr;
566139f7f9bSDimitry Andric   }
567139f7f9bSDimitry Andric }
56817a519f9SDimitry Andric 
569f22ef01cSRoman Divacky void AggExprEmitter::VisitCastExpr(CastExpr *E) {
570f22ef01cSRoman Divacky   switch (E->getCastKind()) {
571e580952dSDimitry Andric   case CK_Dynamic: {
5723861d79fSDimitry Andric     // FIXME: Can this actually happen? We have no test coverage for it.
573f22ef01cSRoman Divacky     assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
5743861d79fSDimitry Andric     LValue LV = CGF.EmitCheckedLValue(E->getSubExpr(),
5753861d79fSDimitry Andric                                       CodeGenFunction::TCK_Load);
576f22ef01cSRoman Divacky     // FIXME: Do we also need to handle property references here?
577f22ef01cSRoman Divacky     if (LV.isSimple())
578f22ef01cSRoman Divacky       CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
579f22ef01cSRoman Divacky     else
580f22ef01cSRoman Divacky       CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
581f22ef01cSRoman Divacky 
5822754fe60SDimitry Andric     if (!Dest.isIgnored())
583f22ef01cSRoman Divacky       CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
584f22ef01cSRoman Divacky     break;
585f22ef01cSRoman Divacky   }
586f22ef01cSRoman Divacky 
587e580952dSDimitry Andric   case CK_ToUnion: {
58833956c43SDimitry Andric     // Evaluate even if the destination is ignored.
58933956c43SDimitry Andric     if (Dest.isIgnored()) {
59033956c43SDimitry Andric       CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(),
59133956c43SDimitry Andric                       /*ignoreResult=*/true);
59233956c43SDimitry Andric       break;
59333956c43SDimitry Andric     }
5943b0f4066SDimitry Andric 
595f22ef01cSRoman Divacky     // GCC union extension
596e580952dSDimitry Andric     QualType Ty = E->getSubExpr()->getType();
597e580952dSDimitry Andric     QualType PtrTy = CGF.getContext().getPointerType(Ty);
5982754fe60SDimitry Andric     llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
599f22ef01cSRoman Divacky                                                  CGF.ConvertType(PtrTy));
60017a519f9SDimitry Andric     EmitInitializationToLValue(E->getSubExpr(),
60117a519f9SDimitry Andric                                CGF.MakeAddrLValue(CastPtr, Ty));
602f22ef01cSRoman Divacky     break;
603f22ef01cSRoman Divacky   }
604f22ef01cSRoman Divacky 
605e580952dSDimitry Andric   case CK_DerivedToBase:
606e580952dSDimitry Andric   case CK_BaseToDerived:
607e580952dSDimitry Andric   case CK_UncheckedDerivedToBase: {
6086122f3e6SDimitry Andric     llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
609f22ef01cSRoman Divacky                 "should have been unpacked before we got here");
610f22ef01cSRoman Divacky   }
611f22ef01cSRoman Divacky 
612139f7f9bSDimitry Andric   case CK_NonAtomicToAtomic:
613139f7f9bSDimitry Andric   case CK_AtomicToNonAtomic: {
614139f7f9bSDimitry Andric     bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);
615139f7f9bSDimitry Andric 
616139f7f9bSDimitry Andric     // Determine the atomic and value types.
617139f7f9bSDimitry Andric     QualType atomicType = E->getSubExpr()->getType();
618139f7f9bSDimitry Andric     QualType valueType = E->getType();
619139f7f9bSDimitry Andric     if (isToAtomic) std::swap(atomicType, valueType);
620139f7f9bSDimitry Andric 
621139f7f9bSDimitry Andric     assert(atomicType->isAtomicType());
622139f7f9bSDimitry Andric     assert(CGF.getContext().hasSameUnqualifiedType(valueType,
623139f7f9bSDimitry Andric                           atomicType->castAs<AtomicType>()->getValueType()));
624139f7f9bSDimitry Andric 
625139f7f9bSDimitry Andric     // Just recurse normally if we're ignoring the result or the
626139f7f9bSDimitry Andric     // atomic type doesn't change representation.
627139f7f9bSDimitry Andric     if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {
628139f7f9bSDimitry Andric       return Visit(E->getSubExpr());
629139f7f9bSDimitry Andric     }
630139f7f9bSDimitry Andric 
631139f7f9bSDimitry Andric     CastKind peepholeTarget =
632139f7f9bSDimitry Andric       (isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic);
633139f7f9bSDimitry Andric 
634139f7f9bSDimitry Andric     // These two cases are reverses of each other; try to peephole them.
635139f7f9bSDimitry Andric     if (Expr *op = findPeephole(E->getSubExpr(), peepholeTarget)) {
636139f7f9bSDimitry Andric       assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),
637139f7f9bSDimitry Andric                                                      E->getType()) &&
638139f7f9bSDimitry Andric            "peephole significantly changed types?");
639139f7f9bSDimitry Andric       return Visit(op);
640139f7f9bSDimitry Andric     }
641139f7f9bSDimitry Andric 
642139f7f9bSDimitry Andric     // If we're converting an r-value of non-atomic type to an r-value
643f785676fSDimitry Andric     // of atomic type, just emit directly into the relevant sub-object.
644139f7f9bSDimitry Andric     if (isToAtomic) {
645f785676fSDimitry Andric       AggValueSlot valueDest = Dest;
646f785676fSDimitry Andric       if (!valueDest.isIgnored() && CGF.CGM.isPaddedAtomicType(atomicType)) {
647f785676fSDimitry Andric         // Zero-initialize.  (Strictly speaking, we only need to intialize
648f785676fSDimitry Andric         // the padding at the end, but this is simpler.)
649f785676fSDimitry Andric         if (!Dest.isZeroed())
650f785676fSDimitry Andric           CGF.EmitNullInitialization(Dest.getAddr(), atomicType);
651f785676fSDimitry Andric 
652f785676fSDimitry Andric         // Build a GEP to refer to the subobject.
653f785676fSDimitry Andric         llvm::Value *valueAddr =
65433956c43SDimitry Andric             CGF.Builder.CreateStructGEP(nullptr, valueDest.getAddr(), 0);
655f785676fSDimitry Andric         valueDest = AggValueSlot::forAddr(valueAddr,
656f785676fSDimitry Andric                                           valueDest.getAlignment(),
657f785676fSDimitry Andric                                           valueDest.getQualifiers(),
658f785676fSDimitry Andric                                           valueDest.isExternallyDestructed(),
659f785676fSDimitry Andric                                           valueDest.requiresGCollection(),
660f785676fSDimitry Andric                                           valueDest.isPotentiallyAliased(),
661f785676fSDimitry Andric                                           AggValueSlot::IsZeroed);
662f785676fSDimitry Andric       }
663f785676fSDimitry Andric 
664f785676fSDimitry Andric       CGF.EmitAggExpr(E->getSubExpr(), valueDest);
665139f7f9bSDimitry Andric       return;
666139f7f9bSDimitry Andric     }
667139f7f9bSDimitry Andric 
668139f7f9bSDimitry Andric     // Otherwise, we're converting an atomic type to a non-atomic type.
669f785676fSDimitry Andric     // Make an atomic temporary, emit into that, and then copy the value out.
670139f7f9bSDimitry Andric     AggValueSlot atomicSlot =
671139f7f9bSDimitry Andric       CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");
672139f7f9bSDimitry Andric     CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
673139f7f9bSDimitry Andric 
674139f7f9bSDimitry Andric     llvm::Value *valueAddr =
67533956c43SDimitry Andric         Builder.CreateStructGEP(nullptr, atomicSlot.getAddr(), 0);
676139f7f9bSDimitry Andric     RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());
677139f7f9bSDimitry Andric     return EmitFinalDestCopy(valueType, rvalue);
678139f7f9bSDimitry Andric   }
679139f7f9bSDimitry Andric 
6807ae0e2c9SDimitry Andric   case CK_LValueToRValue:
6817ae0e2c9SDimitry Andric     // If we're loading from a volatile type, force the destination
6827ae0e2c9SDimitry Andric     // into existence.
6837ae0e2c9SDimitry Andric     if (E->getSubExpr()->getType().isVolatileQualified()) {
6847ae0e2c9SDimitry Andric       EnsureDest(E->getType());
6857ae0e2c9SDimitry Andric       return Visit(E->getSubExpr());
6867ae0e2c9SDimitry Andric     }
687139f7f9bSDimitry Andric 
6887ae0e2c9SDimitry Andric     // fallthrough
6897ae0e2c9SDimitry Andric 
690e580952dSDimitry Andric   case CK_NoOp:
691e580952dSDimitry Andric   case CK_UserDefinedConversion:
692e580952dSDimitry Andric   case CK_ConstructorConversion:
693f22ef01cSRoman Divacky     assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
694f22ef01cSRoman Divacky                                                    E->getType()) &&
695f22ef01cSRoman Divacky            "Implicit cast types must be compatible");
696f22ef01cSRoman Divacky     Visit(E->getSubExpr());
697f22ef01cSRoman Divacky     break;
698f22ef01cSRoman Divacky 
699e580952dSDimitry Andric   case CK_LValueBitCast:
7002754fe60SDimitry Andric     llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
7012754fe60SDimitry Andric 
7022754fe60SDimitry Andric   case CK_Dependent:
7032754fe60SDimitry Andric   case CK_BitCast:
7042754fe60SDimitry Andric   case CK_ArrayToPointerDecay:
7052754fe60SDimitry Andric   case CK_FunctionToPointerDecay:
7062754fe60SDimitry Andric   case CK_NullToPointer:
7072754fe60SDimitry Andric   case CK_NullToMemberPointer:
7082754fe60SDimitry Andric   case CK_BaseToDerivedMemberPointer:
7092754fe60SDimitry Andric   case CK_DerivedToBaseMemberPointer:
7102754fe60SDimitry Andric   case CK_MemberPointerToBoolean:
711dff0c46cSDimitry Andric   case CK_ReinterpretMemberPointer:
7122754fe60SDimitry Andric   case CK_IntegralToPointer:
7132754fe60SDimitry Andric   case CK_PointerToIntegral:
7142754fe60SDimitry Andric   case CK_PointerToBoolean:
7152754fe60SDimitry Andric   case CK_ToVoid:
7162754fe60SDimitry Andric   case CK_VectorSplat:
7172754fe60SDimitry Andric   case CK_IntegralCast:
7182754fe60SDimitry Andric   case CK_IntegralToBoolean:
7192754fe60SDimitry Andric   case CK_IntegralToFloating:
7202754fe60SDimitry Andric   case CK_FloatingToIntegral:
7212754fe60SDimitry Andric   case CK_FloatingToBoolean:
7222754fe60SDimitry Andric   case CK_FloatingCast:
7236122f3e6SDimitry Andric   case CK_CPointerToObjCPointerCast:
7246122f3e6SDimitry Andric   case CK_BlockPointerToObjCPointerCast:
7252754fe60SDimitry Andric   case CK_AnyPointerToBlockPointerCast:
7262754fe60SDimitry Andric   case CK_ObjCObjectLValueCast:
7272754fe60SDimitry Andric   case CK_FloatingRealToComplex:
7282754fe60SDimitry Andric   case CK_FloatingComplexToReal:
7292754fe60SDimitry Andric   case CK_FloatingComplexToBoolean:
7302754fe60SDimitry Andric   case CK_FloatingComplexCast:
7312754fe60SDimitry Andric   case CK_FloatingComplexToIntegralComplex:
7322754fe60SDimitry Andric   case CK_IntegralRealToComplex:
7332754fe60SDimitry Andric   case CK_IntegralComplexToReal:
7342754fe60SDimitry Andric   case CK_IntegralComplexToBoolean:
7352754fe60SDimitry Andric   case CK_IntegralComplexCast:
7362754fe60SDimitry Andric   case CK_IntegralComplexToFloatingComplex:
7376122f3e6SDimitry Andric   case CK_ARCProduceObject:
7386122f3e6SDimitry Andric   case CK_ARCConsumeObject:
7396122f3e6SDimitry Andric   case CK_ARCReclaimReturnedObject:
7406122f3e6SDimitry Andric   case CK_ARCExtendBlockObject:
741dff0c46cSDimitry Andric   case CK_CopyAndAutoreleaseBlockObject:
7423861d79fSDimitry Andric   case CK_BuiltinFnToFnPtr:
743139f7f9bSDimitry Andric   case CK_ZeroToOCLEvent:
74459d1ed5bSDimitry Andric   case CK_AddressSpaceConversion:
7452754fe60SDimitry Andric     llvm_unreachable("cast kind invalid for aggregate types");
746f22ef01cSRoman Divacky   }
747f22ef01cSRoman Divacky }
748f22ef01cSRoman Divacky 
749f22ef01cSRoman Divacky void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
75033956c43SDimitry Andric   if (E->getCallReturnType(CGF.getContext())->isReferenceType()) {
751f22ef01cSRoman Divacky     EmitAggLoadOfLValue(E);
752f22ef01cSRoman Divacky     return;
753f22ef01cSRoman Divacky   }
754f22ef01cSRoman Divacky 
755f22ef01cSRoman Divacky   RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
7566122f3e6SDimitry Andric   EmitMoveFromReturnSlot(E, RV);
757f22ef01cSRoman Divacky }
758f22ef01cSRoman Divacky 
759f22ef01cSRoman Divacky void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
760f22ef01cSRoman Divacky   RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
7616122f3e6SDimitry Andric   EmitMoveFromReturnSlot(E, RV);
762f22ef01cSRoman Divacky }
763f22ef01cSRoman Divacky 
764f22ef01cSRoman Divacky void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
7652754fe60SDimitry Andric   CGF.EmitIgnoredExpr(E->getLHS());
7662754fe60SDimitry Andric   Visit(E->getRHS());
767f22ef01cSRoman Divacky }
768f22ef01cSRoman Divacky 
769f22ef01cSRoman Divacky void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
7702754fe60SDimitry Andric   CodeGenFunction::StmtExprEvaluation eval(CGF);
7712754fe60SDimitry Andric   CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
772f22ef01cSRoman Divacky }
773f22ef01cSRoman Divacky 
774f22ef01cSRoman Divacky void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
775e580952dSDimitry Andric   if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
776f22ef01cSRoman Divacky     VisitPointerToDataMemberBinaryOperator(E);
777f22ef01cSRoman Divacky   else
778f22ef01cSRoman Divacky     CGF.ErrorUnsupported(E, "aggregate binary expression");
779f22ef01cSRoman Divacky }
780f22ef01cSRoman Divacky 
781f22ef01cSRoman Divacky void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
782f22ef01cSRoman Divacky                                                     const BinaryOperator *E) {
783f22ef01cSRoman Divacky   LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
7847ae0e2c9SDimitry Andric   EmitFinalDestCopy(E->getType(), LV);
7857ae0e2c9SDimitry Andric }
7867ae0e2c9SDimitry Andric 
7877ae0e2c9SDimitry Andric /// Is the value of the given expression possibly a reference to or
7887ae0e2c9SDimitry Andric /// into a __block variable?
7897ae0e2c9SDimitry Andric static bool isBlockVarRef(const Expr *E) {
7907ae0e2c9SDimitry Andric   // Make sure we look through parens.
7917ae0e2c9SDimitry Andric   E = E->IgnoreParens();
7927ae0e2c9SDimitry Andric 
7937ae0e2c9SDimitry Andric   // Check for a direct reference to a __block variable.
7947ae0e2c9SDimitry Andric   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7957ae0e2c9SDimitry Andric     const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7967ae0e2c9SDimitry Andric     return (var && var->hasAttr<BlocksAttr>());
7977ae0e2c9SDimitry Andric   }
7987ae0e2c9SDimitry Andric 
7997ae0e2c9SDimitry Andric   // More complicated stuff.
8007ae0e2c9SDimitry Andric 
8017ae0e2c9SDimitry Andric   // Binary operators.
8027ae0e2c9SDimitry Andric   if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {
8037ae0e2c9SDimitry Andric     // For an assignment or pointer-to-member operation, just care
8047ae0e2c9SDimitry Andric     // about the LHS.
8057ae0e2c9SDimitry Andric     if (op->isAssignmentOp() || op->isPtrMemOp())
8067ae0e2c9SDimitry Andric       return isBlockVarRef(op->getLHS());
8077ae0e2c9SDimitry Andric 
8087ae0e2c9SDimitry Andric     // For a comma, just care about the RHS.
8097ae0e2c9SDimitry Andric     if (op->getOpcode() == BO_Comma)
8107ae0e2c9SDimitry Andric       return isBlockVarRef(op->getRHS());
8117ae0e2c9SDimitry Andric 
8127ae0e2c9SDimitry Andric     // FIXME: pointer arithmetic?
8137ae0e2c9SDimitry Andric     return false;
8147ae0e2c9SDimitry Andric 
8157ae0e2c9SDimitry Andric   // Check both sides of a conditional operator.
8167ae0e2c9SDimitry Andric   } else if (const AbstractConditionalOperator *op
8177ae0e2c9SDimitry Andric                = dyn_cast<AbstractConditionalOperator>(E)) {
8187ae0e2c9SDimitry Andric     return isBlockVarRef(op->getTrueExpr())
8197ae0e2c9SDimitry Andric         || isBlockVarRef(op->getFalseExpr());
8207ae0e2c9SDimitry Andric 
8217ae0e2c9SDimitry Andric   // OVEs are required to support BinaryConditionalOperators.
8227ae0e2c9SDimitry Andric   } else if (const OpaqueValueExpr *op
8237ae0e2c9SDimitry Andric                = dyn_cast<OpaqueValueExpr>(E)) {
8247ae0e2c9SDimitry Andric     if (const Expr *src = op->getSourceExpr())
8257ae0e2c9SDimitry Andric       return isBlockVarRef(src);
8267ae0e2c9SDimitry Andric 
8277ae0e2c9SDimitry Andric   // Casts are necessary to get things like (*(int*)&var) = foo().
8287ae0e2c9SDimitry Andric   // We don't really care about the kind of cast here, except
8297ae0e2c9SDimitry Andric   // we don't want to look through l2r casts, because it's okay
8307ae0e2c9SDimitry Andric   // to get the *value* in a __block variable.
8317ae0e2c9SDimitry Andric   } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {
8327ae0e2c9SDimitry Andric     if (cast->getCastKind() == CK_LValueToRValue)
8337ae0e2c9SDimitry Andric       return false;
8347ae0e2c9SDimitry Andric     return isBlockVarRef(cast->getSubExpr());
8357ae0e2c9SDimitry Andric 
8367ae0e2c9SDimitry Andric   // Handle unary operators.  Again, just aggressively look through
8377ae0e2c9SDimitry Andric   // it, ignoring the operation.
8387ae0e2c9SDimitry Andric   } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {
8397ae0e2c9SDimitry Andric     return isBlockVarRef(uop->getSubExpr());
8407ae0e2c9SDimitry Andric 
8417ae0e2c9SDimitry Andric   // Look into the base of a field access.
8427ae0e2c9SDimitry Andric   } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
8437ae0e2c9SDimitry Andric     return isBlockVarRef(mem->getBase());
8447ae0e2c9SDimitry Andric 
8457ae0e2c9SDimitry Andric   // Look into the base of a subscript.
8467ae0e2c9SDimitry Andric   } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {
8477ae0e2c9SDimitry Andric     return isBlockVarRef(sub->getBase());
8487ae0e2c9SDimitry Andric   }
8497ae0e2c9SDimitry Andric 
8507ae0e2c9SDimitry Andric   return false;
851f22ef01cSRoman Divacky }
852f22ef01cSRoman Divacky 
853f22ef01cSRoman Divacky void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
854f22ef01cSRoman Divacky   // For an assignment to work, the value on the right has
855f22ef01cSRoman Divacky   // to be compatible with the value on the left.
856f22ef01cSRoman Divacky   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
857f22ef01cSRoman Divacky                                                  E->getRHS()->getType())
858f22ef01cSRoman Divacky          && "Invalid assignment");
8592754fe60SDimitry Andric 
8607ae0e2c9SDimitry Andric   // If the LHS might be a __block variable, and the RHS can
8617ae0e2c9SDimitry Andric   // potentially cause a block copy, we need to evaluate the RHS first
8627ae0e2c9SDimitry Andric   // so that the assignment goes the right place.
8637ae0e2c9SDimitry Andric   // This is pretty semantically fragile.
8647ae0e2c9SDimitry Andric   if (isBlockVarRef(E->getLHS()) &&
8653b0f4066SDimitry Andric       E->getRHS()->HasSideEffects(CGF.getContext())) {
8667ae0e2c9SDimitry Andric     // Ensure that we have a destination, and evaluate the RHS into that.
8677ae0e2c9SDimitry Andric     EnsureDest(E->getRHS()->getType());
8687ae0e2c9SDimitry Andric     Visit(E->getRHS());
8697ae0e2c9SDimitry Andric 
8707ae0e2c9SDimitry Andric     // Now emit the LHS and copy into it.
8713861d79fSDimitry Andric     LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
8727ae0e2c9SDimitry Andric 
873139f7f9bSDimitry Andric     // That copy is an atomic copy if the LHS is atomic.
87433956c43SDimitry Andric     if (LHS.getType()->isAtomicType() ||
87533956c43SDimitry Andric         CGF.LValueIsSuitableForInlineAtomic(LHS)) {
876139f7f9bSDimitry Andric       CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
877139f7f9bSDimitry Andric       return;
878139f7f9bSDimitry Andric     }
879139f7f9bSDimitry Andric 
8807ae0e2c9SDimitry Andric     EmitCopy(E->getLHS()->getType(),
8817ae0e2c9SDimitry Andric              AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
8826122f3e6SDimitry Andric                                      needsGC(E->getLHS()->getType()),
8837ae0e2c9SDimitry Andric                                      AggValueSlot::IsAliased),
8847ae0e2c9SDimitry Andric              Dest);
8853b0f4066SDimitry Andric     return;
8863b0f4066SDimitry Andric   }
8873b0f4066SDimitry Andric 
888f22ef01cSRoman Divacky   LValue LHS = CGF.EmitLValue(E->getLHS());
889f22ef01cSRoman Divacky 
890139f7f9bSDimitry Andric   // If we have an atomic type, evaluate into the destination and then
891139f7f9bSDimitry Andric   // do an atomic copy.
89233956c43SDimitry Andric   if (LHS.getType()->isAtomicType() ||
89333956c43SDimitry Andric       CGF.LValueIsSuitableForInlineAtomic(LHS)) {
894139f7f9bSDimitry Andric     EnsureDest(E->getRHS()->getType());
895139f7f9bSDimitry Andric     Visit(E->getRHS());
896139f7f9bSDimitry Andric     CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
897139f7f9bSDimitry Andric     return;
898139f7f9bSDimitry Andric   }
899139f7f9bSDimitry Andric 
900f22ef01cSRoman Divacky   // Codegen the RHS so that it stores directly into the LHS.
9016122f3e6SDimitry Andric   AggValueSlot LHSSlot =
9026122f3e6SDimitry Andric     AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
9036122f3e6SDimitry Andric                             needsGC(E->getLHS()->getType()),
9046122f3e6SDimitry Andric                             AggValueSlot::IsAliased);
905139f7f9bSDimitry Andric   // A non-volatile aggregate destination might have volatile member.
906139f7f9bSDimitry Andric   if (!LHSSlot.isVolatile() &&
907139f7f9bSDimitry Andric       CGF.hasVolatileMember(E->getLHS()->getType()))
908139f7f9bSDimitry Andric     LHSSlot.setVolatile(true);
909139f7f9bSDimitry Andric 
9107ae0e2c9SDimitry Andric   CGF.EmitAggExpr(E->getRHS(), LHSSlot);
9117ae0e2c9SDimitry Andric 
9127ae0e2c9SDimitry Andric   // Copy into the destination if the assignment isn't ignored.
9137ae0e2c9SDimitry Andric   EmitFinalDestCopy(E->getType(), LHS);
914f22ef01cSRoman Divacky }
915f22ef01cSRoman Divacky 
9162754fe60SDimitry Andric void AggExprEmitter::
9172754fe60SDimitry Andric VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
918f22ef01cSRoman Divacky   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
919f22ef01cSRoman Divacky   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
920f22ef01cSRoman Divacky   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
921f22ef01cSRoman Divacky 
9222754fe60SDimitry Andric   // Bind the common expression if necessary.
9232754fe60SDimitry Andric   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
9242754fe60SDimitry Andric 
9252754fe60SDimitry Andric   CodeGenFunction::ConditionalEvaluation eval(CGF);
92633956c43SDimitry Andric   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
92733956c43SDimitry Andric                            CGF.getProfileCount(E));
928f22ef01cSRoman Divacky 
9292754fe60SDimitry Andric   // Save whether the destination's lifetime is externally managed.
9306122f3e6SDimitry Andric   bool isExternallyDestructed = Dest.isExternallyDestructed();
9312754fe60SDimitry Andric 
9322754fe60SDimitry Andric   eval.begin(CGF);
933f22ef01cSRoman Divacky   CGF.EmitBlock(LHSBlock);
93433956c43SDimitry Andric   CGF.incrementProfileCounter(E);
9352754fe60SDimitry Andric   Visit(E->getTrueExpr());
9362754fe60SDimitry Andric   eval.end(CGF);
937f22ef01cSRoman Divacky 
9382754fe60SDimitry Andric   assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
9392754fe60SDimitry Andric   CGF.Builder.CreateBr(ContBlock);
940f22ef01cSRoman Divacky 
9412754fe60SDimitry Andric   // If the result of an agg expression is unused, then the emission
9422754fe60SDimitry Andric   // of the LHS might need to create a destination slot.  That's fine
9432754fe60SDimitry Andric   // with us, and we can safely emit the RHS into the same slot, but
9446122f3e6SDimitry Andric   // we shouldn't claim that it's already being destructed.
9456122f3e6SDimitry Andric   Dest.setExternallyDestructed(isExternallyDestructed);
946f22ef01cSRoman Divacky 
9472754fe60SDimitry Andric   eval.begin(CGF);
948f22ef01cSRoman Divacky   CGF.EmitBlock(RHSBlock);
9492754fe60SDimitry Andric   Visit(E->getFalseExpr());
9502754fe60SDimitry Andric   eval.end(CGF);
951f22ef01cSRoman Divacky 
952f22ef01cSRoman Divacky   CGF.EmitBlock(ContBlock);
953f22ef01cSRoman Divacky }
954f22ef01cSRoman Divacky 
955f22ef01cSRoman Divacky void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
956f785676fSDimitry Andric   Visit(CE->getChosenSubExpr());
957f22ef01cSRoman Divacky }
958f22ef01cSRoman Divacky 
959f22ef01cSRoman Divacky void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
960f22ef01cSRoman Divacky   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
961f22ef01cSRoman Divacky   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
962f22ef01cSRoman Divacky 
963f22ef01cSRoman Divacky   if (!ArgPtr) {
96459d1ed5bSDimitry Andric     // If EmitVAArg fails, we fall back to the LLVM instruction.
96559d1ed5bSDimitry Andric     llvm::Value *Val =
96659d1ed5bSDimitry Andric         Builder.CreateVAArg(ArgValue, CGF.ConvertType(VE->getType()));
96759d1ed5bSDimitry Andric     if (!Dest.isIgnored())
96859d1ed5bSDimitry Andric       Builder.CreateStore(Val, Dest.getAddr());
969f22ef01cSRoman Divacky     return;
970f22ef01cSRoman Divacky   }
971f22ef01cSRoman Divacky 
9727ae0e2c9SDimitry Andric   EmitFinalDestCopy(VE->getType(), CGF.MakeAddrLValue(ArgPtr, VE->getType()));
973f22ef01cSRoman Divacky }
974f22ef01cSRoman Divacky 
975f22ef01cSRoman Divacky void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
9762754fe60SDimitry Andric   // Ensure that we have a slot, but if we already do, remember
9776122f3e6SDimitry Andric   // whether it was externally destructed.
9786122f3e6SDimitry Andric   bool wasExternallyDestructed = Dest.isExternallyDestructed();
9797ae0e2c9SDimitry Andric   EnsureDest(E->getType());
9806122f3e6SDimitry Andric 
9816122f3e6SDimitry Andric   // We're going to push a destructor if there isn't already one.
9826122f3e6SDimitry Andric   Dest.setExternallyDestructed();
983f22ef01cSRoman Divacky 
984f22ef01cSRoman Divacky   Visit(E->getSubExpr());
985f22ef01cSRoman Divacky 
9866122f3e6SDimitry Andric   // Push that destructor we promised.
9876122f3e6SDimitry Andric   if (!wasExternallyDestructed)
988dff0c46cSDimitry Andric     CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddr());
989f22ef01cSRoman Divacky }
990f22ef01cSRoman Divacky 
991f22ef01cSRoman Divacky void
992f22ef01cSRoman Divacky AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
9932754fe60SDimitry Andric   AggValueSlot Slot = EnsureSlot(E->getType());
9942754fe60SDimitry Andric   CGF.EmitCXXConstructExpr(E, Slot);
995f22ef01cSRoman Divacky }
996f22ef01cSRoman Divacky 
997dff0c46cSDimitry Andric void
998dff0c46cSDimitry Andric AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
999dff0c46cSDimitry Andric   AggValueSlot Slot = EnsureSlot(E->getType());
1000dff0c46cSDimitry Andric   CGF.EmitLambdaExpr(E, Slot);
1001dff0c46cSDimitry Andric }
1002dff0c46cSDimitry Andric 
10032754fe60SDimitry Andric void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
1004dff0c46cSDimitry Andric   CGF.enterFullExpression(E);
1005dff0c46cSDimitry Andric   CodeGenFunction::RunCleanupsScope cleanups(CGF);
1006dff0c46cSDimitry Andric   Visit(E->getSubExpr());
1007f22ef01cSRoman Divacky }
1008f22ef01cSRoman Divacky 
1009ffd1746dSEd Schouten void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
10102754fe60SDimitry Andric   QualType T = E->getType();
10112754fe60SDimitry Andric   AggValueSlot Slot = EnsureSlot(T);
101217a519f9SDimitry Andric   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
1013f22ef01cSRoman Divacky }
1014f22ef01cSRoman Divacky 
1015f22ef01cSRoman Divacky void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
10162754fe60SDimitry Andric   QualType T = E->getType();
10172754fe60SDimitry Andric   AggValueSlot Slot = EnsureSlot(T);
101817a519f9SDimitry Andric   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
10192754fe60SDimitry Andric }
1020f22ef01cSRoman Divacky 
10212754fe60SDimitry Andric /// isSimpleZero - If emitting this value will obviously just cause a store of
10222754fe60SDimitry Andric /// zero to memory, return true.  This can return false if uncertain, so it just
10232754fe60SDimitry Andric /// handles simple cases.
10242754fe60SDimitry Andric static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
10253b0f4066SDimitry Andric   E = E->IgnoreParens();
10263b0f4066SDimitry Andric 
10272754fe60SDimitry Andric   // 0
10282754fe60SDimitry Andric   if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
10292754fe60SDimitry Andric     return IL->getValue() == 0;
10302754fe60SDimitry Andric   // +0.0
10312754fe60SDimitry Andric   if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
10322754fe60SDimitry Andric     return FL->getValue().isPosZero();
10332754fe60SDimitry Andric   // int()
10342754fe60SDimitry Andric   if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
10352754fe60SDimitry Andric       CGF.getTypes().isZeroInitializable(E->getType()))
10362754fe60SDimitry Andric     return true;
10372754fe60SDimitry Andric   // (int*)0 - Null pointer expressions.
10382754fe60SDimitry Andric   if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
10392754fe60SDimitry Andric     return ICE->getCastKind() == CK_NullToPointer;
10402754fe60SDimitry Andric   // '\0'
10412754fe60SDimitry Andric   if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
10422754fe60SDimitry Andric     return CL->getValue() == 0;
10432754fe60SDimitry Andric 
10442754fe60SDimitry Andric   // Otherwise, hard case: conservatively return false.
10452754fe60SDimitry Andric   return false;
1046f22ef01cSRoman Divacky }
10472754fe60SDimitry Andric 
1048f22ef01cSRoman Divacky 
1049f22ef01cSRoman Divacky void
105017a519f9SDimitry Andric AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) {
105117a519f9SDimitry Andric   QualType type = LV.getType();
1052f22ef01cSRoman Divacky   // FIXME: Ignore result?
1053f22ef01cSRoman Divacky   // FIXME: Are initializers affected by volatile?
10542754fe60SDimitry Andric   if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
10552754fe60SDimitry Andric     // Storing "i32 0" to a zero'd memory location is a noop.
1056139f7f9bSDimitry Andric     return;
1057139f7f9bSDimitry Andric   } else if (isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) {
1058139f7f9bSDimitry Andric     return EmitNullInitializationToLValue(LV);
105917a519f9SDimitry Andric   } else if (type->isReferenceType()) {
1060f785676fSDimitry Andric     RValue RV = CGF.EmitReferenceBindingToExpr(E);
1061139f7f9bSDimitry Andric     return CGF.EmitStoreThroughLValue(RV, LV);
1062139f7f9bSDimitry Andric   }
1063139f7f9bSDimitry Andric 
1064139f7f9bSDimitry Andric   switch (CGF.getEvaluationKind(type)) {
1065139f7f9bSDimitry Andric   case TEK_Complex:
1066139f7f9bSDimitry Andric     CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
1067139f7f9bSDimitry Andric     return;
1068139f7f9bSDimitry Andric   case TEK_Aggregate:
10696122f3e6SDimitry Andric     CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV,
10706122f3e6SDimitry Andric                                                AggValueSlot::IsDestructed,
10716122f3e6SDimitry Andric                                       AggValueSlot::DoesNotNeedGCBarriers,
10726122f3e6SDimitry Andric                                                AggValueSlot::IsNotAliased,
107317a519f9SDimitry Andric                                                Dest.isZeroed()));
1074139f7f9bSDimitry Andric     return;
1075139f7f9bSDimitry Andric   case TEK_Scalar:
1076139f7f9bSDimitry Andric     if (LV.isSimple()) {
107759d1ed5bSDimitry Andric       CGF.EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false);
1078f22ef01cSRoman Divacky     } else {
107917a519f9SDimitry Andric       CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
1080f22ef01cSRoman Divacky     }
1081139f7f9bSDimitry Andric     return;
1082139f7f9bSDimitry Andric   }
1083139f7f9bSDimitry Andric   llvm_unreachable("bad evaluation kind");
1084f22ef01cSRoman Divacky }
1085f22ef01cSRoman Divacky 
108617a519f9SDimitry Andric void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
108717a519f9SDimitry Andric   QualType type = lv.getType();
108817a519f9SDimitry Andric 
10892754fe60SDimitry Andric   // If the destination slot is already zeroed out before the aggregate is
10902754fe60SDimitry Andric   // copied into it, we don't have to emit any zeros here.
109117a519f9SDimitry Andric   if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
10922754fe60SDimitry Andric     return;
10932754fe60SDimitry Andric 
1094139f7f9bSDimitry Andric   if (CGF.hasScalarEvaluationKind(type)) {
1095139f7f9bSDimitry Andric     // For non-aggregates, we can store the appropriate null constant.
1096139f7f9bSDimitry Andric     llvm::Value *null = CGF.CGM.EmitNullConstant(type);
1097dff0c46cSDimitry Andric     // Note that the following is not equivalent to
1098dff0c46cSDimitry Andric     // EmitStoreThroughBitfieldLValue for ARC types.
1099dff0c46cSDimitry Andric     if (lv.isBitField()) {
1100dff0c46cSDimitry Andric       CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
1101dff0c46cSDimitry Andric     } else {
1102dff0c46cSDimitry Andric       assert(lv.isSimple());
1103dff0c46cSDimitry Andric       CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
1104dff0c46cSDimitry Andric     }
1105f22ef01cSRoman Divacky   } else {
1106f22ef01cSRoman Divacky     // There's a potential optimization opportunity in combining
1107f22ef01cSRoman Divacky     // memsets; that would be easy for arrays, but relatively
1108f22ef01cSRoman Divacky     // difficult for structures with the current code.
110917a519f9SDimitry Andric     CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
1110f22ef01cSRoman Divacky   }
1111f22ef01cSRoman Divacky }
1112f22ef01cSRoman Divacky 
1113f22ef01cSRoman Divacky void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
1114f22ef01cSRoman Divacky #if 0
1115f22ef01cSRoman Divacky   // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
1116f22ef01cSRoman Divacky   // (Length of globals? Chunks of zeroed-out space?).
1117f22ef01cSRoman Divacky   //
1118f22ef01cSRoman Divacky   // If we can, prefer a copy from a global; this is a lot less code for long
1119f22ef01cSRoman Divacky   // globals, and it's easier for the current optimizers to analyze.
1120f22ef01cSRoman Divacky   if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
1121f22ef01cSRoman Divacky     llvm::GlobalVariable* GV =
1122f22ef01cSRoman Divacky     new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
1123f22ef01cSRoman Divacky                              llvm::GlobalValue::InternalLinkage, C, "");
11247ae0e2c9SDimitry Andric     EmitFinalDestCopy(E->getType(), CGF.MakeAddrLValue(GV, E->getType()));
1125f22ef01cSRoman Divacky     return;
1126f22ef01cSRoman Divacky   }
1127f22ef01cSRoman Divacky #endif
11282754fe60SDimitry Andric   if (E->hadArrayRangeDesignator())
1129f22ef01cSRoman Divacky     CGF.ErrorUnsupported(E, "GNU array range designator extension");
11302754fe60SDimitry Andric 
1131cb4dff85SDimitry Andric   AggValueSlot Dest = EnsureSlot(E->getType());
1132f785676fSDimitry Andric 
1133cb4dff85SDimitry Andric   LValue DestLV = CGF.MakeAddrLValue(Dest.getAddr(), E->getType(),
1134cb4dff85SDimitry Andric                                      Dest.getAlignment());
1135f22ef01cSRoman Divacky 
1136f22ef01cSRoman Divacky   // Handle initialization of an array.
1137f22ef01cSRoman Divacky   if (E->getType()->isArrayType()) {
1138cb4dff85SDimitry Andric     if (E->isStringLiteralInit())
1139cb4dff85SDimitry Andric       return Visit(E->getInit(0));
1140f22ef01cSRoman Divacky 
1141dff0c46cSDimitry Andric     QualType elementType =
1142dff0c46cSDimitry Andric         CGF.getContext().getAsArrayType(E->getType())->getElementType();
1143f22ef01cSRoman Divacky 
1144dff0c46cSDimitry Andric     llvm::PointerType *APType =
1145cb4dff85SDimitry Andric       cast<llvm::PointerType>(Dest.getAddr()->getType());
1146dff0c46cSDimitry Andric     llvm::ArrayType *AType =
1147dff0c46cSDimitry Andric       cast<llvm::ArrayType>(APType->getElementType());
114817a519f9SDimitry Andric 
1149cb4dff85SDimitry Andric     EmitArrayInit(Dest.getAddr(), AType, elementType, E);
1150f22ef01cSRoman Divacky     return;
1151f22ef01cSRoman Divacky   }
1152f22ef01cSRoman Divacky 
115359d1ed5bSDimitry Andric   if (E->getType()->isAtomicType()) {
115459d1ed5bSDimitry Andric     // An _Atomic(T) object can be list-initialized from an expression
115559d1ed5bSDimitry Andric     // of the same type.
115659d1ed5bSDimitry Andric     assert(E->getNumInits() == 1 &&
115759d1ed5bSDimitry Andric            CGF.getContext().hasSameUnqualifiedType(E->getInit(0)->getType(),
115859d1ed5bSDimitry Andric                                                    E->getType()) &&
115959d1ed5bSDimitry Andric            "unexpected list initialization for atomic object");
116059d1ed5bSDimitry Andric     return Visit(E->getInit(0));
116159d1ed5bSDimitry Andric   }
116259d1ed5bSDimitry Andric 
1163f22ef01cSRoman Divacky   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
1164f22ef01cSRoman Divacky 
1165f22ef01cSRoman Divacky   // Do struct initialization; this code just sets each individual member
1166f22ef01cSRoman Divacky   // to the approprate value.  This makes bitfield support automatic;
1167f22ef01cSRoman Divacky   // the disadvantage is that the generated code is more difficult for
1168f22ef01cSRoman Divacky   // the optimizer, especially with bitfields.
1169f22ef01cSRoman Divacky   unsigned NumInitElements = E->getNumInits();
117017a519f9SDimitry Andric   RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
1171e580952dSDimitry Andric 
1172284c1978SDimitry Andric   // Prepare a 'this' for CXXDefaultInitExprs.
1173284c1978SDimitry Andric   CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddr());
1174284c1978SDimitry Andric 
117517a519f9SDimitry Andric   if (record->isUnion()) {
1176f22ef01cSRoman Divacky     // Only initialize one field of a union. The field itself is
1177f22ef01cSRoman Divacky     // specified by the initializer list.
1178f22ef01cSRoman Divacky     if (!E->getInitializedFieldInUnion()) {
1179f22ef01cSRoman Divacky       // Empty union; we have nothing to do.
1180f22ef01cSRoman Divacky 
1181f22ef01cSRoman Divacky #ifndef NDEBUG
1182f22ef01cSRoman Divacky       // Make sure that it's really an empty and not a failure of
1183f22ef01cSRoman Divacky       // semantic analysis.
118459d1ed5bSDimitry Andric       for (const auto *Field : record->fields())
1185f22ef01cSRoman Divacky         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
1186f22ef01cSRoman Divacky #endif
1187f22ef01cSRoman Divacky       return;
1188f22ef01cSRoman Divacky     }
1189f22ef01cSRoman Divacky 
1190f22ef01cSRoman Divacky     // FIXME: volatility
1191f22ef01cSRoman Divacky     FieldDecl *Field = E->getInitializedFieldInUnion();
1192f22ef01cSRoman Divacky 
1193cb4dff85SDimitry Andric     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
1194f22ef01cSRoman Divacky     if (NumInitElements) {
1195f22ef01cSRoman Divacky       // Store the initializer into the field
119617a519f9SDimitry Andric       EmitInitializationToLValue(E->getInit(0), FieldLoc);
1197f22ef01cSRoman Divacky     } else {
11982754fe60SDimitry Andric       // Default-initialize to null.
119917a519f9SDimitry Andric       EmitNullInitializationToLValue(FieldLoc);
1200f22ef01cSRoman Divacky     }
1201f22ef01cSRoman Divacky 
1202f22ef01cSRoman Divacky     return;
1203f22ef01cSRoman Divacky   }
1204f22ef01cSRoman Divacky 
120517a519f9SDimitry Andric   // We'll need to enter cleanup scopes in case any of the member
120617a519f9SDimitry Andric   // initializers throw an exception.
12076122f3e6SDimitry Andric   SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
120859d1ed5bSDimitry Andric   llvm::Instruction *cleanupDominator = nullptr;
120917a519f9SDimitry Andric 
1210f22ef01cSRoman Divacky   // Here we iterate over the fields; this makes it simpler to both
1211f22ef01cSRoman Divacky   // default-initialize fields and skip over unnamed fields.
121217a519f9SDimitry Andric   unsigned curInitIndex = 0;
121359d1ed5bSDimitry Andric   for (const auto *field : record->fields()) {
121417a519f9SDimitry Andric     // We're done once we hit the flexible array member.
121517a519f9SDimitry Andric     if (field->getType()->isIncompleteArrayType())
1216f22ef01cSRoman Divacky       break;
1217f22ef01cSRoman Divacky 
121817a519f9SDimitry Andric     // Always skip anonymous bitfields.
121917a519f9SDimitry Andric     if (field->isUnnamedBitfield())
1220f22ef01cSRoman Divacky       continue;
1221f22ef01cSRoman Divacky 
122217a519f9SDimitry Andric     // We're done if we reach the end of the explicit initializers, we
122317a519f9SDimitry Andric     // have a zeroed object, and the rest of the fields are
122417a519f9SDimitry Andric     // zero-initializable.
122517a519f9SDimitry Andric     if (curInitIndex == NumInitElements && Dest.isZeroed() &&
12262754fe60SDimitry Andric         CGF.getTypes().isZeroInitializable(E->getType()))
12272754fe60SDimitry Andric       break;
12282754fe60SDimitry Andric 
1229cb4dff85SDimitry Andric 
123059d1ed5bSDimitry Andric     LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field);
1231f22ef01cSRoman Divacky     // We never generate write-barries for initialized fields.
123217a519f9SDimitry Andric     LV.setNonGC(true);
12332754fe60SDimitry Andric 
123417a519f9SDimitry Andric     if (curInitIndex < NumInitElements) {
1235f22ef01cSRoman Divacky       // Store the initializer into the field.
123617a519f9SDimitry Andric       EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
1237f22ef01cSRoman Divacky     } else {
1238f22ef01cSRoman Divacky       // We're out of initalizers; default-initialize to null
123917a519f9SDimitry Andric       EmitNullInitializationToLValue(LV);
124017a519f9SDimitry Andric     }
124117a519f9SDimitry Andric 
124217a519f9SDimitry Andric     // Push a destructor if necessary.
124317a519f9SDimitry Andric     // FIXME: if we have an array of structures, all explicitly
124417a519f9SDimitry Andric     // initialized, we can end up pushing a linear number of cleanups.
124517a519f9SDimitry Andric     bool pushedCleanup = false;
124617a519f9SDimitry Andric     if (QualType::DestructionKind dtorKind
124717a519f9SDimitry Andric           = field->getType().isDestructedType()) {
124817a519f9SDimitry Andric       assert(LV.isSimple());
124917a519f9SDimitry Andric       if (CGF.needsEHCleanup(dtorKind)) {
1250dff0c46cSDimitry Andric         if (!cleanupDominator)
1251dff0c46cSDimitry Andric           cleanupDominator = CGF.Builder.CreateUnreachable(); // placeholder
1252dff0c46cSDimitry Andric 
125317a519f9SDimitry Andric         CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
125417a519f9SDimitry Andric                         CGF.getDestroyer(dtorKind), false);
125517a519f9SDimitry Andric         cleanups.push_back(CGF.EHStack.stable_begin());
125617a519f9SDimitry Andric         pushedCleanup = true;
125717a519f9SDimitry Andric       }
1258f22ef01cSRoman Divacky     }
12592754fe60SDimitry Andric 
12602754fe60SDimitry Andric     // If the GEP didn't get used because of a dead zero init or something
12612754fe60SDimitry Andric     // else, clean it up for -O0 builds and general tidiness.
126217a519f9SDimitry Andric     if (!pushedCleanup && LV.isSimple())
12632754fe60SDimitry Andric       if (llvm::GetElementPtrInst *GEP =
126417a519f9SDimitry Andric             dyn_cast<llvm::GetElementPtrInst>(LV.getAddress()))
12652754fe60SDimitry Andric         if (GEP->use_empty())
12662754fe60SDimitry Andric           GEP->eraseFromParent();
1267f22ef01cSRoman Divacky   }
126817a519f9SDimitry Andric 
126917a519f9SDimitry Andric   // Deactivate all the partial cleanups in reverse order, which
127017a519f9SDimitry Andric   // generally means popping them.
127117a519f9SDimitry Andric   for (unsigned i = cleanups.size(); i != 0; --i)
1272dff0c46cSDimitry Andric     CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
1273dff0c46cSDimitry Andric 
1274dff0c46cSDimitry Andric   // Destroy the placeholder if we made one.
1275dff0c46cSDimitry Andric   if (cleanupDominator)
1276dff0c46cSDimitry Andric     cleanupDominator->eraseFromParent();
1277f22ef01cSRoman Divacky }
1278f22ef01cSRoman Divacky 
1279f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
1280f22ef01cSRoman Divacky //                        Entry Points into this File
1281f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
1282f22ef01cSRoman Divacky 
12832754fe60SDimitry Andric /// GetNumNonZeroBytesInInit - Get an approximate count of the number of
12842754fe60SDimitry Andric /// non-zero bytes that will be stored when outputting the initializer for the
12852754fe60SDimitry Andric /// specified initializer expression.
12863b0f4066SDimitry Andric static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
12873b0f4066SDimitry Andric   E = E->IgnoreParens();
12882754fe60SDimitry Andric 
12892754fe60SDimitry Andric   // 0 and 0.0 won't require any non-zero stores!
12903b0f4066SDimitry Andric   if (isSimpleZero(E, CGF)) return CharUnits::Zero();
12912754fe60SDimitry Andric 
12922754fe60SDimitry Andric   // If this is an initlist expr, sum up the size of sizes of the (present)
12932754fe60SDimitry Andric   // elements.  If this is something weird, assume the whole thing is non-zero.
12942754fe60SDimitry Andric   const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
129559d1ed5bSDimitry Andric   if (!ILE || !CGF.getTypes().isZeroInitializable(ILE->getType()))
12963b0f4066SDimitry Andric     return CGF.getContext().getTypeSizeInChars(E->getType());
12972754fe60SDimitry Andric 
12982754fe60SDimitry Andric   // InitListExprs for structs have to be handled carefully.  If there are
12992754fe60SDimitry Andric   // reference members, we need to consider the size of the reference, not the
13002754fe60SDimitry Andric   // referencee.  InitListExprs for unions and arrays can't have references.
13012754fe60SDimitry Andric   if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
13022754fe60SDimitry Andric     if (!RT->isUnionType()) {
13032754fe60SDimitry Andric       RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
13043b0f4066SDimitry Andric       CharUnits NumNonZeroBytes = CharUnits::Zero();
13052754fe60SDimitry Andric 
13062754fe60SDimitry Andric       unsigned ILEElement = 0;
130759d1ed5bSDimitry Andric       for (const auto *Field : SD->fields()) {
13082754fe60SDimitry Andric         // We're done once we hit the flexible array member or run out of
13092754fe60SDimitry Andric         // InitListExpr elements.
13102754fe60SDimitry Andric         if (Field->getType()->isIncompleteArrayType() ||
13112754fe60SDimitry Andric             ILEElement == ILE->getNumInits())
13122754fe60SDimitry Andric           break;
13132754fe60SDimitry Andric         if (Field->isUnnamedBitfield())
13142754fe60SDimitry Andric           continue;
13152754fe60SDimitry Andric 
13162754fe60SDimitry Andric         const Expr *E = ILE->getInit(ILEElement++);
13172754fe60SDimitry Andric 
13182754fe60SDimitry Andric         // Reference values are always non-null and have the width of a pointer.
13192754fe60SDimitry Andric         if (Field->getType()->isReferenceType())
13203b0f4066SDimitry Andric           NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
1321284c1978SDimitry Andric               CGF.getTarget().getPointerWidth(0));
13222754fe60SDimitry Andric         else
13232754fe60SDimitry Andric           NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
13242754fe60SDimitry Andric       }
13252754fe60SDimitry Andric 
13262754fe60SDimitry Andric       return NumNonZeroBytes;
13272754fe60SDimitry Andric     }
13282754fe60SDimitry Andric   }
13292754fe60SDimitry Andric 
13302754fe60SDimitry Andric 
13313b0f4066SDimitry Andric   CharUnits NumNonZeroBytes = CharUnits::Zero();
13322754fe60SDimitry Andric   for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
13332754fe60SDimitry Andric     NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
13342754fe60SDimitry Andric   return NumNonZeroBytes;
13352754fe60SDimitry Andric }
13362754fe60SDimitry Andric 
13372754fe60SDimitry Andric /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
13382754fe60SDimitry Andric /// zeros in it, emit a memset and avoid storing the individual zeros.
13392754fe60SDimitry Andric ///
13402754fe60SDimitry Andric static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
13412754fe60SDimitry Andric                                      CodeGenFunction &CGF) {
13422754fe60SDimitry Andric   // If the slot is already known to be zeroed, nothing to do.  Don't mess with
13432754fe60SDimitry Andric   // volatile stores.
134459d1ed5bSDimitry Andric   if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == nullptr)
134559d1ed5bSDimitry Andric     return;
13462754fe60SDimitry Andric 
13473b0f4066SDimitry Andric   // C++ objects with a user-declared constructor don't need zero'ing.
13483861d79fSDimitry Andric   if (CGF.getLangOpts().CPlusPlus)
13493b0f4066SDimitry Andric     if (const RecordType *RT = CGF.getContext()
13503b0f4066SDimitry Andric                        .getBaseElementType(E->getType())->getAs<RecordType>()) {
13513b0f4066SDimitry Andric       const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
13523b0f4066SDimitry Andric       if (RD->hasUserDeclaredConstructor())
13533b0f4066SDimitry Andric         return;
13543b0f4066SDimitry Andric     }
13553b0f4066SDimitry Andric 
13562754fe60SDimitry Andric   // If the type is 16-bytes or smaller, prefer individual stores over memset.
13573b0f4066SDimitry Andric   std::pair<CharUnits, CharUnits> TypeInfo =
13583b0f4066SDimitry Andric     CGF.getContext().getTypeInfoInChars(E->getType());
13593b0f4066SDimitry Andric   if (TypeInfo.first <= CharUnits::fromQuantity(16))
13602754fe60SDimitry Andric     return;
13612754fe60SDimitry Andric 
13622754fe60SDimitry Andric   // Check to see if over 3/4 of the initializer are known to be zero.  If so,
13632754fe60SDimitry Andric   // we prefer to emit memset + individual stores for the rest.
13643b0f4066SDimitry Andric   CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
13653b0f4066SDimitry Andric   if (NumNonZeroBytes*4 > TypeInfo.first)
13662754fe60SDimitry Andric     return;
13672754fe60SDimitry Andric 
13682754fe60SDimitry Andric   // Okay, it seems like a good idea to use an initial memset, emit the call.
13693b0f4066SDimitry Andric   llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first.getQuantity());
13703b0f4066SDimitry Andric   CharUnits Align = TypeInfo.second;
13712754fe60SDimitry Andric 
13722754fe60SDimitry Andric   llvm::Value *Loc = Slot.getAddr();
13732754fe60SDimitry Andric 
1374dff0c46cSDimitry Andric   Loc = CGF.Builder.CreateBitCast(Loc, CGF.Int8PtrTy);
13753b0f4066SDimitry Andric   CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal,
13763b0f4066SDimitry Andric                            Align.getQuantity(), false);
13772754fe60SDimitry Andric 
13782754fe60SDimitry Andric   // Tell the AggExprEmitter that the slot is known zero.
13792754fe60SDimitry Andric   Slot.setZeroed();
13802754fe60SDimitry Andric }
13812754fe60SDimitry Andric 
13822754fe60SDimitry Andric 
13832754fe60SDimitry Andric 
13842754fe60SDimitry Andric 
1385f22ef01cSRoman Divacky /// EmitAggExpr - Emit the computation of the specified expression of aggregate
1386f22ef01cSRoman Divacky /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
1387f22ef01cSRoman Divacky /// the value of the aggregate expression is not needed.  If VolatileDest is
1388f22ef01cSRoman Divacky /// true, DestPtr cannot be 0.
13897ae0e2c9SDimitry Andric void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) {
1390139f7f9bSDimitry Andric   assert(E && hasAggregateEvaluationKind(E->getType()) &&
1391f22ef01cSRoman Divacky          "Invalid aggregate expression to emit");
139259d1ed5bSDimitry Andric   assert((Slot.getAddr() != nullptr || Slot.isIgnored()) &&
13932754fe60SDimitry Andric          "slot has bits but no address");
1394f22ef01cSRoman Divacky 
13952754fe60SDimitry Andric   // Optimize the slot if possible.
13962754fe60SDimitry Andric   CheckAggExprForMemSetUse(Slot, E, *this);
13972754fe60SDimitry Andric 
139897bc6c73SDimitry Andric   AggExprEmitter(*this, Slot, Slot.isIgnored()).Visit(const_cast<Expr*>(E));
1399f22ef01cSRoman Divacky }
1400f22ef01cSRoman Divacky 
1401f22ef01cSRoman Divacky LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
1402139f7f9bSDimitry Andric   assert(hasAggregateEvaluationKind(E->getType()) && "Invalid argument!");
1403f22ef01cSRoman Divacky   llvm::Value *Temp = CreateMemTemp(E->getType());
1404e580952dSDimitry Andric   LValue LV = MakeAddrLValue(Temp, E->getType());
14056122f3e6SDimitry Andric   EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,
14066122f3e6SDimitry Andric                                          AggValueSlot::DoesNotNeedGCBarriers,
14076122f3e6SDimitry Andric                                          AggValueSlot::IsNotAliased));
1408e580952dSDimitry Andric   return LV;
1409f22ef01cSRoman Divacky }
1410f22ef01cSRoman Divacky 
1411f22ef01cSRoman Divacky void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
1412f22ef01cSRoman Divacky                                         llvm::Value *SrcPtr, QualType Ty,
14137ae0e2c9SDimitry Andric                                         bool isVolatile,
14143861d79fSDimitry Andric                                         CharUnits alignment,
14153861d79fSDimitry Andric                                         bool isAssignment) {
1416f22ef01cSRoman Divacky   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
1417f22ef01cSRoman Divacky 
14183861d79fSDimitry Andric   if (getLangOpts().CPlusPlus) {
1419f22ef01cSRoman Divacky     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1420f22ef01cSRoman Divacky       CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
1421f22ef01cSRoman Divacky       assert((Record->hasTrivialCopyConstructor() ||
14226122f3e6SDimitry Andric               Record->hasTrivialCopyAssignment() ||
14236122f3e6SDimitry Andric               Record->hasTrivialMoveConstructor() ||
142433956c43SDimitry Andric               Record->hasTrivialMoveAssignment() ||
142533956c43SDimitry Andric               Record->isUnion()) &&
1426139f7f9bSDimitry Andric              "Trying to aggregate-copy a type without a trivial copy/move "
1427f22ef01cSRoman Divacky              "constructor or assignment operator");
1428f22ef01cSRoman Divacky       // Ignore empty classes in C++.
1429f22ef01cSRoman Divacky       if (Record->isEmpty())
1430f22ef01cSRoman Divacky         return;
1431f22ef01cSRoman Divacky     }
1432f22ef01cSRoman Divacky   }
1433f22ef01cSRoman Divacky 
1434f22ef01cSRoman Divacky   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
1435f22ef01cSRoman Divacky   // C99 6.5.16.1p3, which states "If the value being stored in an object is
1436f22ef01cSRoman Divacky   // read from another object that overlaps in anyway the storage of the first
1437f22ef01cSRoman Divacky   // object, then the overlap shall be exact and the two objects shall have
1438f22ef01cSRoman Divacky   // qualified or unqualified versions of a compatible type."
1439f22ef01cSRoman Divacky   //
1440f22ef01cSRoman Divacky   // memcpy is not defined if the source and destination pointers are exactly
1441f22ef01cSRoman Divacky   // equal, but other compilers do this optimization, and almost every memcpy
1442f22ef01cSRoman Divacky   // implementation handles this case safely.  If there is a libc that does not
1443f22ef01cSRoman Divacky   // safely handle this, we can add a target hook.
1444f22ef01cSRoman Divacky 
14453861d79fSDimitry Andric   // Get data size and alignment info for this aggregate. If this is an
14463861d79fSDimitry Andric   // assignment don't copy the tail padding. Otherwise copying it is fine.
14473861d79fSDimitry Andric   std::pair<CharUnits, CharUnits> TypeInfo;
14483861d79fSDimitry Andric   if (isAssignment)
14493861d79fSDimitry Andric     TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);
14503861d79fSDimitry Andric   else
14513861d79fSDimitry Andric     TypeInfo = getContext().getTypeInfoInChars(Ty);
1452f22ef01cSRoman Divacky 
14537ae0e2c9SDimitry Andric   if (alignment.isZero())
14547ae0e2c9SDimitry Andric     alignment = TypeInfo.second;
1455dff0c46cSDimitry Andric 
145633956c43SDimitry Andric   llvm::Value *SizeVal = nullptr;
145733956c43SDimitry Andric   if (TypeInfo.first.isZero()) {
145833956c43SDimitry Andric     // But note that getTypeInfo returns 0 for a VLA.
145933956c43SDimitry Andric     if (auto *VAT = dyn_cast_or_null<VariableArrayType>(
146033956c43SDimitry Andric             getContext().getAsArrayType(Ty))) {
146133956c43SDimitry Andric       QualType BaseEltTy;
146233956c43SDimitry Andric       SizeVal = emitArrayLength(VAT, BaseEltTy, DestPtr);
146333956c43SDimitry Andric       TypeInfo = getContext().getTypeInfoDataSizeInChars(BaseEltTy);
146433956c43SDimitry Andric       std::pair<CharUnits, CharUnits> LastElementTypeInfo;
146533956c43SDimitry Andric       if (!isAssignment)
146633956c43SDimitry Andric         LastElementTypeInfo = getContext().getTypeInfoInChars(BaseEltTy);
146733956c43SDimitry Andric       assert(!TypeInfo.first.isZero());
146833956c43SDimitry Andric       SizeVal = Builder.CreateNUWMul(
146933956c43SDimitry Andric           SizeVal,
147033956c43SDimitry Andric           llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()));
147133956c43SDimitry Andric       if (!isAssignment) {
147233956c43SDimitry Andric         SizeVal = Builder.CreateNUWSub(
147333956c43SDimitry Andric             SizeVal,
147433956c43SDimitry Andric             llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()));
147533956c43SDimitry Andric         SizeVal = Builder.CreateNUWAdd(
147633956c43SDimitry Andric             SizeVal, llvm::ConstantInt::get(
147733956c43SDimitry Andric                          SizeTy, LastElementTypeInfo.first.getQuantity()));
147833956c43SDimitry Andric       }
147933956c43SDimitry Andric     }
148033956c43SDimitry Andric   }
148133956c43SDimitry Andric   if (!SizeVal) {
148233956c43SDimitry Andric     SizeVal = llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity());
148333956c43SDimitry Andric   }
1484f22ef01cSRoman Divacky 
1485f22ef01cSRoman Divacky   // FIXME: If we have a volatile struct, the optimizer can remove what might
1486f22ef01cSRoman Divacky   // appear to be `extra' memory ops:
1487f22ef01cSRoman Divacky   //
1488f22ef01cSRoman Divacky   // volatile struct { int i; } a, b;
1489f22ef01cSRoman Divacky   //
1490f22ef01cSRoman Divacky   // int main() {
1491f22ef01cSRoman Divacky   //   a = b;
1492f22ef01cSRoman Divacky   //   a = b;
1493f22ef01cSRoman Divacky   // }
1494f22ef01cSRoman Divacky   //
1495f22ef01cSRoman Divacky   // we need to use a different call here.  We use isVolatile to indicate when
1496f22ef01cSRoman Divacky   // either the source or the destination is volatile.
1497f22ef01cSRoman Divacky 
14986122f3e6SDimitry Andric   llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
14996122f3e6SDimitry Andric   llvm::Type *DBP =
15002754fe60SDimitry Andric     llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace());
15016122f3e6SDimitry Andric   DestPtr = Builder.CreateBitCast(DestPtr, DBP);
1502f22ef01cSRoman Divacky 
15036122f3e6SDimitry Andric   llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
15046122f3e6SDimitry Andric   llvm::Type *SBP =
15052754fe60SDimitry Andric     llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace());
15066122f3e6SDimitry Andric   SrcPtr = Builder.CreateBitCast(SrcPtr, SBP);
1507f22ef01cSRoman Divacky 
150817a519f9SDimitry Andric   // Don't do any of the memmove_collectable tests if GC isn't set.
1509dff0c46cSDimitry Andric   if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
151017a519f9SDimitry Andric     // fall through
151117a519f9SDimitry Andric   } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1512ffd1746dSEd Schouten     RecordDecl *Record = RecordTy->getDecl();
1513ffd1746dSEd Schouten     if (Record->hasObjectMember()) {
1514ffd1746dSEd Schouten       CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1515ffd1746dSEd Schouten                                                     SizeVal);
1516ffd1746dSEd Schouten       return;
1517ffd1746dSEd Schouten     }
151817a519f9SDimitry Andric   } else if (Ty->isArrayType()) {
1519ffd1746dSEd Schouten     QualType BaseType = getContext().getBaseElementType(Ty);
1520ffd1746dSEd Schouten     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
1521ffd1746dSEd Schouten       if (RecordTy->getDecl()->hasObjectMember()) {
1522ffd1746dSEd Schouten         CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1523ffd1746dSEd Schouten                                                       SizeVal);
1524ffd1746dSEd Schouten         return;
1525ffd1746dSEd Schouten       }
1526ffd1746dSEd Schouten     }
1527ffd1746dSEd Schouten   }
1528ffd1746dSEd Schouten 
15293861d79fSDimitry Andric   // Determine the metadata to describe the position of any padding in this
15303861d79fSDimitry Andric   // memcpy, as well as the TBAA tags for the members of the struct, in case
15313861d79fSDimitry Andric   // the optimizer wishes to expand it in to scalar memory operations.
15323861d79fSDimitry Andric   llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty);
15333861d79fSDimitry Andric 
153433956c43SDimitry Andric   Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, alignment.getQuantity(),
153533956c43SDimitry Andric                        isVolatile, /*TBAATag=*/nullptr, TBAAStructTag);
1536dff0c46cSDimitry Andric }
1537