17a51313dSChris Lattner //===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===//
27a51313dSChris Lattner //
37a51313dSChris Lattner //                     The LLVM Compiler Infrastructure
47a51313dSChris Lattner //
57a51313dSChris Lattner // This file is distributed under the University of Illinois Open Source
67a51313dSChris Lattner // License. See LICENSE.TXT for details.
77a51313dSChris Lattner //
87a51313dSChris Lattner //===----------------------------------------------------------------------===//
97a51313dSChris Lattner //
107a51313dSChris Lattner // This contains code to emit Aggregate Expr nodes as LLVM code.
117a51313dSChris Lattner //
127a51313dSChris Lattner //===----------------------------------------------------------------------===//
137a51313dSChris Lattner 
147a51313dSChris Lattner #include "CodeGenFunction.h"
155f21d2f6SFariborz Jahanian #include "CGObjCRuntime.h"
163a02247dSChandler Carruth #include "CodeGenModule.h"
17e0ef348cSIvan A. Kosarev #include "ConstantEmitter.h"
18ad319a73SDaniel Dunbar #include "clang/AST/ASTContext.h"
19b7f8f594SAnders Carlsson #include "clang/AST/DeclCXX.h"
20c83ed824SSebastian Redl #include "clang/AST/DeclTemplate.h"
21ad319a73SDaniel Dunbar #include "clang/AST/StmtVisitor.h"
22ffd5551bSChandler Carruth #include "llvm/IR/Constants.h"
23ffd5551bSChandler Carruth #include "llvm/IR/Function.h"
24ffd5551bSChandler Carruth #include "llvm/IR/GlobalVariable.h"
25ffd5551bSChandler Carruth #include "llvm/IR/Intrinsics.h"
267a51313dSChris Lattner using namespace clang;
277a51313dSChris Lattner using namespace CodeGen;
287a51313dSChris Lattner 
297a51313dSChris Lattner //===----------------------------------------------------------------------===//
307a51313dSChris Lattner //                        Aggregate Expression Emitter
317a51313dSChris Lattner //===----------------------------------------------------------------------===//
327a51313dSChris Lattner 
337a51313dSChris Lattner namespace  {
34337e3a5fSBenjamin Kramer class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
357a51313dSChris Lattner   CodeGenFunction &CGF;
36cb463859SDaniel Dunbar   CGBuilderTy &Builder;
377a626f63SJohn McCall   AggValueSlot Dest;
386aab1117SLeny Kholodov   bool IsResultUnused;
3978a15113SJohn McCall 
40a5efa738SJohn McCall   /// We want to use 'dest' as the return slot except under two
41a5efa738SJohn McCall   /// conditions:
42a5efa738SJohn McCall   ///   - The destination slot requires garbage collection, so we
43a5efa738SJohn McCall   ///     need to use the GC API.
44a5efa738SJohn McCall   ///   - The destination slot is potentially aliased.
45a5efa738SJohn McCall   bool shouldUseDestForReturnSlot() const {
46a5efa738SJohn McCall     return !(Dest.requiresGCollection() || Dest.isPotentiallyAliased());
47a5efa738SJohn McCall   }
48a5efa738SJohn McCall 
4978a15113SJohn McCall   ReturnValueSlot getReturnValueSlot() const {
50a5efa738SJohn McCall     if (!shouldUseDestForReturnSlot())
51a5efa738SJohn McCall       return ReturnValueSlot();
52cc04e9f6SJohn McCall 
537f416cc4SJohn McCall     return ReturnValueSlot(Dest.getAddress(), Dest.isVolatile(),
547f416cc4SJohn McCall                            IsResultUnused);
557a626f63SJohn McCall   }
567a626f63SJohn McCall 
577a626f63SJohn McCall   AggValueSlot EnsureSlot(QualType T) {
587a626f63SJohn McCall     if (!Dest.isIgnored()) return Dest;
597a626f63SJohn McCall     return CGF.CreateAggTemp(T, "agg.tmp.ensured");
6078a15113SJohn McCall   }
614e8ca4faSJohn McCall   void EnsureDest(QualType T) {
624e8ca4faSJohn McCall     if (!Dest.isIgnored()) return;
634e8ca4faSJohn McCall     Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured");
644e8ca4faSJohn McCall   }
65cc04e9f6SJohn McCall 
667a51313dSChris Lattner public:
676aab1117SLeny Kholodov   AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest, bool IsResultUnused)
686aab1117SLeny Kholodov     : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
696aab1117SLeny Kholodov     IsResultUnused(IsResultUnused) { }
707a51313dSChris Lattner 
717a51313dSChris Lattner   //===--------------------------------------------------------------------===//
727a51313dSChris Lattner   //                               Utilities
737a51313dSChris Lattner   //===--------------------------------------------------------------------===//
747a51313dSChris Lattner 
757a51313dSChris Lattner   /// EmitAggLoadOfLValue - Given an expression with aggregate type that
767a51313dSChris Lattner   /// represents a value lvalue, this method emits the address of the lvalue,
777a51313dSChris Lattner   /// then loads the result into DestPtr.
787a51313dSChris Lattner   void EmitAggLoadOfLValue(const Expr *E);
797a51313dSChris Lattner 
80*7275da0fSAkira Hatanaka   enum ExprValueKind {
81*7275da0fSAkira Hatanaka     EVK_RValue,
82*7275da0fSAkira Hatanaka     EVK_NonRValue
83*7275da0fSAkira Hatanaka   };
84*7275da0fSAkira Hatanaka 
85ca9fc09cSMike Stump   /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
86*7275da0fSAkira Hatanaka   /// SrcIsRValue is true if source comes from an RValue.
87*7275da0fSAkira Hatanaka   void EmitFinalDestCopy(QualType type, const LValue &src,
88*7275da0fSAkira Hatanaka                          ExprValueKind SrcValueKind = EVK_NonRValue);
897f416cc4SJohn McCall   void EmitFinalDestCopy(QualType type, RValue src);
904e8ca4faSJohn McCall   void EmitCopy(QualType type, const AggValueSlot &dest,
914e8ca4faSJohn McCall                 const AggValueSlot &src);
92ca9fc09cSMike Stump 
93a5efa738SJohn McCall   void EmitMoveFromReturnSlot(const Expr *E, RValue Src);
94cc04e9f6SJohn McCall 
957f416cc4SJohn McCall   void EmitArrayInit(Address DestPtr, llvm::ArrayType *AType,
96e0ef348cSIvan A. Kosarev                      QualType ArrayQTy, InitListExpr *E);
97c83ed824SSebastian Redl 
988d6fc958SJohn McCall   AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
99bbafb8a7SDavid Blaikie     if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))
1008d6fc958SJohn McCall       return AggValueSlot::NeedsGCBarriers;
1018d6fc958SJohn McCall     return AggValueSlot::DoesNotNeedGCBarriers;
1028d6fc958SJohn McCall   }
1038d6fc958SJohn McCall 
104cc04e9f6SJohn McCall   bool TypeRequiresGCollection(QualType T);
105cc04e9f6SJohn McCall 
1067a51313dSChris Lattner   //===--------------------------------------------------------------------===//
1077a51313dSChris Lattner   //                            Visitor Methods
1087a51313dSChris Lattner   //===--------------------------------------------------------------------===//
1097a51313dSChris Lattner 
11001fb5fb1SDavid Blaikie   void Visit(Expr *E) {
1119b479666SDavid Blaikie     ApplyDebugLocation DL(CGF, E);
11201fb5fb1SDavid Blaikie     StmtVisitor<AggExprEmitter>::Visit(E);
11301fb5fb1SDavid Blaikie   }
11401fb5fb1SDavid Blaikie 
1157a51313dSChris Lattner   void VisitStmt(Stmt *S) {
116a7c8cf62SDaniel Dunbar     CGF.ErrorUnsupported(S, "aggregate expression");
1177a51313dSChris Lattner   }
1187a51313dSChris Lattner   void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
11991147596SPeter Collingbourne   void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
12091147596SPeter Collingbourne     Visit(GE->getResultExpr());
12191147596SPeter Collingbourne   }
1225eb58583SGor Nishanov   void VisitCoawaitExpr(CoawaitExpr *E) {
1235eb58583SGor Nishanov     CGF.EmitCoawaitExpr(*E, Dest, IsResultUnused);
1245eb58583SGor Nishanov   }
1255eb58583SGor Nishanov   void VisitCoyieldExpr(CoyieldExpr *E) {
1265eb58583SGor Nishanov     CGF.EmitCoyieldExpr(*E, Dest, IsResultUnused);
1275eb58583SGor Nishanov   }
1285eb58583SGor Nishanov   void VisitUnaryCoawait(UnaryOperator *E) { Visit(E->getSubExpr()); }
1293f66b84cSEli Friedman   void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
1307c454bb8SJohn McCall   void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
1317c454bb8SJohn McCall     return Visit(E->getReplacement());
1327c454bb8SJohn McCall   }
1337a51313dSChris Lattner 
1347a51313dSChris Lattner   // l-values.
1356cc8317cSAlex Lorenz   void VisitDeclRefExpr(DeclRefExpr *E) { EmitAggLoadOfLValue(E); }
1367a51313dSChris Lattner   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
1377a51313dSChris Lattner   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
138d443c0a0SDaniel Dunbar   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
1399b71f0cfSDouglas Gregor   void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
1407a51313dSChris Lattner   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
1417a51313dSChris Lattner     EmitAggLoadOfLValue(E);
1427a51313dSChris Lattner   }
1432f343dd5SChris Lattner   void VisitPredefinedExpr(const PredefinedExpr *E) {
1442f343dd5SChris Lattner     EmitAggLoadOfLValue(E);
1452f343dd5SChris Lattner   }
146bc7d67ceSMike Stump 
1477a51313dSChris Lattner   // Operators.
148ec143777SAnders Carlsson   void VisitCastExpr(CastExpr *E);
1497a51313dSChris Lattner   void VisitCallExpr(const CallExpr *E);
1507a51313dSChris Lattner   void VisitStmtExpr(const StmtExpr *E);
1517a51313dSChris Lattner   void VisitBinaryOperator(const BinaryOperator *BO);
152ffba662dSFariborz Jahanian   void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
1537a51313dSChris Lattner   void VisitBinAssign(const BinaryOperator *E);
1544b0e2a30SEli Friedman   void VisitBinComma(const BinaryOperator *E);
1557a51313dSChris Lattner 
156b1d329daSChris Lattner   void VisitObjCMessageExpr(ObjCMessageExpr *E);
157c8317a44SDaniel Dunbar   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
158c8317a44SDaniel Dunbar     EmitAggLoadOfLValue(E);
159c8317a44SDaniel Dunbar   }
1607a51313dSChris Lattner 
161cb77930dSYunzhong Gao   void VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E);
162c07a0c7eSJohn McCall   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
1635b2095ceSAnders Carlsson   void VisitChooseExpr(const ChooseExpr *CE);
1647a51313dSChris Lattner   void VisitInitListExpr(InitListExpr *E);
165939b6880SRichard Smith   void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
166939b6880SRichard Smith                               llvm::Value *outerBegin = nullptr);
16718ada985SAnders Carlsson   void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
168cb77930dSYunzhong Gao   void VisitNoInitExpr(NoInitExpr *E) { } // Do nothing.
169aa9c7aedSChris Lattner   void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
170aa9c7aedSChris Lattner     Visit(DAE->getExpr());
171aa9c7aedSChris Lattner   }
172852c9db7SRichard Smith   void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
173852c9db7SRichard Smith     CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
174852c9db7SRichard Smith     Visit(DIE->getExpr());
175852c9db7SRichard Smith   }
1763be22e27SAnders Carlsson   void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
1771619a504SAnders Carlsson   void VisitCXXConstructExpr(const CXXConstructExpr *E);
1785179eb78SRichard Smith   void VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
179c370a7eeSEli Friedman   void VisitLambdaExpr(LambdaExpr *E);
180cc1b96d3SRichard Smith   void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
1815d413781SJohn McCall   void VisitExprWithCleanups(ExprWithCleanups *E);
182747eb784SDouglas Gregor   void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
1835bbbb137SMike Stump   void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
184fe31481fSDouglas Gregor   void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
1851bf5846aSJohn McCall   void VisitOpaqueValueExpr(OpaqueValueExpr *E);
1861bf5846aSJohn McCall 
187fe96e0b6SJohn McCall   void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
188fe96e0b6SJohn McCall     if (E->isGLValue()) {
189fe96e0b6SJohn McCall       LValue LV = CGF.EmitPseudoObjectLValue(E);
1904e8ca4faSJohn McCall       return EmitFinalDestCopy(E->getType(), LV);
191fe96e0b6SJohn McCall     }
192fe96e0b6SJohn McCall 
193fe96e0b6SJohn McCall     CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
194fe96e0b6SJohn McCall   }
195fe96e0b6SJohn McCall 
19621911e89SEli Friedman   void VisitVAArgExpr(VAArgExpr *E);
197579a05d7SChris Lattner 
198615ed1a3SChad Rosier   void EmitInitializationToLValue(Expr *E, LValue Address);
1991553b190SJohn McCall   void EmitNullInitializationToLValue(LValue Address);
2007a51313dSChris Lattner   //  case Expr::ChooseExprClass:
201f16b8c30SMike Stump   void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
202df14b3a8SEli Friedman   void VisitAtomicExpr(AtomicExpr *E) {
203cc2a6e06STim Northover     RValue Res = CGF.EmitAtomicExpr(E);
204cc2a6e06STim Northover     EmitFinalDestCopy(E->getType(), Res);
205df14b3a8SEli Friedman   }
2067a51313dSChris Lattner };
2077a51313dSChris Lattner }  // end anonymous namespace.
2087a51313dSChris Lattner 
2097a51313dSChris Lattner //===----------------------------------------------------------------------===//
2107a51313dSChris Lattner //                                Utilities
2117a51313dSChris Lattner //===----------------------------------------------------------------------===//
2127a51313dSChris Lattner 
2137a51313dSChris Lattner /// EmitAggLoadOfLValue - Given an expression with aggregate type that
2147a51313dSChris Lattner /// represents a value lvalue, this method emits the address of the lvalue,
2157a51313dSChris Lattner /// then loads the result into DestPtr.
2167a51313dSChris Lattner void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
2177a51313dSChris Lattner   LValue LV = CGF.EmitLValue(E);
218a8ec7eb9SJohn McCall 
219a8ec7eb9SJohn McCall   // If the type of the l-value is atomic, then do an atomic load.
220a5b195a1SDavid Majnemer   if (LV.getType()->isAtomicType() || CGF.LValueIsSuitableForInlineAtomic(LV)) {
2212d84e842SNick Lewycky     CGF.EmitAtomicLoad(LV, E->getExprLoc(), Dest);
222a8ec7eb9SJohn McCall     return;
223a8ec7eb9SJohn McCall   }
224a8ec7eb9SJohn McCall 
2254e8ca4faSJohn McCall   EmitFinalDestCopy(E->getType(), LV);
226ca9fc09cSMike Stump }
227ca9fc09cSMike Stump 
228cc04e9f6SJohn McCall /// \brief True if the given aggregate type requires special GC API calls.
229cc04e9f6SJohn McCall bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
230cc04e9f6SJohn McCall   // Only record types have members that might require garbage collection.
231cc04e9f6SJohn McCall   const RecordType *RecordTy = T->getAs<RecordType>();
232cc04e9f6SJohn McCall   if (!RecordTy) return false;
233cc04e9f6SJohn McCall 
234cc04e9f6SJohn McCall   // Don't mess with non-trivial C++ types.
235cc04e9f6SJohn McCall   RecordDecl *Record = RecordTy->getDecl();
236cc04e9f6SJohn McCall   if (isa<CXXRecordDecl>(Record) &&
23716488472SRichard Smith       (cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() ||
238cc04e9f6SJohn McCall        !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
239cc04e9f6SJohn McCall     return false;
240cc04e9f6SJohn McCall 
241cc04e9f6SJohn McCall   // Check whether the type has an object member.
242cc04e9f6SJohn McCall   return Record->hasObjectMember();
243cc04e9f6SJohn McCall }
244cc04e9f6SJohn McCall 
245a5efa738SJohn McCall /// \brief Perform the final move to DestPtr if for some reason
246a5efa738SJohn McCall /// getReturnValueSlot() didn't use it directly.
247cc04e9f6SJohn McCall ///
248cc04e9f6SJohn McCall /// The idea is that you do something like this:
249cc04e9f6SJohn McCall ///   RValue Result = EmitSomething(..., getReturnValueSlot());
250a5efa738SJohn McCall ///   EmitMoveFromReturnSlot(E, Result);
251a5efa738SJohn McCall ///
252a5efa738SJohn McCall /// If nothing interferes, this will cause the result to be emitted
253a5efa738SJohn McCall /// directly into the return value slot.  Otherwise, a final move
254a5efa738SJohn McCall /// will be performed.
2554e8ca4faSJohn McCall void AggExprEmitter::EmitMoveFromReturnSlot(const Expr *E, RValue src) {
256*7275da0fSAkira Hatanaka   // Push destructor if the result is ignored and the type is a C struct that
257*7275da0fSAkira Hatanaka   // is non-trivial to destroy.
258*7275da0fSAkira Hatanaka   QualType Ty = E->getType();
259*7275da0fSAkira Hatanaka   if (Dest.isIgnored() &&
260*7275da0fSAkira Hatanaka       Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
261*7275da0fSAkira Hatanaka     CGF.pushDestroy(Ty.isDestructedType(), src.getAggregateAddress(), Ty);
262*7275da0fSAkira Hatanaka 
263a5efa738SJohn McCall   if (shouldUseDestForReturnSlot()) {
264a5efa738SJohn McCall     // Logically, Dest.getAddr() should equal Src.getAggregateAddr().
265a5efa738SJohn McCall     // The possibility of undef rvalues complicates that a lot,
266a5efa738SJohn McCall     // though, so we can't really assert.
267a5efa738SJohn McCall     return;
268021510e9SFariborz Jahanian   }
269a5efa738SJohn McCall 
2704e8ca4faSJohn McCall   // Otherwise, copy from there to the destination.
2717f416cc4SJohn McCall   assert(Dest.getPointer() != src.getAggregatePointer());
2727f416cc4SJohn McCall   EmitFinalDestCopy(E->getType(), src);
273cc04e9f6SJohn McCall }
274cc04e9f6SJohn McCall 
275ca9fc09cSMike Stump /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
2767f416cc4SJohn McCall void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src) {
2774e8ca4faSJohn McCall   assert(src.isAggregate() && "value must be aggregate value!");
2787f416cc4SJohn McCall   LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddress(), type);
279*7275da0fSAkira Hatanaka   EmitFinalDestCopy(type, srcLV, EVK_RValue);
2804e8ca4faSJohn McCall }
2817a51313dSChris Lattner 
2824e8ca4faSJohn McCall /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
283*7275da0fSAkira Hatanaka void AggExprEmitter::EmitFinalDestCopy(QualType type, const LValue &src,
284*7275da0fSAkira Hatanaka                                        ExprValueKind SrcValueKind) {
2857a626f63SJohn McCall   // If Dest is ignored, then we're evaluating an aggregate expression
2864e8ca4faSJohn McCall   // in a context that doesn't care about the result.  Note that loads
2874e8ca4faSJohn McCall   // from volatile l-values force the existence of a non-ignored
2884e8ca4faSJohn McCall   // destination.
2894e8ca4faSJohn McCall   if (Dest.isIgnored())
290ec3cbfe8SMike Stump     return;
291c123623dSFariborz Jahanian 
292*7275da0fSAkira Hatanaka   // Copy non-trivial C structs here.
293*7275da0fSAkira Hatanaka   LValue DstLV = CGF.MakeAddrLValue(
294*7275da0fSAkira Hatanaka       Dest.getAddress(), Dest.isVolatile() ? type.withVolatile() : type);
295*7275da0fSAkira Hatanaka 
296*7275da0fSAkira Hatanaka   if (SrcValueKind == EVK_RValue) {
297*7275da0fSAkira Hatanaka     if (type.isNonTrivialToPrimitiveDestructiveMove() == QualType::PCK_Struct) {
298*7275da0fSAkira Hatanaka       if (Dest.isPotentiallyAliased())
299*7275da0fSAkira Hatanaka         CGF.callCStructMoveAssignmentOperator(DstLV, src);
300*7275da0fSAkira Hatanaka       else
301*7275da0fSAkira Hatanaka         CGF.callCStructMoveConstructor(DstLV, src);
302*7275da0fSAkira Hatanaka       return;
303*7275da0fSAkira Hatanaka     }
304*7275da0fSAkira Hatanaka   } else {
305*7275da0fSAkira Hatanaka     if (type.isNonTrivialToPrimitiveCopy() == QualType::PCK_Struct) {
306*7275da0fSAkira Hatanaka       if (Dest.isPotentiallyAliased())
307*7275da0fSAkira Hatanaka         CGF.callCStructCopyAssignmentOperator(DstLV, src);
308*7275da0fSAkira Hatanaka       else
309*7275da0fSAkira Hatanaka         CGF.callCStructCopyConstructor(DstLV, src);
310*7275da0fSAkira Hatanaka       return;
311*7275da0fSAkira Hatanaka     }
312*7275da0fSAkira Hatanaka   }
313*7275da0fSAkira Hatanaka 
3144e8ca4faSJohn McCall   AggValueSlot srcAgg =
3154e8ca4faSJohn McCall     AggValueSlot::forLValue(src, AggValueSlot::IsDestructed,
3164e8ca4faSJohn McCall                             needsGC(type), AggValueSlot::IsAliased);
3174e8ca4faSJohn McCall   EmitCopy(type, Dest, srcAgg);
318332ec2ceSMike Stump }
3197a51313dSChris Lattner 
3204e8ca4faSJohn McCall /// Perform a copy from the source into the destination.
3214e8ca4faSJohn McCall ///
3224e8ca4faSJohn McCall /// \param type - the type of the aggregate being copied; qualifiers are
3234e8ca4faSJohn McCall ///   ignored
3244e8ca4faSJohn McCall void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,
3254e8ca4faSJohn McCall                               const AggValueSlot &src) {
3264e8ca4faSJohn McCall   if (dest.requiresGCollection()) {
3274e8ca4faSJohn McCall     CharUnits sz = CGF.getContext().getTypeSizeInChars(type);
3284e8ca4faSJohn McCall     llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());
329879d7266SFariborz Jahanian     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
3307f416cc4SJohn McCall                                                       dest.getAddress(),
3317f416cc4SJohn McCall                                                       src.getAddress(),
3324e8ca4faSJohn McCall                                                       size);
333879d7266SFariborz Jahanian     return;
334879d7266SFariborz Jahanian   }
3354e8ca4faSJohn McCall 
336ca9fc09cSMike Stump   // If the result of the assignment is used, copy the LHS there also.
3374e8ca4faSJohn McCall   // It's volatile if either side is.  Use the minimum alignment of
3384e8ca4faSJohn McCall   // the two sides.
3391860b520SIvan A. Kosarev   LValue DestLV = CGF.MakeAddrLValue(dest.getAddress(), type);
3401860b520SIvan A. Kosarev   LValue SrcLV = CGF.MakeAddrLValue(src.getAddress(), type);
3411860b520SIvan A. Kosarev   CGF.EmitAggregateCopy(DestLV, SrcLV, type,
3427f416cc4SJohn McCall                         dest.isVolatile() || src.isVolatile());
3437a51313dSChris Lattner }
3447a51313dSChris Lattner 
345c83ed824SSebastian Redl /// \brief Emit the initializer for a std::initializer_list initialized with a
346c83ed824SSebastian Redl /// real initializer list.
347cc1b96d3SRichard Smith void
348cc1b96d3SRichard Smith AggExprEmitter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
349cc1b96d3SRichard Smith   // Emit an array containing the elements.  The array is externally destructed
350cc1b96d3SRichard Smith   // if the std::initializer_list object is.
351cc1b96d3SRichard Smith   ASTContext &Ctx = CGF.getContext();
352cc1b96d3SRichard Smith   LValue Array = CGF.EmitLValue(E->getSubExpr());
353cc1b96d3SRichard Smith   assert(Array.isSimple() && "initializer_list array not a simple lvalue");
3547f416cc4SJohn McCall   Address ArrayPtr = Array.getAddress();
355c83ed824SSebastian Redl 
356cc1b96d3SRichard Smith   const ConstantArrayType *ArrayType =
357cc1b96d3SRichard Smith       Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
358cc1b96d3SRichard Smith   assert(ArrayType && "std::initializer_list constructed from non-array");
359c83ed824SSebastian Redl 
360cc1b96d3SRichard Smith   // FIXME: Perform the checks on the field types in SemaInit.
361cc1b96d3SRichard Smith   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
362cc1b96d3SRichard Smith   RecordDecl::field_iterator Field = Record->field_begin();
363cc1b96d3SRichard Smith   if (Field == Record->field_end()) {
364cc1b96d3SRichard Smith     CGF.ErrorUnsupported(E, "weird std::initializer_list");
365f2e0a307SSebastian Redl     return;
366c83ed824SSebastian Redl   }
367c83ed824SSebastian Redl 
368c83ed824SSebastian Redl   // Start pointer.
369cc1b96d3SRichard Smith   if (!Field->getType()->isPointerType() ||
370cc1b96d3SRichard Smith       !Ctx.hasSameType(Field->getType()->getPointeeType(),
371cc1b96d3SRichard Smith                        ArrayType->getElementType())) {
372cc1b96d3SRichard Smith     CGF.ErrorUnsupported(E, "weird std::initializer_list");
373f2e0a307SSebastian Redl     return;
374c83ed824SSebastian Redl   }
375c83ed824SSebastian Redl 
376cc1b96d3SRichard Smith   AggValueSlot Dest = EnsureSlot(E->getType());
3777f416cc4SJohn McCall   LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
378cc1b96d3SRichard Smith   LValue Start = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
379cc1b96d3SRichard Smith   llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0);
380cc1b96d3SRichard Smith   llvm::Value *IdxStart[] = { Zero, Zero };
381cc1b96d3SRichard Smith   llvm::Value *ArrayStart =
3827f416cc4SJohn McCall       Builder.CreateInBoundsGEP(ArrayPtr.getPointer(), IdxStart, "arraystart");
383cc1b96d3SRichard Smith   CGF.EmitStoreThroughLValue(RValue::get(ArrayStart), Start);
384cc1b96d3SRichard Smith   ++Field;
385cc1b96d3SRichard Smith 
386cc1b96d3SRichard Smith   if (Field == Record->field_end()) {
387cc1b96d3SRichard Smith     CGF.ErrorUnsupported(E, "weird std::initializer_list");
388f2e0a307SSebastian Redl     return;
389c83ed824SSebastian Redl   }
390cc1b96d3SRichard Smith 
391cc1b96d3SRichard Smith   llvm::Value *Size = Builder.getInt(ArrayType->getSize());
392cc1b96d3SRichard Smith   LValue EndOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
393cc1b96d3SRichard Smith   if (Field->getType()->isPointerType() &&
394cc1b96d3SRichard Smith       Ctx.hasSameType(Field->getType()->getPointeeType(),
395cc1b96d3SRichard Smith                       ArrayType->getElementType())) {
396c83ed824SSebastian Redl     // End pointer.
397cc1b96d3SRichard Smith     llvm::Value *IdxEnd[] = { Zero, Size };
398cc1b96d3SRichard Smith     llvm::Value *ArrayEnd =
3997f416cc4SJohn McCall         Builder.CreateInBoundsGEP(ArrayPtr.getPointer(), IdxEnd, "arrayend");
400cc1b96d3SRichard Smith     CGF.EmitStoreThroughLValue(RValue::get(ArrayEnd), EndOrLength);
401cc1b96d3SRichard Smith   } else if (Ctx.hasSameType(Field->getType(), Ctx.getSizeType())) {
402c83ed824SSebastian Redl     // Length.
403cc1b96d3SRichard Smith     CGF.EmitStoreThroughLValue(RValue::get(Size), EndOrLength);
404c83ed824SSebastian Redl   } else {
405cc1b96d3SRichard Smith     CGF.ErrorUnsupported(E, "weird std::initializer_list");
406f2e0a307SSebastian Redl     return;
407c83ed824SSebastian Redl   }
408c83ed824SSebastian Redl }
409c83ed824SSebastian Redl 
4108edda962SRichard Smith /// \brief Determine if E is a trivial array filler, that is, one that is
4118edda962SRichard Smith /// equivalent to zero-initialization.
4128edda962SRichard Smith static bool isTrivialFiller(Expr *E) {
4138edda962SRichard Smith   if (!E)
4148edda962SRichard Smith     return true;
4158edda962SRichard Smith 
4168edda962SRichard Smith   if (isa<ImplicitValueInitExpr>(E))
4178edda962SRichard Smith     return true;
4188edda962SRichard Smith 
4198edda962SRichard Smith   if (auto *ILE = dyn_cast<InitListExpr>(E)) {
4208edda962SRichard Smith     if (ILE->getNumInits())
4218edda962SRichard Smith       return false;
4228edda962SRichard Smith     return isTrivialFiller(ILE->getArrayFiller());
4238edda962SRichard Smith   }
4248edda962SRichard Smith 
4258edda962SRichard Smith   if (auto *Cons = dyn_cast_or_null<CXXConstructExpr>(E))
4268edda962SRichard Smith     return Cons->getConstructor()->isDefaultConstructor() &&
4278edda962SRichard Smith            Cons->getConstructor()->isTrivial();
4288edda962SRichard Smith 
4298edda962SRichard Smith   // FIXME: Are there other cases where we can avoid emitting an initializer?
4308edda962SRichard Smith   return false;
4318edda962SRichard Smith }
4328edda962SRichard Smith 
433c83ed824SSebastian Redl /// \brief Emit initialization of an array from an initializer list.
4347f416cc4SJohn McCall void AggExprEmitter::EmitArrayInit(Address DestPtr, llvm::ArrayType *AType,
435e0ef348cSIvan A. Kosarev                                    QualType ArrayQTy, InitListExpr *E) {
436c83ed824SSebastian Redl   uint64_t NumInitElements = E->getNumInits();
437c83ed824SSebastian Redl 
438c83ed824SSebastian Redl   uint64_t NumArrayElements = AType->getNumElements();
439c83ed824SSebastian Redl   assert(NumInitElements <= NumArrayElements);
440c83ed824SSebastian Redl 
441e0ef348cSIvan A. Kosarev   QualType elementType =
442e0ef348cSIvan A. Kosarev       CGF.getContext().getAsArrayType(ArrayQTy)->getElementType();
443e0ef348cSIvan A. Kosarev 
444c83ed824SSebastian Redl   // DestPtr is an array*.  Construct an elementType* by drilling
445c83ed824SSebastian Redl   // down a level.
446c83ed824SSebastian Redl   llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
447c83ed824SSebastian Redl   llvm::Value *indices[] = { zero, zero };
448c83ed824SSebastian Redl   llvm::Value *begin =
4497f416cc4SJohn McCall     Builder.CreateInBoundsGEP(DestPtr.getPointer(), indices, "arrayinit.begin");
4507f416cc4SJohn McCall 
4517f416cc4SJohn McCall   CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
4527f416cc4SJohn McCall   CharUnits elementAlign =
4537f416cc4SJohn McCall     DestPtr.getAlignment().alignmentOfArrayElement(elementSize);
454c83ed824SSebastian Redl 
455e0ef348cSIvan A. Kosarev   // Consider initializing the array by copying from a global. For this to be
456e0ef348cSIvan A. Kosarev   // more efficient than per-element initialization, the size of the elements
457e0ef348cSIvan A. Kosarev   // with explicit initializers should be large enough.
458e0ef348cSIvan A. Kosarev   if (NumInitElements * elementSize.getQuantity() > 16 &&
459e0ef348cSIvan A. Kosarev       elementType.isTriviallyCopyableType(CGF.getContext())) {
460e0ef348cSIvan A. Kosarev     CodeGen::CodeGenModule &CGM = CGF.CGM;
461e0ef348cSIvan A. Kosarev     ConstantEmitter Emitter(CGM);
462e0ef348cSIvan A. Kosarev     LangAS AS = ArrayQTy.getAddressSpace();
463e0ef348cSIvan A. Kosarev     if (llvm::Constant *C = Emitter.tryEmitForInitializer(E, AS, ArrayQTy)) {
464e0ef348cSIvan A. Kosarev       auto GV = new llvm::GlobalVariable(
465e0ef348cSIvan A. Kosarev           CGM.getModule(), C->getType(),
466e0ef348cSIvan A. Kosarev           CGM.isTypeConstant(ArrayQTy, /* ExcludeCtorDtor= */ true),
467e0ef348cSIvan A. Kosarev           llvm::GlobalValue::PrivateLinkage, C, "constinit",
468e0ef348cSIvan A. Kosarev           /* InsertBefore= */ nullptr, llvm::GlobalVariable::NotThreadLocal,
469e0ef348cSIvan A. Kosarev           CGM.getContext().getTargetAddressSpace(AS));
470e0ef348cSIvan A. Kosarev       Emitter.finalize(GV);
471e0ef348cSIvan A. Kosarev       CharUnits Align = CGM.getContext().getTypeAlignInChars(ArrayQTy);
472e0ef348cSIvan A. Kosarev       GV->setAlignment(Align.getQuantity());
473e0ef348cSIvan A. Kosarev       EmitFinalDestCopy(ArrayQTy, CGF.MakeAddrLValue(GV, ArrayQTy, Align));
474e0ef348cSIvan A. Kosarev       return;
475e0ef348cSIvan A. Kosarev     }
476e0ef348cSIvan A. Kosarev   }
477e0ef348cSIvan A. Kosarev 
478c83ed824SSebastian Redl   // Exception safety requires us to destroy all the
479c83ed824SSebastian Redl   // already-constructed members if an initializer throws.
480c83ed824SSebastian Redl   // For that, we'll need an EH cleanup.
481c83ed824SSebastian Redl   QualType::DestructionKind dtorKind = elementType.isDestructedType();
4827f416cc4SJohn McCall   Address endOfInit = Address::invalid();
483c83ed824SSebastian Redl   EHScopeStack::stable_iterator cleanup;
4848a13c418SCraig Topper   llvm::Instruction *cleanupDominator = nullptr;
485c83ed824SSebastian Redl   if (CGF.needsEHCleanup(dtorKind)) {
486c83ed824SSebastian Redl     // In principle we could tell the cleanup where we are more
487c83ed824SSebastian Redl     // directly, but the control flow can get so varied here that it
488c83ed824SSebastian Redl     // would actually be quite complex.  Therefore we go through an
489c83ed824SSebastian Redl     // alloca.
4907f416cc4SJohn McCall     endOfInit = CGF.CreateTempAlloca(begin->getType(), CGF.getPointerAlign(),
491c83ed824SSebastian Redl                                      "arrayinit.endOfInit");
492c83ed824SSebastian Redl     cleanupDominator = Builder.CreateStore(begin, endOfInit);
493c83ed824SSebastian Redl     CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
4947f416cc4SJohn McCall                                          elementAlign,
495c83ed824SSebastian Redl                                          CGF.getDestroyer(dtorKind));
496c83ed824SSebastian Redl     cleanup = CGF.EHStack.stable_begin();
497c83ed824SSebastian Redl 
498c83ed824SSebastian Redl   // Otherwise, remember that we didn't need a cleanup.
499c83ed824SSebastian Redl   } else {
500c83ed824SSebastian Redl     dtorKind = QualType::DK_none;
501c83ed824SSebastian Redl   }
502c83ed824SSebastian Redl 
503c83ed824SSebastian Redl   llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
504c83ed824SSebastian Redl 
505c83ed824SSebastian Redl   // The 'current element to initialize'.  The invariants on this
506c83ed824SSebastian Redl   // variable are complicated.  Essentially, after each iteration of
507c83ed824SSebastian Redl   // the loop, it points to the last initialized element, except
508c83ed824SSebastian Redl   // that it points to the beginning of the array before any
509c83ed824SSebastian Redl   // elements have been initialized.
510c83ed824SSebastian Redl   llvm::Value *element = begin;
511c83ed824SSebastian Redl 
512c83ed824SSebastian Redl   // Emit the explicit initializers.
513c83ed824SSebastian Redl   for (uint64_t i = 0; i != NumInitElements; ++i) {
514c83ed824SSebastian Redl     // Advance to the next element.
515c83ed824SSebastian Redl     if (i > 0) {
516c83ed824SSebastian Redl       element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element");
517c83ed824SSebastian Redl 
518c83ed824SSebastian Redl       // Tell the cleanup that it needs to destroy up to this
519c83ed824SSebastian Redl       // element.  TODO: some of these stores can be trivially
520c83ed824SSebastian Redl       // observed to be unnecessary.
5217f416cc4SJohn McCall       if (endOfInit.isValid()) Builder.CreateStore(element, endOfInit);
522c83ed824SSebastian Redl     }
523c83ed824SSebastian Redl 
5247f416cc4SJohn McCall     LValue elementLV =
5257f416cc4SJohn McCall       CGF.MakeAddrLValue(Address(element, elementAlign), elementType);
526615ed1a3SChad Rosier     EmitInitializationToLValue(E->getInit(i), elementLV);
527c83ed824SSebastian Redl   }
528c83ed824SSebastian Redl 
529c83ed824SSebastian Redl   // Check whether there's a non-trivial array-fill expression.
530c83ed824SSebastian Redl   Expr *filler = E->getArrayFiller();
5318edda962SRichard Smith   bool hasTrivialFiller = isTrivialFiller(filler);
532c83ed824SSebastian Redl 
533c83ed824SSebastian Redl   // Any remaining elements need to be zero-initialized, possibly
534c83ed824SSebastian Redl   // using the filler expression.  We can skip this if the we're
535c83ed824SSebastian Redl   // emitting to zeroed memory.
536c83ed824SSebastian Redl   if (NumInitElements != NumArrayElements &&
537c83ed824SSebastian Redl       !(Dest.isZeroed() && hasTrivialFiller &&
538c83ed824SSebastian Redl         CGF.getTypes().isZeroInitializable(elementType))) {
539c83ed824SSebastian Redl 
540c83ed824SSebastian Redl     // Use an actual loop.  This is basically
541c83ed824SSebastian Redl     //   do { *array++ = filler; } while (array != end);
542c83ed824SSebastian Redl 
543c83ed824SSebastian Redl     // Advance to the start of the rest of the array.
544c83ed824SSebastian Redl     if (NumInitElements) {
545c83ed824SSebastian Redl       element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start");
5467f416cc4SJohn McCall       if (endOfInit.isValid()) Builder.CreateStore(element, endOfInit);
547c83ed824SSebastian Redl     }
548c83ed824SSebastian Redl 
549c83ed824SSebastian Redl     // Compute the end of the array.
550c83ed824SSebastian Redl     llvm::Value *end = Builder.CreateInBoundsGEP(begin,
551c83ed824SSebastian Redl                       llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
552c83ed824SSebastian Redl                                                  "arrayinit.end");
553c83ed824SSebastian Redl 
554c83ed824SSebastian Redl     llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
555c83ed824SSebastian Redl     llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
556c83ed824SSebastian Redl 
557c83ed824SSebastian Redl     // Jump into the body.
558c83ed824SSebastian Redl     CGF.EmitBlock(bodyBB);
559c83ed824SSebastian Redl     llvm::PHINode *currentElement =
560c83ed824SSebastian Redl       Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
561c83ed824SSebastian Redl     currentElement->addIncoming(element, entryBB);
562c83ed824SSebastian Redl 
563c83ed824SSebastian Redl     // Emit the actual filler expression.
56472236372SRichard Smith     {
56572236372SRichard Smith       // C++1z [class.temporary]p5:
56672236372SRichard Smith       //   when a default constructor is called to initialize an element of
56772236372SRichard Smith       //   an array with no corresponding initializer [...] the destruction of
56872236372SRichard Smith       //   every temporary created in a default argument is sequenced before
56972236372SRichard Smith       //   the construction of the next array element, if any
57072236372SRichard Smith       CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
5717f416cc4SJohn McCall       LValue elementLV =
5727f416cc4SJohn McCall         CGF.MakeAddrLValue(Address(currentElement, elementAlign), elementType);
573c83ed824SSebastian Redl       if (filler)
574615ed1a3SChad Rosier         EmitInitializationToLValue(filler, elementLV);
575c83ed824SSebastian Redl       else
576c83ed824SSebastian Redl         EmitNullInitializationToLValue(elementLV);
57772236372SRichard Smith     }
578c83ed824SSebastian Redl 
579c83ed824SSebastian Redl     // Move on to the next element.
580c83ed824SSebastian Redl     llvm::Value *nextElement =
581c83ed824SSebastian Redl       Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
582c83ed824SSebastian Redl 
583c83ed824SSebastian Redl     // Tell the EH cleanup that we finished with the last element.
5847f416cc4SJohn McCall     if (endOfInit.isValid()) Builder.CreateStore(nextElement, endOfInit);
585c83ed824SSebastian Redl 
586c83ed824SSebastian Redl     // Leave the loop if we're done.
587c83ed824SSebastian Redl     llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
588c83ed824SSebastian Redl                                              "arrayinit.done");
589c83ed824SSebastian Redl     llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
590c83ed824SSebastian Redl     Builder.CreateCondBr(done, endBB, bodyBB);
591c83ed824SSebastian Redl     currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
592c83ed824SSebastian Redl 
593c83ed824SSebastian Redl     CGF.EmitBlock(endBB);
594c83ed824SSebastian Redl   }
595c83ed824SSebastian Redl 
596c83ed824SSebastian Redl   // Leave the partial-array cleanup if we entered one.
597c83ed824SSebastian Redl   if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator);
598c83ed824SSebastian Redl }
599c83ed824SSebastian Redl 
6007a51313dSChris Lattner //===----------------------------------------------------------------------===//
6017a51313dSChris Lattner //                            Visitor Methods
6027a51313dSChris Lattner //===----------------------------------------------------------------------===//
6037a51313dSChris Lattner 
604fe31481fSDouglas Gregor void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
605fe31481fSDouglas Gregor   Visit(E->GetTemporaryExpr());
606fe31481fSDouglas Gregor }
607fe31481fSDouglas Gregor 
6081bf5846aSJohn McCall void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
6094e8ca4faSJohn McCall   EmitFinalDestCopy(e->getType(), CGF.getOpaqueLValueMapping(e));
6101bf5846aSJohn McCall }
6111bf5846aSJohn McCall 
6129b71f0cfSDouglas Gregor void
6139b71f0cfSDouglas Gregor AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
614bea4c3d8SJohn McCall   if (Dest.isPotentiallyAliased() &&
615bea4c3d8SJohn McCall       E->getType().isPODType(CGF.getContext())) {
6166c9d31ebSDouglas Gregor     // For a POD type, just emit a load of the lvalue + a copy, because our
6176c9d31ebSDouglas Gregor     // compound literal might alias the destination.
6186c9d31ebSDouglas Gregor     EmitAggLoadOfLValue(E);
6196c9d31ebSDouglas Gregor     return;
6206c9d31ebSDouglas Gregor   }
6216c9d31ebSDouglas Gregor 
6229b71f0cfSDouglas Gregor   AggValueSlot Slot = EnsureSlot(E->getType());
6239b71f0cfSDouglas Gregor   CGF.EmitAggExpr(E->getInitializer(), Slot);
6249b71f0cfSDouglas Gregor }
6259b71f0cfSDouglas Gregor 
626a8ec7eb9SJohn McCall /// Attempt to look through various unimportant expressions to find a
627a8ec7eb9SJohn McCall /// cast of the given kind.
628a8ec7eb9SJohn McCall static Expr *findPeephole(Expr *op, CastKind kind) {
629a8ec7eb9SJohn McCall   while (true) {
630a8ec7eb9SJohn McCall     op = op->IgnoreParens();
631a8ec7eb9SJohn McCall     if (CastExpr *castE = dyn_cast<CastExpr>(op)) {
632a8ec7eb9SJohn McCall       if (castE->getCastKind() == kind)
633a8ec7eb9SJohn McCall         return castE->getSubExpr();
634a8ec7eb9SJohn McCall       if (castE->getCastKind() == CK_NoOp)
635a8ec7eb9SJohn McCall         continue;
636a8ec7eb9SJohn McCall     }
6378a13c418SCraig Topper     return nullptr;
638a8ec7eb9SJohn McCall   }
639a8ec7eb9SJohn McCall }
6409b71f0cfSDouglas Gregor 
641ec143777SAnders Carlsson void AggExprEmitter::VisitCastExpr(CastExpr *E) {
6422bf9b4c0SAlexey Bataev   if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
6432bf9b4c0SAlexey Bataev     CGF.CGM.EmitExplicitCastExprType(ECE, &CGF);
6441fb7ae9eSAnders Carlsson   switch (E->getCastKind()) {
6458a01a751SAnders Carlsson   case CK_Dynamic: {
64669d0d262SRichard Smith     // FIXME: Can this actually happen? We have no test coverage for it.
6471c073f47SDouglas Gregor     assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
64869d0d262SRichard Smith     LValue LV = CGF.EmitCheckedLValue(E->getSubExpr(),
6494d1458edSRichard Smith                                       CodeGenFunction::TCK_Load);
6501c073f47SDouglas Gregor     // FIXME: Do we also need to handle property references here?
6511c073f47SDouglas Gregor     if (LV.isSimple())
6521c073f47SDouglas Gregor       CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
6531c073f47SDouglas Gregor     else
6541c073f47SDouglas Gregor       CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
6551c073f47SDouglas Gregor 
6567a626f63SJohn McCall     if (!Dest.isIgnored())
6571c073f47SDouglas Gregor       CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
6581c073f47SDouglas Gregor     break;
6591c073f47SDouglas Gregor   }
6601c073f47SDouglas Gregor 
661e302792bSJohn McCall   case CK_ToUnion: {
662892bb0caSReid Kleckner     // Evaluate even if the destination is ignored.
663892bb0caSReid Kleckner     if (Dest.isIgnored()) {
664892bb0caSReid Kleckner       CGF.EmitAnyExpr(E->getSubExpr(), AggValueSlot::ignored(),
665892bb0caSReid Kleckner                       /*ignoreResult=*/true);
666892bb0caSReid Kleckner       break;
667892bb0caSReid Kleckner     }
66858989b71SJohn McCall 
6697ffcf93bSNuno Lopes     // GCC union extension
6702e442a00SDaniel Dunbar     QualType Ty = E->getSubExpr()->getType();
6717f416cc4SJohn McCall     Address CastPtr =
6727f416cc4SJohn McCall       Builder.CreateElementBitCast(Dest.getAddress(), CGF.ConvertType(Ty));
6731553b190SJohn McCall     EmitInitializationToLValue(E->getSubExpr(),
674615ed1a3SChad Rosier                                CGF.MakeAddrLValue(CastPtr, Ty));
6751fb7ae9eSAnders Carlsson     break;
6767ffcf93bSNuno Lopes   }
6777ffcf93bSNuno Lopes 
678e302792bSJohn McCall   case CK_DerivedToBase:
679e302792bSJohn McCall   case CK_BaseToDerived:
680e302792bSJohn McCall   case CK_UncheckedDerivedToBase: {
68183d382b1SDavid Blaikie     llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
682aae38d66SDouglas Gregor                 "should have been unpacked before we got here");
683aae38d66SDouglas Gregor   }
684aae38d66SDouglas Gregor 
685a8ec7eb9SJohn McCall   case CK_NonAtomicToAtomic:
686a8ec7eb9SJohn McCall   case CK_AtomicToNonAtomic: {
687a8ec7eb9SJohn McCall     bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);
688a8ec7eb9SJohn McCall 
689a8ec7eb9SJohn McCall     // Determine the atomic and value types.
690a8ec7eb9SJohn McCall     QualType atomicType = E->getSubExpr()->getType();
691a8ec7eb9SJohn McCall     QualType valueType = E->getType();
692a8ec7eb9SJohn McCall     if (isToAtomic) std::swap(atomicType, valueType);
693a8ec7eb9SJohn McCall 
694a8ec7eb9SJohn McCall     assert(atomicType->isAtomicType());
695a8ec7eb9SJohn McCall     assert(CGF.getContext().hasSameUnqualifiedType(valueType,
696a8ec7eb9SJohn McCall                           atomicType->castAs<AtomicType>()->getValueType()));
697a8ec7eb9SJohn McCall 
698a8ec7eb9SJohn McCall     // Just recurse normally if we're ignoring the result or the
699a8ec7eb9SJohn McCall     // atomic type doesn't change representation.
700a8ec7eb9SJohn McCall     if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {
701a8ec7eb9SJohn McCall       return Visit(E->getSubExpr());
702a8ec7eb9SJohn McCall     }
703a8ec7eb9SJohn McCall 
704a8ec7eb9SJohn McCall     CastKind peepholeTarget =
705a8ec7eb9SJohn McCall       (isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic);
706a8ec7eb9SJohn McCall 
707a8ec7eb9SJohn McCall     // These two cases are reverses of each other; try to peephole them.
708a8ec7eb9SJohn McCall     if (Expr *op = findPeephole(E->getSubExpr(), peepholeTarget)) {
709a8ec7eb9SJohn McCall       assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),
710a8ec7eb9SJohn McCall                                                      E->getType()) &&
711a8ec7eb9SJohn McCall            "peephole significantly changed types?");
712a8ec7eb9SJohn McCall       return Visit(op);
713a8ec7eb9SJohn McCall     }
714a8ec7eb9SJohn McCall 
715a8ec7eb9SJohn McCall     // If we're converting an r-value of non-atomic type to an r-value
716be4504dfSEli Friedman     // of atomic type, just emit directly into the relevant sub-object.
717a8ec7eb9SJohn McCall     if (isToAtomic) {
718be4504dfSEli Friedman       AggValueSlot valueDest = Dest;
719be4504dfSEli Friedman       if (!valueDest.isIgnored() && CGF.CGM.isPaddedAtomicType(atomicType)) {
720be4504dfSEli Friedman         // Zero-initialize.  (Strictly speaking, we only need to intialize
721be4504dfSEli Friedman         // the padding at the end, but this is simpler.)
722be4504dfSEli Friedman         if (!Dest.isZeroed())
7237f416cc4SJohn McCall           CGF.EmitNullInitialization(Dest.getAddress(), atomicType);
724be4504dfSEli Friedman 
725be4504dfSEli Friedman         // Build a GEP to refer to the subobject.
7267f416cc4SJohn McCall         Address valueAddr =
7277f416cc4SJohn McCall             CGF.Builder.CreateStructGEP(valueDest.getAddress(), 0,
7287f416cc4SJohn McCall                                         CharUnits());
729be4504dfSEli Friedman         valueDest = AggValueSlot::forAddr(valueAddr,
730be4504dfSEli Friedman                                           valueDest.getQualifiers(),
731be4504dfSEli Friedman                                           valueDest.isExternallyDestructed(),
732be4504dfSEli Friedman                                           valueDest.requiresGCollection(),
733be4504dfSEli Friedman                                           valueDest.isPotentiallyAliased(),
734be4504dfSEli Friedman                                           AggValueSlot::IsZeroed);
735be4504dfSEli Friedman       }
736be4504dfSEli Friedman 
737035b39e3SEli Friedman       CGF.EmitAggExpr(E->getSubExpr(), valueDest);
738a8ec7eb9SJohn McCall       return;
739a8ec7eb9SJohn McCall     }
740a8ec7eb9SJohn McCall 
741a8ec7eb9SJohn McCall     // Otherwise, we're converting an atomic type to a non-atomic type.
742be4504dfSEli Friedman     // Make an atomic temporary, emit into that, and then copy the value out.
743a8ec7eb9SJohn McCall     AggValueSlot atomicSlot =
744a8ec7eb9SJohn McCall       CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");
745a8ec7eb9SJohn McCall     CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
746a8ec7eb9SJohn McCall 
7477f416cc4SJohn McCall     Address valueAddr =
7487f416cc4SJohn McCall       Builder.CreateStructGEP(atomicSlot.getAddress(), 0, CharUnits());
749a8ec7eb9SJohn McCall     RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());
750a8ec7eb9SJohn McCall     return EmitFinalDestCopy(valueType, rvalue);
751a8ec7eb9SJohn McCall   }
752a8ec7eb9SJohn McCall 
7534e8ca4faSJohn McCall   case CK_LValueToRValue:
7544e8ca4faSJohn McCall     // If we're loading from a volatile type, force the destination
7554e8ca4faSJohn McCall     // into existence.
7564e8ca4faSJohn McCall     if (E->getSubExpr()->getType().isVolatileQualified()) {
7574e8ca4faSJohn McCall       EnsureDest(E->getType());
7584e8ca4faSJohn McCall       return Visit(E->getSubExpr());
7594e8ca4faSJohn McCall     }
760a8ec7eb9SJohn McCall 
761f3b3ccdaSAdrian Prantl     LLVM_FALLTHROUGH;
7624e8ca4faSJohn McCall 
763e302792bSJohn McCall   case CK_NoOp:
764e302792bSJohn McCall   case CK_UserDefinedConversion:
765e302792bSJohn McCall   case CK_ConstructorConversion:
7662a69547fSEli Friedman     assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
7672a69547fSEli Friedman                                                    E->getType()) &&
7680f398c44SChris Lattner            "Implicit cast types must be compatible");
7697a51313dSChris Lattner     Visit(E->getSubExpr());
7701fb7ae9eSAnders Carlsson     break;
771b05a3e55SAnders Carlsson 
772e302792bSJohn McCall   case CK_LValueBitCast:
773f3735e01SJohn McCall     llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
77431996343SJohn McCall 
775f3735e01SJohn McCall   case CK_Dependent:
776f3735e01SJohn McCall   case CK_BitCast:
777f3735e01SJohn McCall   case CK_ArrayToPointerDecay:
778f3735e01SJohn McCall   case CK_FunctionToPointerDecay:
779f3735e01SJohn McCall   case CK_NullToPointer:
780f3735e01SJohn McCall   case CK_NullToMemberPointer:
781f3735e01SJohn McCall   case CK_BaseToDerivedMemberPointer:
782f3735e01SJohn McCall   case CK_DerivedToBaseMemberPointer:
783f3735e01SJohn McCall   case CK_MemberPointerToBoolean:
784c62bb391SJohn McCall   case CK_ReinterpretMemberPointer:
785f3735e01SJohn McCall   case CK_IntegralToPointer:
786f3735e01SJohn McCall   case CK_PointerToIntegral:
787f3735e01SJohn McCall   case CK_PointerToBoolean:
788f3735e01SJohn McCall   case CK_ToVoid:
789f3735e01SJohn McCall   case CK_VectorSplat:
790f3735e01SJohn McCall   case CK_IntegralCast:
791df1ed009SGeorge Burgess IV   case CK_BooleanToSignedIntegral:
792f3735e01SJohn McCall   case CK_IntegralToBoolean:
793f3735e01SJohn McCall   case CK_IntegralToFloating:
794f3735e01SJohn McCall   case CK_FloatingToIntegral:
795f3735e01SJohn McCall   case CK_FloatingToBoolean:
796f3735e01SJohn McCall   case CK_FloatingCast:
7979320b87cSJohn McCall   case CK_CPointerToObjCPointerCast:
7989320b87cSJohn McCall   case CK_BlockPointerToObjCPointerCast:
799f3735e01SJohn McCall   case CK_AnyPointerToBlockPointerCast:
800f3735e01SJohn McCall   case CK_ObjCObjectLValueCast:
801f3735e01SJohn McCall   case CK_FloatingRealToComplex:
802f3735e01SJohn McCall   case CK_FloatingComplexToReal:
803f3735e01SJohn McCall   case CK_FloatingComplexToBoolean:
804f3735e01SJohn McCall   case CK_FloatingComplexCast:
805f3735e01SJohn McCall   case CK_FloatingComplexToIntegralComplex:
806f3735e01SJohn McCall   case CK_IntegralRealToComplex:
807f3735e01SJohn McCall   case CK_IntegralComplexToReal:
808f3735e01SJohn McCall   case CK_IntegralComplexToBoolean:
809f3735e01SJohn McCall   case CK_IntegralComplexCast:
810f3735e01SJohn McCall   case CK_IntegralComplexToFloatingComplex:
8112d637d2eSJohn McCall   case CK_ARCProduceObject:
8122d637d2eSJohn McCall   case CK_ARCConsumeObject:
8132d637d2eSJohn McCall   case CK_ARCReclaimReturnedObject:
8142d637d2eSJohn McCall   case CK_ARCExtendBlockObject:
815ed90df38SDouglas Gregor   case CK_CopyAndAutoreleaseBlockObject:
81634866c77SEli Friedman   case CK_BuiltinFnToFnPtr:
8171b4fb3e0SGuy Benyei   case CK_ZeroToOCLEvent:
81889831421SEgor Churaev   case CK_ZeroToOCLQueue:
819e1468322SDavid Tweed   case CK_AddressSpaceConversion:
8200bc4b2d3SYaxun Liu   case CK_IntToOCLSampler:
821f3735e01SJohn McCall     llvm_unreachable("cast kind invalid for aggregate types");
8221fb7ae9eSAnders Carlsson   }
8237a51313dSChris Lattner }
8247a51313dSChris Lattner 
8250f398c44SChris Lattner void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
826ced8bdf7SDavid Majnemer   if (E->getCallReturnType(CGF.getContext())->isReferenceType()) {
827ddcbfe7bSAnders Carlsson     EmitAggLoadOfLValue(E);
828ddcbfe7bSAnders Carlsson     return;
829ddcbfe7bSAnders Carlsson   }
830ddcbfe7bSAnders Carlsson 
831cc04e9f6SJohn McCall   RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
832a5efa738SJohn McCall   EmitMoveFromReturnSlot(E, RV);
8337a51313dSChris Lattner }
8340f398c44SChris Lattner 
8350f398c44SChris Lattner void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
836cc04e9f6SJohn McCall   RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
837a5efa738SJohn McCall   EmitMoveFromReturnSlot(E, RV);
838b1d329daSChris Lattner }
8397a51313dSChris Lattner 
8400f398c44SChris Lattner void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
841a2342eb8SJohn McCall   CGF.EmitIgnoredExpr(E->getLHS());
8427a626f63SJohn McCall   Visit(E->getRHS());
8434b0e2a30SEli Friedman }
8444b0e2a30SEli Friedman 
8457a51313dSChris Lattner void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
846ce1de617SJohn McCall   CodeGenFunction::StmtExprEvaluation eval(CGF);
8477a626f63SJohn McCall   CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
8487a51313dSChris Lattner }
8497a51313dSChris Lattner 
8507a51313dSChris Lattner void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
851e302792bSJohn McCall   if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
852ffba662dSFariborz Jahanian     VisitPointerToDataMemberBinaryOperator(E);
853ffba662dSFariborz Jahanian   else
854a7c8cf62SDaniel Dunbar     CGF.ErrorUnsupported(E, "aggregate binary expression");
8557a51313dSChris Lattner }
8567a51313dSChris Lattner 
857ffba662dSFariborz Jahanian void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
858ffba662dSFariborz Jahanian                                                     const BinaryOperator *E) {
859ffba662dSFariborz Jahanian   LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
8604e8ca4faSJohn McCall   EmitFinalDestCopy(E->getType(), LV);
8614e8ca4faSJohn McCall }
8624e8ca4faSJohn McCall 
8634e8ca4faSJohn McCall /// Is the value of the given expression possibly a reference to or
8644e8ca4faSJohn McCall /// into a __block variable?
8654e8ca4faSJohn McCall static bool isBlockVarRef(const Expr *E) {
8664e8ca4faSJohn McCall   // Make sure we look through parens.
8674e8ca4faSJohn McCall   E = E->IgnoreParens();
8684e8ca4faSJohn McCall 
8694e8ca4faSJohn McCall   // Check for a direct reference to a __block variable.
8704e8ca4faSJohn McCall   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8714e8ca4faSJohn McCall     const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8724e8ca4faSJohn McCall     return (var && var->hasAttr<BlocksAttr>());
8734e8ca4faSJohn McCall   }
8744e8ca4faSJohn McCall 
8754e8ca4faSJohn McCall   // More complicated stuff.
8764e8ca4faSJohn McCall 
8774e8ca4faSJohn McCall   // Binary operators.
8784e8ca4faSJohn McCall   if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {
8794e8ca4faSJohn McCall     // For an assignment or pointer-to-member operation, just care
8804e8ca4faSJohn McCall     // about the LHS.
8814e8ca4faSJohn McCall     if (op->isAssignmentOp() || op->isPtrMemOp())
8824e8ca4faSJohn McCall       return isBlockVarRef(op->getLHS());
8834e8ca4faSJohn McCall 
8844e8ca4faSJohn McCall     // For a comma, just care about the RHS.
8854e8ca4faSJohn McCall     if (op->getOpcode() == BO_Comma)
8864e8ca4faSJohn McCall       return isBlockVarRef(op->getRHS());
8874e8ca4faSJohn McCall 
8884e8ca4faSJohn McCall     // FIXME: pointer arithmetic?
8894e8ca4faSJohn McCall     return false;
8904e8ca4faSJohn McCall 
8914e8ca4faSJohn McCall   // Check both sides of a conditional operator.
8924e8ca4faSJohn McCall   } else if (const AbstractConditionalOperator *op
8934e8ca4faSJohn McCall                = dyn_cast<AbstractConditionalOperator>(E)) {
8944e8ca4faSJohn McCall     return isBlockVarRef(op->getTrueExpr())
8954e8ca4faSJohn McCall         || isBlockVarRef(op->getFalseExpr());
8964e8ca4faSJohn McCall 
8974e8ca4faSJohn McCall   // OVEs are required to support BinaryConditionalOperators.
8984e8ca4faSJohn McCall   } else if (const OpaqueValueExpr *op
8994e8ca4faSJohn McCall                = dyn_cast<OpaqueValueExpr>(E)) {
9004e8ca4faSJohn McCall     if (const Expr *src = op->getSourceExpr())
9014e8ca4faSJohn McCall       return isBlockVarRef(src);
9024e8ca4faSJohn McCall 
9034e8ca4faSJohn McCall   // Casts are necessary to get things like (*(int*)&var) = foo().
9044e8ca4faSJohn McCall   // We don't really care about the kind of cast here, except
9054e8ca4faSJohn McCall   // we don't want to look through l2r casts, because it's okay
9064e8ca4faSJohn McCall   // to get the *value* in a __block variable.
9074e8ca4faSJohn McCall   } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {
9084e8ca4faSJohn McCall     if (cast->getCastKind() == CK_LValueToRValue)
9094e8ca4faSJohn McCall       return false;
9104e8ca4faSJohn McCall     return isBlockVarRef(cast->getSubExpr());
9114e8ca4faSJohn McCall 
9124e8ca4faSJohn McCall   // Handle unary operators.  Again, just aggressively look through
9134e8ca4faSJohn McCall   // it, ignoring the operation.
9144e8ca4faSJohn McCall   } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {
9154e8ca4faSJohn McCall     return isBlockVarRef(uop->getSubExpr());
9164e8ca4faSJohn McCall 
9174e8ca4faSJohn McCall   // Look into the base of a field access.
9184e8ca4faSJohn McCall   } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
9194e8ca4faSJohn McCall     return isBlockVarRef(mem->getBase());
9204e8ca4faSJohn McCall 
9214e8ca4faSJohn McCall   // Look into the base of a subscript.
9224e8ca4faSJohn McCall   } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {
9234e8ca4faSJohn McCall     return isBlockVarRef(sub->getBase());
9244e8ca4faSJohn McCall   }
9254e8ca4faSJohn McCall 
9264e8ca4faSJohn McCall   return false;
927ffba662dSFariborz Jahanian }
928ffba662dSFariborz Jahanian 
9297a51313dSChris Lattner void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
9307a51313dSChris Lattner   // For an assignment to work, the value on the right has
9317a51313dSChris Lattner   // to be compatible with the value on the left.
9322a69547fSEli Friedman   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
9332a69547fSEli Friedman                                                  E->getRHS()->getType())
9347a51313dSChris Lattner          && "Invalid assignment");
935d0a30016SJohn McCall 
9364e8ca4faSJohn McCall   // If the LHS might be a __block variable, and the RHS can
9374e8ca4faSJohn McCall   // potentially cause a block copy, we need to evaluate the RHS first
9384e8ca4faSJohn McCall   // so that the assignment goes the right place.
9394e8ca4faSJohn McCall   // This is pretty semantically fragile.
9404e8ca4faSJohn McCall   if (isBlockVarRef(E->getLHS()) &&
94199514b91SFariborz Jahanian       E->getRHS()->HasSideEffects(CGF.getContext())) {
9424e8ca4faSJohn McCall     // Ensure that we have a destination, and evaluate the RHS into that.
9434e8ca4faSJohn McCall     EnsureDest(E->getRHS()->getType());
9444e8ca4faSJohn McCall     Visit(E->getRHS());
9454e8ca4faSJohn McCall 
9464e8ca4faSJohn McCall     // Now emit the LHS and copy into it.
947e30752c9SRichard Smith     LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
9484e8ca4faSJohn McCall 
949a8ec7eb9SJohn McCall     // That copy is an atomic copy if the LHS is atomic.
950a5b195a1SDavid Majnemer     if (LHS.getType()->isAtomicType() ||
951a5b195a1SDavid Majnemer         CGF.LValueIsSuitableForInlineAtomic(LHS)) {
952a8ec7eb9SJohn McCall       CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
953a8ec7eb9SJohn McCall       return;
954a8ec7eb9SJohn McCall     }
955a8ec7eb9SJohn McCall 
9564e8ca4faSJohn McCall     EmitCopy(E->getLHS()->getType(),
9574e8ca4faSJohn McCall              AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
95846759f4fSJohn McCall                                      needsGC(E->getLHS()->getType()),
9594e8ca4faSJohn McCall                                      AggValueSlot::IsAliased),
9604e8ca4faSJohn McCall              Dest);
96199514b91SFariborz Jahanian     return;
96299514b91SFariborz Jahanian   }
96399514b91SFariborz Jahanian 
9647a51313dSChris Lattner   LValue LHS = CGF.EmitLValue(E->getLHS());
9657a51313dSChris Lattner 
966a8ec7eb9SJohn McCall   // If we have an atomic type, evaluate into the destination and then
967a8ec7eb9SJohn McCall   // do an atomic copy.
968a5b195a1SDavid Majnemer   if (LHS.getType()->isAtomicType() ||
969a5b195a1SDavid Majnemer       CGF.LValueIsSuitableForInlineAtomic(LHS)) {
970a8ec7eb9SJohn McCall     EnsureDest(E->getRHS()->getType());
971a8ec7eb9SJohn McCall     Visit(E->getRHS());
972a8ec7eb9SJohn McCall     CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
973a8ec7eb9SJohn McCall     return;
974a8ec7eb9SJohn McCall   }
975a8ec7eb9SJohn McCall 
9767a51313dSChris Lattner   // Codegen the RHS so that it stores directly into the LHS.
9778d6fc958SJohn McCall   AggValueSlot LHSSlot =
9788d6fc958SJohn McCall     AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
97946759f4fSJohn McCall                             needsGC(E->getLHS()->getType()),
980615ed1a3SChad Rosier                             AggValueSlot::IsAliased);
9817865220dSFariborz Jahanian   // A non-volatile aggregate destination might have volatile member.
9827865220dSFariborz Jahanian   if (!LHSSlot.isVolatile() &&
9837865220dSFariborz Jahanian       CGF.hasVolatileMember(E->getLHS()->getType()))
9847865220dSFariborz Jahanian     LHSSlot.setVolatile(true);
9857865220dSFariborz Jahanian 
9864e8ca4faSJohn McCall   CGF.EmitAggExpr(E->getRHS(), LHSSlot);
9874e8ca4faSJohn McCall 
9884e8ca4faSJohn McCall   // Copy into the destination if the assignment isn't ignored.
9894e8ca4faSJohn McCall   EmitFinalDestCopy(E->getType(), LHS);
9907a51313dSChris Lattner }
9917a51313dSChris Lattner 
992c07a0c7eSJohn McCall void AggExprEmitter::
993c07a0c7eSJohn McCall VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
994a612e79bSDaniel Dunbar   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
995a612e79bSDaniel Dunbar   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
996a612e79bSDaniel Dunbar   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
9977a51313dSChris Lattner 
998c07a0c7eSJohn McCall   // Bind the common expression if necessary.
99948fd89adSEli Friedman   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
1000c07a0c7eSJohn McCall 
1001ce1de617SJohn McCall   CodeGenFunction::ConditionalEvaluation eval(CGF);
100266242d6cSJustin Bogner   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock,
100366242d6cSJustin Bogner                            CGF.getProfileCount(E));
10047a51313dSChris Lattner 
10055b26f65bSJohn McCall   // Save whether the destination's lifetime is externally managed.
1006cac93853SJohn McCall   bool isExternallyDestructed = Dest.isExternallyDestructed();
10077a51313dSChris Lattner 
1008ce1de617SJohn McCall   eval.begin(CGF);
1009ce1de617SJohn McCall   CGF.EmitBlock(LHSBlock);
101066242d6cSJustin Bogner   CGF.incrementProfileCounter(E);
1011c07a0c7eSJohn McCall   Visit(E->getTrueExpr());
1012ce1de617SJohn McCall   eval.end(CGF);
10137a51313dSChris Lattner 
1014ce1de617SJohn McCall   assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
1015ce1de617SJohn McCall   CGF.Builder.CreateBr(ContBlock);
10167a51313dSChris Lattner 
10175b26f65bSJohn McCall   // If the result of an agg expression is unused, then the emission
10185b26f65bSJohn McCall   // of the LHS might need to create a destination slot.  That's fine
10195b26f65bSJohn McCall   // with us, and we can safely emit the RHS into the same slot, but
1020cac93853SJohn McCall   // we shouldn't claim that it's already being destructed.
1021cac93853SJohn McCall   Dest.setExternallyDestructed(isExternallyDestructed);
10225b26f65bSJohn McCall 
1023ce1de617SJohn McCall   eval.begin(CGF);
1024ce1de617SJohn McCall   CGF.EmitBlock(RHSBlock);
1025c07a0c7eSJohn McCall   Visit(E->getFalseExpr());
1026ce1de617SJohn McCall   eval.end(CGF);
10277a51313dSChris Lattner 
10287a51313dSChris Lattner   CGF.EmitBlock(ContBlock);
10297a51313dSChris Lattner }
10307a51313dSChris Lattner 
10315b2095ceSAnders Carlsson void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
103275807f23SEli Friedman   Visit(CE->getChosenSubExpr());
10335b2095ceSAnders Carlsson }
10345b2095ceSAnders Carlsson 
103521911e89SEli Friedman void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
1036c7d5c94fSCharles Davis   Address ArgValue = Address::invalid();
1037c7d5c94fSCharles Davis   Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
103813abd7e9SAnders Carlsson 
103929b5f086SJames Y Knight   // If EmitVAArg fails, emit an error.
10407f416cc4SJohn McCall   if (!ArgPtr.isValid()) {
104129b5f086SJames Y Knight     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
1042020cddcfSSebastian Redl     return;
1043020cddcfSSebastian Redl   }
104413abd7e9SAnders Carlsson 
10454e8ca4faSJohn McCall   EmitFinalDestCopy(VE->getType(), CGF.MakeAddrLValue(ArgPtr, VE->getType()));
104621911e89SEli Friedman }
104721911e89SEli Friedman 
10483be22e27SAnders Carlsson void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
10497a626f63SJohn McCall   // Ensure that we have a slot, but if we already do, remember
1050cac93853SJohn McCall   // whether it was externally destructed.
1051cac93853SJohn McCall   bool wasExternallyDestructed = Dest.isExternallyDestructed();
10524e8ca4faSJohn McCall   EnsureDest(E->getType());
1053cac93853SJohn McCall 
1054cac93853SJohn McCall   // We're going to push a destructor if there isn't already one.
1055cac93853SJohn McCall   Dest.setExternallyDestructed();
10563be22e27SAnders Carlsson 
10573be22e27SAnders Carlsson   Visit(E->getSubExpr());
10583be22e27SAnders Carlsson 
1059cac93853SJohn McCall   // Push that destructor we promised.
1060cac93853SJohn McCall   if (!wasExternallyDestructed)
10617f416cc4SJohn McCall     CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddress());
10623be22e27SAnders Carlsson }
10633be22e27SAnders Carlsson 
1064b7f8f594SAnders Carlsson void
10651619a504SAnders Carlsson AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10667a626f63SJohn McCall   AggValueSlot Slot = EnsureSlot(E->getType());
10677a626f63SJohn McCall   CGF.EmitCXXConstructExpr(E, Slot);
1068c82b86dfSAnders Carlsson }
1069c82b86dfSAnders Carlsson 
10705179eb78SRichard Smith void AggExprEmitter::VisitCXXInheritedCtorInitExpr(
10715179eb78SRichard Smith     const CXXInheritedCtorInitExpr *E) {
10725179eb78SRichard Smith   AggValueSlot Slot = EnsureSlot(E->getType());
10735179eb78SRichard Smith   CGF.EmitInheritedCXXConstructorCall(
10745179eb78SRichard Smith       E->getConstructor(), E->constructsVBase(), Slot.getAddress(),
10755179eb78SRichard Smith       E->inheritedFromVBase(), E);
10765179eb78SRichard Smith }
10775179eb78SRichard Smith 
1078c370a7eeSEli Friedman void
1079c370a7eeSEli Friedman AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
1080c370a7eeSEli Friedman   AggValueSlot Slot = EnsureSlot(E->getType());
1081c370a7eeSEli Friedman   CGF.EmitLambdaExpr(E, Slot);
1082c370a7eeSEli Friedman }
1083c370a7eeSEli Friedman 
10845d413781SJohn McCall void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
108508ef4660SJohn McCall   CGF.enterFullExpression(E);
108608ef4660SJohn McCall   CodeGenFunction::RunCleanupsScope cleanups(CGF);
108708ef4660SJohn McCall   Visit(E->getSubExpr());
1088b7f8f594SAnders Carlsson }
1089b7f8f594SAnders Carlsson 
1090747eb784SDouglas Gregor void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
10917a626f63SJohn McCall   QualType T = E->getType();
10927a626f63SJohn McCall   AggValueSlot Slot = EnsureSlot(T);
10937f416cc4SJohn McCall   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
109418ada985SAnders Carlsson }
109518ada985SAnders Carlsson 
109618ada985SAnders Carlsson void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
10977a626f63SJohn McCall   QualType T = E->getType();
10987a626f63SJohn McCall   AggValueSlot Slot = EnsureSlot(T);
10997f416cc4SJohn McCall   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddress(), T));
1100ff3507b9SNuno Lopes }
1101ff3507b9SNuno Lopes 
110227a3631bSChris Lattner /// isSimpleZero - If emitting this value will obviously just cause a store of
110327a3631bSChris Lattner /// zero to memory, return true.  This can return false if uncertain, so it just
110427a3631bSChris Lattner /// handles simple cases.
110527a3631bSChris Lattner static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
110691147596SPeter Collingbourne   E = E->IgnoreParens();
110791147596SPeter Collingbourne 
110827a3631bSChris Lattner   // 0
110927a3631bSChris Lattner   if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
111027a3631bSChris Lattner     return IL->getValue() == 0;
111127a3631bSChris Lattner   // +0.0
111227a3631bSChris Lattner   if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
111327a3631bSChris Lattner     return FL->getValue().isPosZero();
111427a3631bSChris Lattner   // int()
111527a3631bSChris Lattner   if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
111627a3631bSChris Lattner       CGF.getTypes().isZeroInitializable(E->getType()))
111727a3631bSChris Lattner     return true;
111827a3631bSChris Lattner   // (int*)0 - Null pointer expressions.
111927a3631bSChris Lattner   if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
1120402804b6SYaxun Liu     return ICE->getCastKind() == CK_NullToPointer &&
1121402804b6SYaxun Liu         CGF.getTypes().isPointerZeroInitializable(E->getType());
112227a3631bSChris Lattner   // '\0'
112327a3631bSChris Lattner   if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
112427a3631bSChris Lattner     return CL->getValue() == 0;
112527a3631bSChris Lattner 
112627a3631bSChris Lattner   // Otherwise, hard case: conservatively return false.
112727a3631bSChris Lattner   return false;
112827a3631bSChris Lattner }
112927a3631bSChris Lattner 
113027a3631bSChris Lattner 
1131b247350eSAnders Carlsson void
1132615ed1a3SChad Rosier AggExprEmitter::EmitInitializationToLValue(Expr *E, LValue LV) {
11331553b190SJohn McCall   QualType type = LV.getType();
1134df0fe27bSMike Stump   // FIXME: Ignore result?
1135579a05d7SChris Lattner   // FIXME: Are initializers affected by volatile?
113627a3631bSChris Lattner   if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
113727a3631bSChris Lattner     // Storing "i32 0" to a zero'd memory location is a noop.
113847fb9508SJohn McCall     return;
1139d82a2ce3SRichard Smith   } else if (isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) {
114047fb9508SJohn McCall     return EmitNullInitializationToLValue(LV);
1141cb77930dSYunzhong Gao   } else if (isa<NoInitExpr>(E)) {
1142cb77930dSYunzhong Gao     // Do nothing.
1143cb77930dSYunzhong Gao     return;
11441553b190SJohn McCall   } else if (type->isReferenceType()) {
1145a1c9d4d9SRichard Smith     RValue RV = CGF.EmitReferenceBindingToExpr(E);
114647fb9508SJohn McCall     return CGF.EmitStoreThroughLValue(RV, LV);
114747fb9508SJohn McCall   }
114847fb9508SJohn McCall 
114947fb9508SJohn McCall   switch (CGF.getEvaluationKind(type)) {
115047fb9508SJohn McCall   case TEK_Complex:
115147fb9508SJohn McCall     CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
115247fb9508SJohn McCall     return;
115347fb9508SJohn McCall   case TEK_Aggregate:
11548d6fc958SJohn McCall     CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV,
11558d6fc958SJohn McCall                                                AggValueSlot::IsDestructed,
11568d6fc958SJohn McCall                                       AggValueSlot::DoesNotNeedGCBarriers,
1157a5efa738SJohn McCall                                                AggValueSlot::IsNotAliased,
11581553b190SJohn McCall                                                Dest.isZeroed()));
115947fb9508SJohn McCall     return;
116047fb9508SJohn McCall   case TEK_Scalar:
116147fb9508SJohn McCall     if (LV.isSimple()) {
11628a13c418SCraig Topper       CGF.EmitScalarInit(E, /*D=*/nullptr, LV, /*Captured=*/false);
11636e313210SEli Friedman     } else {
116455e1fbc8SJohn McCall       CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
11657a51313dSChris Lattner     }
116647fb9508SJohn McCall     return;
116747fb9508SJohn McCall   }
116847fb9508SJohn McCall   llvm_unreachable("bad evaluation kind");
1169579a05d7SChris Lattner }
1170579a05d7SChris Lattner 
11711553b190SJohn McCall void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
11721553b190SJohn McCall   QualType type = lv.getType();
11731553b190SJohn McCall 
117427a3631bSChris Lattner   // If the destination slot is already zeroed out before the aggregate is
117527a3631bSChris Lattner   // copied into it, we don't have to emit any zeros here.
11761553b190SJohn McCall   if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
117727a3631bSChris Lattner     return;
117827a3631bSChris Lattner 
117947fb9508SJohn McCall   if (CGF.hasScalarEvaluationKind(type)) {
1180d82a2ce3SRichard Smith     // For non-aggregates, we can store the appropriate null constant.
1181d82a2ce3SRichard Smith     llvm::Value *null = CGF.CGM.EmitNullConstant(type);
118291d5bb1eSEli Friedman     // Note that the following is not equivalent to
118391d5bb1eSEli Friedman     // EmitStoreThroughBitfieldLValue for ARC types.
1184cb3785e4SEli Friedman     if (lv.isBitField()) {
118591d5bb1eSEli Friedman       CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
1186cb3785e4SEli Friedman     } else {
118791d5bb1eSEli Friedman       assert(lv.isSimple());
118891d5bb1eSEli Friedman       CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
1189cb3785e4SEli Friedman     }
1190579a05d7SChris Lattner   } else {
1191579a05d7SChris Lattner     // There's a potential optimization opportunity in combining
1192579a05d7SChris Lattner     // memsets; that would be easy for arrays, but relatively
1193579a05d7SChris Lattner     // difficult for structures with the current code.
11941553b190SJohn McCall     CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
1195579a05d7SChris Lattner   }
1196579a05d7SChris Lattner }
1197579a05d7SChris Lattner 
1198579a05d7SChris Lattner void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
1199f5d08c9eSEli Friedman #if 0
12006d11ec8cSEli Friedman   // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
12016d11ec8cSEli Friedman   // (Length of globals? Chunks of zeroed-out space?).
1202f5d08c9eSEli Friedman   //
120318bb9284SMike Stump   // If we can, prefer a copy from a global; this is a lot less code for long
120418bb9284SMike Stump   // globals, and it's easier for the current optimizers to analyze.
12056d11ec8cSEli Friedman   if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
1206c59bb48eSEli Friedman     llvm::GlobalVariable* GV =
12076d11ec8cSEli Friedman     new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
12086d11ec8cSEli Friedman                              llvm::GlobalValue::InternalLinkage, C, "");
12094e8ca4faSJohn McCall     EmitFinalDestCopy(E->getType(), CGF.MakeAddrLValue(GV, E->getType()));
1210c59bb48eSEli Friedman     return;
1211c59bb48eSEli Friedman   }
1212f5d08c9eSEli Friedman #endif
1213f53c0968SChris Lattner   if (E->hadArrayRangeDesignator())
1214bf7207a1SDouglas Gregor     CGF.ErrorUnsupported(E, "GNU array range designator extension");
1215bf7207a1SDouglas Gregor 
1216122f88d4SRichard Smith   if (E->isTransparent())
1217122f88d4SRichard Smith     return Visit(E->getInit(0));
1218122f88d4SRichard Smith 
1219be93c00aSRichard Smith   AggValueSlot Dest = EnsureSlot(E->getType());
1220be93c00aSRichard Smith 
12217f416cc4SJohn McCall   LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
12227a626f63SJohn McCall 
1223579a05d7SChris Lattner   // Handle initialization of an array.
1224579a05d7SChris Lattner   if (E->getType()->isArrayType()) {
12257f416cc4SJohn McCall     auto AType = cast<llvm::ArrayType>(Dest.getAddress().getElementType());
1226e0ef348cSIvan A. Kosarev     EmitArrayInit(Dest.getAddress(), AType, E->getType(), E);
1227579a05d7SChris Lattner     return;
1228579a05d7SChris Lattner   }
1229579a05d7SChris Lattner 
1230579a05d7SChris Lattner   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
1231579a05d7SChris Lattner 
1232579a05d7SChris Lattner   // Do struct initialization; this code just sets each individual member
1233579a05d7SChris Lattner   // to the approprate value.  This makes bitfield support automatic;
1234579a05d7SChris Lattner   // the disadvantage is that the generated code is more difficult for
1235579a05d7SChris Lattner   // the optimizer, especially with bitfields.
1236579a05d7SChris Lattner   unsigned NumInitElements = E->getNumInits();
12373b935d33SJohn McCall   RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
123852bcf963SChris Lattner 
1239872307e2SRichard Smith   // We'll need to enter cleanup scopes in case any of the element
1240872307e2SRichard Smith   // initializers throws an exception.
1241872307e2SRichard Smith   SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
1242872307e2SRichard Smith   llvm::Instruction *cleanupDominator = nullptr;
1243872307e2SRichard Smith 
1244872307e2SRichard Smith   unsigned curInitIndex = 0;
1245872307e2SRichard Smith 
1246872307e2SRichard Smith   // Emit initialization of base classes.
1247872307e2SRichard Smith   if (auto *CXXRD = dyn_cast<CXXRecordDecl>(record)) {
1248872307e2SRichard Smith     assert(E->getNumInits() >= CXXRD->getNumBases() &&
1249872307e2SRichard Smith            "missing initializer for base class");
1250872307e2SRichard Smith     for (auto &Base : CXXRD->bases()) {
1251872307e2SRichard Smith       assert(!Base.isVirtual() && "should not see vbases here");
1252872307e2SRichard Smith       auto *BaseRD = Base.getType()->getAsCXXRecordDecl();
1253872307e2SRichard Smith       Address V = CGF.GetAddressOfDirectBaseInCompleteClass(
1254872307e2SRichard Smith           Dest.getAddress(), CXXRD, BaseRD,
1255872307e2SRichard Smith           /*isBaseVirtual*/ false);
1256872307e2SRichard Smith       AggValueSlot AggSlot =
1257872307e2SRichard Smith         AggValueSlot::forAddr(V, Qualifiers(),
1258872307e2SRichard Smith                               AggValueSlot::IsDestructed,
1259872307e2SRichard Smith                               AggValueSlot::DoesNotNeedGCBarriers,
1260872307e2SRichard Smith                               AggValueSlot::IsNotAliased);
1261872307e2SRichard Smith       CGF.EmitAggExpr(E->getInit(curInitIndex++), AggSlot);
1262872307e2SRichard Smith 
1263872307e2SRichard Smith       if (QualType::DestructionKind dtorKind =
1264872307e2SRichard Smith               Base.getType().isDestructedType()) {
1265872307e2SRichard Smith         CGF.pushDestroy(dtorKind, V, Base.getType());
1266872307e2SRichard Smith         cleanups.push_back(CGF.EHStack.stable_begin());
1267872307e2SRichard Smith       }
1268872307e2SRichard Smith     }
1269872307e2SRichard Smith   }
1270872307e2SRichard Smith 
1271852c9db7SRichard Smith   // Prepare a 'this' for CXXDefaultInitExprs.
12727f416cc4SJohn McCall   CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddress());
1273852c9db7SRichard Smith 
12743b935d33SJohn McCall   if (record->isUnion()) {
12755169570eSDouglas Gregor     // Only initialize one field of a union. The field itself is
12765169570eSDouglas Gregor     // specified by the initializer list.
12775169570eSDouglas Gregor     if (!E->getInitializedFieldInUnion()) {
12785169570eSDouglas Gregor       // Empty union; we have nothing to do.
12795169570eSDouglas Gregor 
12805169570eSDouglas Gregor #ifndef NDEBUG
12815169570eSDouglas Gregor       // Make sure that it's really an empty and not a failure of
12825169570eSDouglas Gregor       // semantic analysis.
1283e8a8baefSAaron Ballman       for (const auto *Field : record->fields())
12845169570eSDouglas Gregor         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
12855169570eSDouglas Gregor #endif
12865169570eSDouglas Gregor       return;
12875169570eSDouglas Gregor     }
12885169570eSDouglas Gregor 
12895169570eSDouglas Gregor     // FIXME: volatility
12905169570eSDouglas Gregor     FieldDecl *Field = E->getInitializedFieldInUnion();
12915169570eSDouglas Gregor 
12927f1ff600SEli Friedman     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
12935169570eSDouglas Gregor     if (NumInitElements) {
12945169570eSDouglas Gregor       // Store the initializer into the field
1295615ed1a3SChad Rosier       EmitInitializationToLValue(E->getInit(0), FieldLoc);
12965169570eSDouglas Gregor     } else {
129727a3631bSChris Lattner       // Default-initialize to null.
12981553b190SJohn McCall       EmitNullInitializationToLValue(FieldLoc);
12995169570eSDouglas Gregor     }
13005169570eSDouglas Gregor 
13015169570eSDouglas Gregor     return;
13025169570eSDouglas Gregor   }
1303579a05d7SChris Lattner 
1304579a05d7SChris Lattner   // Here we iterate over the fields; this makes it simpler to both
1305579a05d7SChris Lattner   // default-initialize fields and skip over unnamed fields.
1306e8a8baefSAaron Ballman   for (const auto *field : record->fields()) {
13073b935d33SJohn McCall     // We're done once we hit the flexible array member.
13083b935d33SJohn McCall     if (field->getType()->isIncompleteArrayType())
130991f84216SDouglas Gregor       break;
131091f84216SDouglas Gregor 
13113b935d33SJohn McCall     // Always skip anonymous bitfields.
13123b935d33SJohn McCall     if (field->isUnnamedBitfield())
1313579a05d7SChris Lattner       continue;
131417bd094aSDouglas Gregor 
13153b935d33SJohn McCall     // We're done if we reach the end of the explicit initializers, we
13163b935d33SJohn McCall     // have a zeroed object, and the rest of the fields are
13173b935d33SJohn McCall     // zero-initializable.
13183b935d33SJohn McCall     if (curInitIndex == NumInitElements && Dest.isZeroed() &&
131927a3631bSChris Lattner         CGF.getTypes().isZeroInitializable(E->getType()))
132027a3631bSChris Lattner       break;
132127a3631bSChris Lattner 
13227f1ff600SEli Friedman 
1323e8a8baefSAaron Ballman     LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, field);
13247c1baf46SFariborz Jahanian     // We never generate write-barries for initialized fields.
13253b935d33SJohn McCall     LV.setNonGC(true);
132627a3631bSChris Lattner 
13273b935d33SJohn McCall     if (curInitIndex < NumInitElements) {
1328e18aaf2cSChris Lattner       // Store the initializer into the field.
1329615ed1a3SChad Rosier       EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
1330579a05d7SChris Lattner     } else {
13312c51880aSSimon Pilgrim       // We're out of initializers; default-initialize to null
13323b935d33SJohn McCall       EmitNullInitializationToLValue(LV);
13333b935d33SJohn McCall     }
13343b935d33SJohn McCall 
13353b935d33SJohn McCall     // Push a destructor if necessary.
13363b935d33SJohn McCall     // FIXME: if we have an array of structures, all explicitly
13373b935d33SJohn McCall     // initialized, we can end up pushing a linear number of cleanups.
13383b935d33SJohn McCall     bool pushedCleanup = false;
13393b935d33SJohn McCall     if (QualType::DestructionKind dtorKind
13403b935d33SJohn McCall           = field->getType().isDestructedType()) {
13413b935d33SJohn McCall       assert(LV.isSimple());
13423b935d33SJohn McCall       if (CGF.needsEHCleanup(dtorKind)) {
1343f4beacd0SJohn McCall         if (!cleanupDominator)
13447f416cc4SJohn McCall           cleanupDominator = CGF.Builder.CreateAlignedLoad(
13455ee4b9a1SReid Kleckner               CGF.Int8Ty,
13467f416cc4SJohn McCall               llvm::Constant::getNullValue(CGF.Int8PtrTy),
13477f416cc4SJohn McCall               CharUnits::One()); // placeholder
1348f4beacd0SJohn McCall 
13493b935d33SJohn McCall         CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
13503b935d33SJohn McCall                         CGF.getDestroyer(dtorKind), false);
13513b935d33SJohn McCall         cleanups.push_back(CGF.EHStack.stable_begin());
13523b935d33SJohn McCall         pushedCleanup = true;
13533b935d33SJohn McCall       }
1354579a05d7SChris Lattner     }
135527a3631bSChris Lattner 
135627a3631bSChris Lattner     // If the GEP didn't get used because of a dead zero init or something
135727a3631bSChris Lattner     // else, clean it up for -O0 builds and general tidiness.
13583b935d33SJohn McCall     if (!pushedCleanup && LV.isSimple())
135927a3631bSChris Lattner       if (llvm::GetElementPtrInst *GEP =
13607f416cc4SJohn McCall             dyn_cast<llvm::GetElementPtrInst>(LV.getPointer()))
136127a3631bSChris Lattner         if (GEP->use_empty())
136227a3631bSChris Lattner           GEP->eraseFromParent();
13637a51313dSChris Lattner   }
13643b935d33SJohn McCall 
13653b935d33SJohn McCall   // Deactivate all the partial cleanups in reverse order, which
13663b935d33SJohn McCall   // generally means popping them.
13673b935d33SJohn McCall   for (unsigned i = cleanups.size(); i != 0; --i)
1368f4beacd0SJohn McCall     CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
1369f4beacd0SJohn McCall 
1370f4beacd0SJohn McCall   // Destroy the placeholder if we made one.
1371f4beacd0SJohn McCall   if (cleanupDominator)
1372f4beacd0SJohn McCall     cleanupDominator->eraseFromParent();
13737a51313dSChris Lattner }
13747a51313dSChris Lattner 
1375939b6880SRichard Smith void AggExprEmitter::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E,
1376939b6880SRichard Smith                                             llvm::Value *outerBegin) {
1377410306bfSRichard Smith   // Emit the common subexpression.
1378410306bfSRichard Smith   CodeGenFunction::OpaqueValueMapping binding(CGF, E->getCommonExpr());
1379410306bfSRichard Smith 
1380410306bfSRichard Smith   Address destPtr = EnsureSlot(E->getType()).getAddress();
1381410306bfSRichard Smith   uint64_t numElements = E->getArraySize().getZExtValue();
1382410306bfSRichard Smith 
1383410306bfSRichard Smith   if (!numElements)
1384410306bfSRichard Smith     return;
1385410306bfSRichard Smith 
1386410306bfSRichard Smith   // destPtr is an array*. Construct an elementType* by drilling down a level.
1387410306bfSRichard Smith   llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
1388410306bfSRichard Smith   llvm::Value *indices[] = {zero, zero};
1389410306bfSRichard Smith   llvm::Value *begin = Builder.CreateInBoundsGEP(destPtr.getPointer(), indices,
1390410306bfSRichard Smith                                                  "arrayinit.begin");
1391410306bfSRichard Smith 
1392939b6880SRichard Smith   // Prepare to special-case multidimensional array initialization: we avoid
1393939b6880SRichard Smith   // emitting multiple destructor loops in that case.
1394939b6880SRichard Smith   if (!outerBegin)
1395939b6880SRichard Smith     outerBegin = begin;
1396939b6880SRichard Smith   ArrayInitLoopExpr *InnerLoop = dyn_cast<ArrayInitLoopExpr>(E->getSubExpr());
1397939b6880SRichard Smith 
139830e304e2SRichard Smith   QualType elementType =
139930e304e2SRichard Smith       CGF.getContext().getAsArrayType(E->getType())->getElementType();
1400410306bfSRichard Smith   CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
1401410306bfSRichard Smith   CharUnits elementAlign =
1402410306bfSRichard Smith       destPtr.getAlignment().alignmentOfArrayElement(elementSize);
1403410306bfSRichard Smith 
1404410306bfSRichard Smith   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1405410306bfSRichard Smith   llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
1406410306bfSRichard Smith 
1407410306bfSRichard Smith   // Jump into the body.
1408410306bfSRichard Smith   CGF.EmitBlock(bodyBB);
1409410306bfSRichard Smith   llvm::PHINode *index =
1410410306bfSRichard Smith       Builder.CreatePHI(zero->getType(), 2, "arrayinit.index");
1411410306bfSRichard Smith   index->addIncoming(zero, entryBB);
1412410306bfSRichard Smith   llvm::Value *element = Builder.CreateInBoundsGEP(begin, index);
1413410306bfSRichard Smith 
141430e304e2SRichard Smith   // Prepare for a cleanup.
141530e304e2SRichard Smith   QualType::DestructionKind dtorKind = elementType.isDestructedType();
141630e304e2SRichard Smith   EHScopeStack::stable_iterator cleanup;
1417939b6880SRichard Smith   if (CGF.needsEHCleanup(dtorKind) && !InnerLoop) {
1418939b6880SRichard Smith     if (outerBegin->getType() != element->getType())
1419939b6880SRichard Smith       outerBegin = Builder.CreateBitCast(outerBegin, element->getType());
1420939b6880SRichard Smith     CGF.pushRegularPartialArrayCleanup(outerBegin, element, elementType,
1421939b6880SRichard Smith                                        elementAlign,
1422939b6880SRichard Smith                                        CGF.getDestroyer(dtorKind));
142330e304e2SRichard Smith     cleanup = CGF.EHStack.stable_begin();
142430e304e2SRichard Smith   } else {
142530e304e2SRichard Smith     dtorKind = QualType::DK_none;
142630e304e2SRichard Smith   }
1427410306bfSRichard Smith 
1428410306bfSRichard Smith   // Emit the actual filler expression.
1429410306bfSRichard Smith   {
143030e304e2SRichard Smith     // Temporaries created in an array initialization loop are destroyed
143130e304e2SRichard Smith     // at the end of each iteration.
143230e304e2SRichard Smith     CodeGenFunction::RunCleanupsScope CleanupsScope(CGF);
1433410306bfSRichard Smith     CodeGenFunction::ArrayInitLoopExprScope Scope(CGF, index);
1434410306bfSRichard Smith     LValue elementLV =
1435410306bfSRichard Smith         CGF.MakeAddrLValue(Address(element, elementAlign), elementType);
1436939b6880SRichard Smith 
1437939b6880SRichard Smith     if (InnerLoop) {
1438939b6880SRichard Smith       // If the subexpression is an ArrayInitLoopExpr, share its cleanup.
1439939b6880SRichard Smith       auto elementSlot = AggValueSlot::forLValue(
1440939b6880SRichard Smith           elementLV, AggValueSlot::IsDestructed,
1441939b6880SRichard Smith           AggValueSlot::DoesNotNeedGCBarriers, AggValueSlot::IsNotAliased);
1442939b6880SRichard Smith       AggExprEmitter(CGF, elementSlot, false)
1443939b6880SRichard Smith           .VisitArrayInitLoopExpr(InnerLoop, outerBegin);
1444939b6880SRichard Smith     } else
1445410306bfSRichard Smith       EmitInitializationToLValue(E->getSubExpr(), elementLV);
1446410306bfSRichard Smith   }
1447410306bfSRichard Smith 
1448410306bfSRichard Smith   // Move on to the next element.
1449410306bfSRichard Smith   llvm::Value *nextIndex = Builder.CreateNUWAdd(
1450410306bfSRichard Smith       index, llvm::ConstantInt::get(CGF.SizeTy, 1), "arrayinit.next");
1451410306bfSRichard Smith   index->addIncoming(nextIndex, Builder.GetInsertBlock());
1452410306bfSRichard Smith 
1453410306bfSRichard Smith   // Leave the loop if we're done.
1454410306bfSRichard Smith   llvm::Value *done = Builder.CreateICmpEQ(
1455410306bfSRichard Smith       nextIndex, llvm::ConstantInt::get(CGF.SizeTy, numElements),
1456410306bfSRichard Smith       "arrayinit.done");
1457410306bfSRichard Smith   llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
1458410306bfSRichard Smith   Builder.CreateCondBr(done, endBB, bodyBB);
1459410306bfSRichard Smith 
1460410306bfSRichard Smith   CGF.EmitBlock(endBB);
1461410306bfSRichard Smith 
1462410306bfSRichard Smith   // Leave the partial-array cleanup if we entered one.
146330e304e2SRichard Smith   if (dtorKind)
146430e304e2SRichard Smith     CGF.DeactivateCleanupBlock(cleanup, index);
1465410306bfSRichard Smith }
1466410306bfSRichard Smith 
1467cb77930dSYunzhong Gao void AggExprEmitter::VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E) {
1468cb77930dSYunzhong Gao   AggValueSlot Dest = EnsureSlot(E->getType());
1469cb77930dSYunzhong Gao 
14707f416cc4SJohn McCall   LValue DestLV = CGF.MakeAddrLValue(Dest.getAddress(), E->getType());
1471cb77930dSYunzhong Gao   EmitInitializationToLValue(E->getBase(), DestLV);
1472cb77930dSYunzhong Gao   VisitInitListExpr(E->getUpdater());
1473cb77930dSYunzhong Gao }
1474cb77930dSYunzhong Gao 
14757a51313dSChris Lattner //===----------------------------------------------------------------------===//
14767a51313dSChris Lattner //                        Entry Points into this File
14777a51313dSChris Lattner //===----------------------------------------------------------------------===//
14787a51313dSChris Lattner 
147927a3631bSChris Lattner /// GetNumNonZeroBytesInInit - Get an approximate count of the number of
148027a3631bSChris Lattner /// non-zero bytes that will be stored when outputting the initializer for the
148127a3631bSChris Lattner /// specified initializer expression.
1482df94cb7dSKen Dyck static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
148391147596SPeter Collingbourne   E = E->IgnoreParens();
148427a3631bSChris Lattner 
148527a3631bSChris Lattner   // 0 and 0.0 won't require any non-zero stores!
1486df94cb7dSKen Dyck   if (isSimpleZero(E, CGF)) return CharUnits::Zero();
148727a3631bSChris Lattner 
148827a3631bSChris Lattner   // If this is an initlist expr, sum up the size of sizes of the (present)
148927a3631bSChris Lattner   // elements.  If this is something weird, assume the whole thing is non-zero.
149027a3631bSChris Lattner   const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
14918a13c418SCraig Topper   if (!ILE || !CGF.getTypes().isZeroInitializable(ILE->getType()))
1492df94cb7dSKen Dyck     return CGF.getContext().getTypeSizeInChars(E->getType());
149327a3631bSChris Lattner 
1494c5cc2fb9SChris Lattner   // InitListExprs for structs have to be handled carefully.  If there are
1495c5cc2fb9SChris Lattner   // reference members, we need to consider the size of the reference, not the
1496c5cc2fb9SChris Lattner   // referencee.  InitListExprs for unions and arrays can't have references.
14975cd84755SChris Lattner   if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
14985cd84755SChris Lattner     if (!RT->isUnionType()) {
1499c5cc2fb9SChris Lattner       RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
1500df94cb7dSKen Dyck       CharUnits NumNonZeroBytes = CharUnits::Zero();
1501c5cc2fb9SChris Lattner 
1502c5cc2fb9SChris Lattner       unsigned ILEElement = 0;
1503872307e2SRichard Smith       if (auto *CXXRD = dyn_cast<CXXRecordDecl>(SD))
15046365e464SRichard Smith         while (ILEElement != CXXRD->getNumBases())
1505872307e2SRichard Smith           NumNonZeroBytes +=
1506872307e2SRichard Smith               GetNumNonZeroBytesInInit(ILE->getInit(ILEElement++), CGF);
1507e8a8baefSAaron Ballman       for (const auto *Field : SD->fields()) {
1508c5cc2fb9SChris Lattner         // We're done once we hit the flexible array member or run out of
1509c5cc2fb9SChris Lattner         // InitListExpr elements.
1510c5cc2fb9SChris Lattner         if (Field->getType()->isIncompleteArrayType() ||
1511c5cc2fb9SChris Lattner             ILEElement == ILE->getNumInits())
1512c5cc2fb9SChris Lattner           break;
1513c5cc2fb9SChris Lattner         if (Field->isUnnamedBitfield())
1514c5cc2fb9SChris Lattner           continue;
1515c5cc2fb9SChris Lattner 
1516c5cc2fb9SChris Lattner         const Expr *E = ILE->getInit(ILEElement++);
1517c5cc2fb9SChris Lattner 
1518c5cc2fb9SChris Lattner         // Reference values are always non-null and have the width of a pointer.
15195cd84755SChris Lattner         if (Field->getType()->isReferenceType())
1520df94cb7dSKen Dyck           NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
1521c8e01705SJohn McCall               CGF.getTarget().getPointerWidth(0));
15225cd84755SChris Lattner         else
1523c5cc2fb9SChris Lattner           NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
1524c5cc2fb9SChris Lattner       }
1525c5cc2fb9SChris Lattner 
1526c5cc2fb9SChris Lattner       return NumNonZeroBytes;
1527c5cc2fb9SChris Lattner     }
15285cd84755SChris Lattner   }
1529c5cc2fb9SChris Lattner 
1530c5cc2fb9SChris Lattner 
1531df94cb7dSKen Dyck   CharUnits NumNonZeroBytes = CharUnits::Zero();
153227a3631bSChris Lattner   for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
153327a3631bSChris Lattner     NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
153427a3631bSChris Lattner   return NumNonZeroBytes;
153527a3631bSChris Lattner }
153627a3631bSChris Lattner 
153727a3631bSChris Lattner /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
153827a3631bSChris Lattner /// zeros in it, emit a memset and avoid storing the individual zeros.
153927a3631bSChris Lattner ///
154027a3631bSChris Lattner static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
154127a3631bSChris Lattner                                      CodeGenFunction &CGF) {
154227a3631bSChris Lattner   // If the slot is already known to be zeroed, nothing to do.  Don't mess with
154327a3631bSChris Lattner   // volatile stores.
15447f416cc4SJohn McCall   if (Slot.isZeroed() || Slot.isVolatile() || !Slot.getAddress().isValid())
15458a13c418SCraig Topper     return;
154627a3631bSChris Lattner 
154703535265SArgyrios Kyrtzidis   // C++ objects with a user-declared constructor don't need zero'ing.
15489c6890a7SRichard Smith   if (CGF.getLangOpts().CPlusPlus)
154903535265SArgyrios Kyrtzidis     if (const RecordType *RT = CGF.getContext()
155003535265SArgyrios Kyrtzidis                        .getBaseElementType(E->getType())->getAs<RecordType>()) {
155103535265SArgyrios Kyrtzidis       const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
155203535265SArgyrios Kyrtzidis       if (RD->hasUserDeclaredConstructor())
155303535265SArgyrios Kyrtzidis         return;
155403535265SArgyrios Kyrtzidis     }
155503535265SArgyrios Kyrtzidis 
155627a3631bSChris Lattner   // If the type is 16-bytes or smaller, prefer individual stores over memset.
15577f416cc4SJohn McCall   CharUnits Size = CGF.getContext().getTypeSizeInChars(E->getType());
15587f416cc4SJohn McCall   if (Size <= CharUnits::fromQuantity(16))
155927a3631bSChris Lattner     return;
156027a3631bSChris Lattner 
156127a3631bSChris Lattner   // Check to see if over 3/4 of the initializer are known to be zero.  If so,
156227a3631bSChris Lattner   // we prefer to emit memset + individual stores for the rest.
1563239a3357SKen Dyck   CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
15647f416cc4SJohn McCall   if (NumNonZeroBytes*4 > Size)
156527a3631bSChris Lattner     return;
156627a3631bSChris Lattner 
156727a3631bSChris Lattner   // Okay, it seems like a good idea to use an initial memset, emit the call.
15687f416cc4SJohn McCall   llvm::Constant *SizeVal = CGF.Builder.getInt64(Size.getQuantity());
156927a3631bSChris Lattner 
15707f416cc4SJohn McCall   Address Loc = Slot.getAddress();
15717f416cc4SJohn McCall   Loc = CGF.Builder.CreateElementBitCast(Loc, CGF.Int8Ty);
15727f416cc4SJohn McCall   CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal, false);
157327a3631bSChris Lattner 
157427a3631bSChris Lattner   // Tell the AggExprEmitter that the slot is known zero.
157527a3631bSChris Lattner   Slot.setZeroed();
157627a3631bSChris Lattner }
157727a3631bSChris Lattner 
157827a3631bSChris Lattner 
157927a3631bSChris Lattner 
158027a3631bSChris Lattner 
158125306cacSMike Stump /// EmitAggExpr - Emit the computation of the specified expression of aggregate
158225306cacSMike Stump /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
158325306cacSMike Stump /// the value of the aggregate expression is not needed.  If VolatileDest is
158425306cacSMike Stump /// true, DestPtr cannot be 0.
15854e8ca4faSJohn McCall void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) {
158647fb9508SJohn McCall   assert(E && hasAggregateEvaluationKind(E->getType()) &&
15877a51313dSChris Lattner          "Invalid aggregate expression to emit");
15887f416cc4SJohn McCall   assert((Slot.getAddress().isValid() || Slot.isIgnored()) &&
158927a3631bSChris Lattner          "slot has bits but no address");
15907a51313dSChris Lattner 
159127a3631bSChris Lattner   // Optimize the slot if possible.
159227a3631bSChris Lattner   CheckAggExprForMemSetUse(Slot, E, *this);
159327a3631bSChris Lattner 
15946aab1117SLeny Kholodov   AggExprEmitter(*this, Slot, Slot.isIgnored()).Visit(const_cast<Expr*>(E));
15957a51313dSChris Lattner }
15960bc8e86dSDaniel Dunbar 
1597d0bc7b9dSDaniel Dunbar LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
159847fb9508SJohn McCall   assert(hasAggregateEvaluationKind(E->getType()) && "Invalid argument!");
15997f416cc4SJohn McCall   Address Temp = CreateMemTemp(E->getType());
16002e442a00SDaniel Dunbar   LValue LV = MakeAddrLValue(Temp, E->getType());
16018d6fc958SJohn McCall   EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,
160246759f4fSJohn McCall                                          AggValueSlot::DoesNotNeedGCBarriers,
1603615ed1a3SChad Rosier                                          AggValueSlot::IsNotAliased));
16042e442a00SDaniel Dunbar   return LV;
1605d0bc7b9dSDaniel Dunbar }
1606d0bc7b9dSDaniel Dunbar 
16071860b520SIvan A. Kosarev void CodeGenFunction::EmitAggregateCopy(LValue Dest, LValue Src,
16081860b520SIvan A. Kosarev                                         QualType Ty, bool isVolatile,
16091ca66919SBenjamin Kramer                                         bool isAssignment) {
1610615ed1a3SChad Rosier   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
16110bc8e86dSDaniel Dunbar 
16121860b520SIvan A. Kosarev   Address DestPtr = Dest.getAddress();
16131860b520SIvan A. Kosarev   Address SrcPtr = Src.getAddress();
16141860b520SIvan A. Kosarev 
16159c6890a7SRichard Smith   if (getLangOpts().CPlusPlus) {
1616615ed1a3SChad Rosier     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1617615ed1a3SChad Rosier       CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
1618615ed1a3SChad Rosier       assert((Record->hasTrivialCopyConstructor() ||
1619615ed1a3SChad Rosier               Record->hasTrivialCopyAssignment() ||
1620615ed1a3SChad Rosier               Record->hasTrivialMoveConstructor() ||
1621419bd094SRichard Smith               Record->hasTrivialMoveAssignment() ||
1622419bd094SRichard Smith               Record->isUnion()) &&
162316488472SRichard Smith              "Trying to aggregate-copy a type without a trivial copy/move "
1624f22101a0SDouglas Gregor              "constructor or assignment operator");
1625615ed1a3SChad Rosier       // Ignore empty classes in C++.
1626615ed1a3SChad Rosier       if (Record->isEmpty())
162716e94af6SAnders Carlsson         return;
162816e94af6SAnders Carlsson     }
162916e94af6SAnders Carlsson   }
163016e94af6SAnders Carlsson 
1631ca05dfefSChris Lattner   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
16323ef668c2SChris Lattner   // C99 6.5.16.1p3, which states "If the value being stored in an object is
16333ef668c2SChris Lattner   // read from another object that overlaps in anyway the storage of the first
16343ef668c2SChris Lattner   // object, then the overlap shall be exact and the two objects shall have
16353ef668c2SChris Lattner   // qualified or unqualified versions of a compatible type."
16363ef668c2SChris Lattner   //
1637ca05dfefSChris Lattner   // memcpy is not defined if the source and destination pointers are exactly
16383ef668c2SChris Lattner   // equal, but other compilers do this optimization, and almost every memcpy
16393ef668c2SChris Lattner   // implementation handles this case safely.  If there is a libc that does not
16403ef668c2SChris Lattner   // safely handle this, we can add a target hook.
16410bc8e86dSDaniel Dunbar 
16427f416cc4SJohn McCall   // Get data size info for this aggregate. If this is an assignment,
16437f416cc4SJohn McCall   // don't copy the tail padding, because we might be assigning into a
16447f416cc4SJohn McCall   // base subobject where the tail padding is claimed.  Otherwise,
16457f416cc4SJohn McCall   // copying it is fine.
16461ca66919SBenjamin Kramer   std::pair<CharUnits, CharUnits> TypeInfo;
16471ca66919SBenjamin Kramer   if (isAssignment)
16481ca66919SBenjamin Kramer     TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);
16491ca66919SBenjamin Kramer   else
16501ca66919SBenjamin Kramer     TypeInfo = getContext().getTypeInfoInChars(Ty);
1651615ed1a3SChad Rosier 
165216dc7b68SAlexey Bataev   llvm::Value *SizeVal = nullptr;
165316dc7b68SAlexey Bataev   if (TypeInfo.first.isZero()) {
165416dc7b68SAlexey Bataev     // But note that getTypeInfo returns 0 for a VLA.
165516dc7b68SAlexey Bataev     if (auto *VAT = dyn_cast_or_null<VariableArrayType>(
165616dc7b68SAlexey Bataev             getContext().getAsArrayType(Ty))) {
165716dc7b68SAlexey Bataev       QualType BaseEltTy;
165816dc7b68SAlexey Bataev       SizeVal = emitArrayLength(VAT, BaseEltTy, DestPtr);
165916dc7b68SAlexey Bataev       TypeInfo = getContext().getTypeInfoDataSizeInChars(BaseEltTy);
166016dc7b68SAlexey Bataev       std::pair<CharUnits, CharUnits> LastElementTypeInfo;
166116dc7b68SAlexey Bataev       if (!isAssignment)
166216dc7b68SAlexey Bataev         LastElementTypeInfo = getContext().getTypeInfoInChars(BaseEltTy);
166316dc7b68SAlexey Bataev       assert(!TypeInfo.first.isZero());
166416dc7b68SAlexey Bataev       SizeVal = Builder.CreateNUWMul(
166516dc7b68SAlexey Bataev           SizeVal,
166616dc7b68SAlexey Bataev           llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()));
166716dc7b68SAlexey Bataev       if (!isAssignment) {
166816dc7b68SAlexey Bataev         SizeVal = Builder.CreateNUWSub(
166916dc7b68SAlexey Bataev             SizeVal,
167016dc7b68SAlexey Bataev             llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity()));
167116dc7b68SAlexey Bataev         SizeVal = Builder.CreateNUWAdd(
167216dc7b68SAlexey Bataev             SizeVal, llvm::ConstantInt::get(
167316dc7b68SAlexey Bataev                          SizeTy, LastElementTypeInfo.first.getQuantity()));
167416dc7b68SAlexey Bataev       }
167516dc7b68SAlexey Bataev     }
167616dc7b68SAlexey Bataev   }
167716dc7b68SAlexey Bataev   if (!SizeVal) {
167816dc7b68SAlexey Bataev     SizeVal = llvm::ConstantInt::get(SizeTy, TypeInfo.first.getQuantity());
167916dc7b68SAlexey Bataev   }
1680615ed1a3SChad Rosier 
1681615ed1a3SChad Rosier   // FIXME: If we have a volatile struct, the optimizer can remove what might
1682615ed1a3SChad Rosier   // appear to be `extra' memory ops:
1683615ed1a3SChad Rosier   //
1684615ed1a3SChad Rosier   // volatile struct { int i; } a, b;
1685615ed1a3SChad Rosier   //
1686615ed1a3SChad Rosier   // int main() {
1687615ed1a3SChad Rosier   //   a = b;
1688615ed1a3SChad Rosier   //   a = b;
1689615ed1a3SChad Rosier   // }
1690615ed1a3SChad Rosier   //
1691615ed1a3SChad Rosier   // we need to use a different call here.  We use isVolatile to indicate when
1692615ed1a3SChad Rosier   // either the source or the destination is volatile.
1693615ed1a3SChad Rosier 
16947f416cc4SJohn McCall   DestPtr = Builder.CreateElementBitCast(DestPtr, Int8Ty);
16957f416cc4SJohn McCall   SrcPtr = Builder.CreateElementBitCast(SrcPtr, Int8Ty);
1696615ed1a3SChad Rosier 
1697615ed1a3SChad Rosier   // Don't do any of the memmove_collectable tests if GC isn't set.
1698615ed1a3SChad Rosier   if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
1699615ed1a3SChad Rosier     // fall through
1700615ed1a3SChad Rosier   } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1701615ed1a3SChad Rosier     RecordDecl *Record = RecordTy->getDecl();
1702615ed1a3SChad Rosier     if (Record->hasObjectMember()) {
1703615ed1a3SChad Rosier       CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1704615ed1a3SChad Rosier                                                     SizeVal);
1705615ed1a3SChad Rosier       return;
1706615ed1a3SChad Rosier     }
1707615ed1a3SChad Rosier   } else if (Ty->isArrayType()) {
1708615ed1a3SChad Rosier     QualType BaseType = getContext().getBaseElementType(Ty);
1709615ed1a3SChad Rosier     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
1710615ed1a3SChad Rosier       if (RecordTy->getDecl()->hasObjectMember()) {
1711615ed1a3SChad Rosier         CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1712615ed1a3SChad Rosier                                                       SizeVal);
1713615ed1a3SChad Rosier         return;
1714615ed1a3SChad Rosier       }
1715615ed1a3SChad Rosier     }
1716615ed1a3SChad Rosier   }
1717615ed1a3SChad Rosier 
17187f416cc4SJohn McCall   auto Inst = Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, isVolatile);
17197f416cc4SJohn McCall 
172022695fceSDan Gohman   // Determine the metadata to describe the position of any padding in this
172122695fceSDan Gohman   // memcpy, as well as the TBAA tags for the members of the struct, in case
172222695fceSDan Gohman   // the optimizer wishes to expand it in to scalar memory operations.
17237f416cc4SJohn McCall   if (llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty))
17247f416cc4SJohn McCall     Inst->setMetadata(llvm::LLVMContext::MD_tbaa_struct, TBAAStructTag);
17251860b520SIvan A. Kosarev 
17261860b520SIvan A. Kosarev   if (CGM.getCodeGenOpts().NewStructPathTBAA) {
17271860b520SIvan A. Kosarev     TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForMemoryTransfer(
17281860b520SIvan A. Kosarev         Dest.getTBAAInfo(), Src.getTBAAInfo());
17291860b520SIvan A. Kosarev     CGM.DecorateInstructionWithTBAA(Inst, TBAAInfo);
17301860b520SIvan A. Kosarev   }
17310bc8e86dSDaniel Dunbar }
1732