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"
157a51313dSChris Lattner #include "CodeGenModule.h"
165f21d2f6SFariborz Jahanian #include "CGObjCRuntime.h"
17ad319a73SDaniel Dunbar #include "clang/AST/ASTContext.h"
18b7f8f594SAnders Carlsson #include "clang/AST/DeclCXX.h"
19ad319a73SDaniel Dunbar #include "clang/AST/StmtVisitor.h"
207a51313dSChris Lattner #include "llvm/Constants.h"
217a51313dSChris Lattner #include "llvm/Function.h"
227a51313dSChris Lattner #include "llvm/GlobalVariable.h"
23579a05d7SChris Lattner #include "llvm/Intrinsics.h"
247a51313dSChris Lattner using namespace clang;
257a51313dSChris Lattner using namespace CodeGen;
267a51313dSChris Lattner 
277a51313dSChris Lattner //===----------------------------------------------------------------------===//
287a51313dSChris Lattner //                        Aggregate Expression Emitter
297a51313dSChris Lattner //===----------------------------------------------------------------------===//
307a51313dSChris Lattner 
317a51313dSChris Lattner namespace  {
32337e3a5fSBenjamin Kramer class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
337a51313dSChris Lattner   CodeGenFunction &CGF;
34cb463859SDaniel Dunbar   CGBuilderTy &Builder;
357a626f63SJohn McCall   AggValueSlot Dest;
36ec3cbfe8SMike Stump   bool IgnoreResult;
3778a15113SJohn McCall 
3878a15113SJohn McCall   ReturnValueSlot getReturnValueSlot() const {
39cc04e9f6SJohn McCall     // If the destination slot requires garbage collection, we can't
40cc04e9f6SJohn McCall     // use the real return value slot, because we have to use the GC
41cc04e9f6SJohn McCall     // API.
4258649dc6SJohn McCall     if (Dest.requiresGCollection()) return ReturnValueSlot();
43cc04e9f6SJohn McCall 
447a626f63SJohn McCall     return ReturnValueSlot(Dest.getAddr(), Dest.isVolatile());
457a626f63SJohn McCall   }
467a626f63SJohn McCall 
477a626f63SJohn McCall   AggValueSlot EnsureSlot(QualType T) {
487a626f63SJohn McCall     if (!Dest.isIgnored()) return Dest;
497a626f63SJohn McCall     return CGF.CreateAggTemp(T, "agg.tmp.ensured");
5078a15113SJohn McCall   }
51cc04e9f6SJohn McCall 
527a51313dSChris Lattner public:
537a626f63SJohn McCall   AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest,
54b60e70f9SFariborz Jahanian                  bool ignore)
557a626f63SJohn McCall     : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
56b60e70f9SFariborz Jahanian       IgnoreResult(ignore) {
577a51313dSChris Lattner   }
587a51313dSChris Lattner 
597a51313dSChris Lattner   //===--------------------------------------------------------------------===//
607a51313dSChris Lattner   //                               Utilities
617a51313dSChris Lattner   //===--------------------------------------------------------------------===//
627a51313dSChris Lattner 
637a51313dSChris Lattner   /// EmitAggLoadOfLValue - Given an expression with aggregate type that
647a51313dSChris Lattner   /// represents a value lvalue, this method emits the address of the lvalue,
657a51313dSChris Lattner   /// then loads the result into DestPtr.
667a51313dSChris Lattner   void EmitAggLoadOfLValue(const Expr *E);
677a51313dSChris Lattner 
68ca9fc09cSMike Stump   /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
69ec3cbfe8SMike Stump   void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false);
70ec3cbfe8SMike Stump   void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false);
71ca9fc09cSMike Stump 
72cc04e9f6SJohn McCall   void EmitGCMove(const Expr *E, RValue Src);
73cc04e9f6SJohn McCall 
74cc04e9f6SJohn McCall   bool TypeRequiresGCollection(QualType T);
75cc04e9f6SJohn McCall 
767a51313dSChris Lattner   //===--------------------------------------------------------------------===//
777a51313dSChris Lattner   //                            Visitor Methods
787a51313dSChris Lattner   //===--------------------------------------------------------------------===//
797a51313dSChris Lattner 
807a51313dSChris Lattner   void VisitStmt(Stmt *S) {
81a7c8cf62SDaniel Dunbar     CGF.ErrorUnsupported(S, "aggregate expression");
827a51313dSChris Lattner   }
837a51313dSChris Lattner   void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
8491147596SPeter Collingbourne   void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
8591147596SPeter Collingbourne     Visit(GE->getResultExpr());
8691147596SPeter Collingbourne   }
873f66b84cSEli Friedman   void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
887c454bb8SJohn McCall   void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
897c454bb8SJohn McCall     return Visit(E->getReplacement());
907c454bb8SJohn McCall   }
917a51313dSChris Lattner 
927a51313dSChris Lattner   // l-values.
937a51313dSChris Lattner   void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); }
947a51313dSChris Lattner   void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
957a51313dSChris Lattner   void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
96d443c0a0SDaniel Dunbar   void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
979b71f0cfSDouglas Gregor   void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
987a51313dSChris Lattner   void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
997a51313dSChris Lattner     EmitAggLoadOfLValue(E);
1007a51313dSChris Lattner   }
1012f343dd5SChris Lattner   void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
1022f343dd5SChris Lattner     EmitAggLoadOfLValue(E);
1032f343dd5SChris Lattner   }
1042f343dd5SChris Lattner   void VisitPredefinedExpr(const PredefinedExpr *E) {
1052f343dd5SChris Lattner     EmitAggLoadOfLValue(E);
1062f343dd5SChris Lattner   }
107bc7d67ceSMike Stump 
1087a51313dSChris Lattner   // Operators.
109ec143777SAnders Carlsson   void VisitCastExpr(CastExpr *E);
1107a51313dSChris Lattner   void VisitCallExpr(const CallExpr *E);
1117a51313dSChris Lattner   void VisitStmtExpr(const StmtExpr *E);
1127a51313dSChris Lattner   void VisitBinaryOperator(const BinaryOperator *BO);
113ffba662dSFariborz Jahanian   void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
1147a51313dSChris Lattner   void VisitBinAssign(const BinaryOperator *E);
1154b0e2a30SEli Friedman   void VisitBinComma(const BinaryOperator *E);
1167a51313dSChris Lattner 
117b1d329daSChris Lattner   void VisitObjCMessageExpr(ObjCMessageExpr *E);
118c8317a44SDaniel Dunbar   void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
119c8317a44SDaniel Dunbar     EmitAggLoadOfLValue(E);
120c8317a44SDaniel Dunbar   }
12155310df7SDaniel Dunbar   void VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E);
1227a51313dSChris Lattner 
123c07a0c7eSJohn McCall   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
1245b2095ceSAnders Carlsson   void VisitChooseExpr(const ChooseExpr *CE);
1257a51313dSChris Lattner   void VisitInitListExpr(InitListExpr *E);
12618ada985SAnders Carlsson   void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
127aa9c7aedSChris Lattner   void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
128aa9c7aedSChris Lattner     Visit(DAE->getExpr());
129aa9c7aedSChris Lattner   }
1303be22e27SAnders Carlsson   void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
1311619a504SAnders Carlsson   void VisitCXXConstructExpr(const CXXConstructExpr *E);
1325d413781SJohn McCall   void VisitExprWithCleanups(ExprWithCleanups *E);
133747eb784SDouglas Gregor   void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
1345bbbb137SMike Stump   void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
135fe31481fSDouglas Gregor   void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
1361bf5846aSJohn McCall   void VisitOpaqueValueExpr(OpaqueValueExpr *E);
1371bf5846aSJohn McCall 
13821911e89SEli Friedman   void VisitVAArgExpr(VAArgExpr *E);
139579a05d7SChris Lattner 
1401553b190SJohn McCall   void EmitInitializationToLValue(Expr *E, LValue Address);
1411553b190SJohn McCall   void EmitNullInitializationToLValue(LValue Address);
1427a51313dSChris Lattner   //  case Expr::ChooseExprClass:
143f16b8c30SMike Stump   void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
1447a51313dSChris Lattner };
1457a51313dSChris Lattner }  // end anonymous namespace.
1467a51313dSChris Lattner 
1477a51313dSChris Lattner //===----------------------------------------------------------------------===//
1487a51313dSChris Lattner //                                Utilities
1497a51313dSChris Lattner //===----------------------------------------------------------------------===//
1507a51313dSChris Lattner 
1517a51313dSChris Lattner /// EmitAggLoadOfLValue - Given an expression with aggregate type that
1527a51313dSChris Lattner /// represents a value lvalue, this method emits the address of the lvalue,
1537a51313dSChris Lattner /// then loads the result into DestPtr.
1547a51313dSChris Lattner void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
1557a51313dSChris Lattner   LValue LV = CGF.EmitLValue(E);
156ca9fc09cSMike Stump   EmitFinalDestCopy(E, LV);
157ca9fc09cSMike Stump }
158ca9fc09cSMike Stump 
159cc04e9f6SJohn McCall /// \brief True if the given aggregate type requires special GC API calls.
160cc04e9f6SJohn McCall bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
161cc04e9f6SJohn McCall   // Only record types have members that might require garbage collection.
162cc04e9f6SJohn McCall   const RecordType *RecordTy = T->getAs<RecordType>();
163cc04e9f6SJohn McCall   if (!RecordTy) return false;
164cc04e9f6SJohn McCall 
165cc04e9f6SJohn McCall   // Don't mess with non-trivial C++ types.
166cc04e9f6SJohn McCall   RecordDecl *Record = RecordTy->getDecl();
167cc04e9f6SJohn McCall   if (isa<CXXRecordDecl>(Record) &&
168cc04e9f6SJohn McCall       (!cast<CXXRecordDecl>(Record)->hasTrivialCopyConstructor() ||
169cc04e9f6SJohn McCall        !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
170cc04e9f6SJohn McCall     return false;
171cc04e9f6SJohn McCall 
172cc04e9f6SJohn McCall   // Check whether the type has an object member.
173cc04e9f6SJohn McCall   return Record->hasObjectMember();
174cc04e9f6SJohn McCall }
175cc04e9f6SJohn McCall 
176cc04e9f6SJohn McCall /// \brief Perform the final move to DestPtr if RequiresGCollection is set.
177cc04e9f6SJohn McCall ///
178cc04e9f6SJohn McCall /// The idea is that you do something like this:
179cc04e9f6SJohn McCall ///   RValue Result = EmitSomething(..., getReturnValueSlot());
180cc04e9f6SJohn McCall ///   EmitGCMove(E, Result);
181cc04e9f6SJohn McCall /// If GC doesn't interfere, this will cause the result to be emitted
182cc04e9f6SJohn McCall /// directly into the return value slot.  If GC does interfere, a final
183cc04e9f6SJohn McCall /// move will be performed.
184cc04e9f6SJohn McCall void AggExprEmitter::EmitGCMove(const Expr *E, RValue Src) {
18558649dc6SJohn McCall   if (Dest.requiresGCollection()) {
1863b4bd9a1SKen Dyck     CharUnits size = CGF.getContext().getTypeSizeInChars(E->getType());
187*2192fe50SChris Lattner     llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
1883b4bd9a1SKen Dyck     llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
1897a626f63SJohn McCall     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF, Dest.getAddr(),
190cc04e9f6SJohn McCall                                                     Src.getAggregateAddr(),
191021510e9SFariborz Jahanian                                                     SizeVal);
192021510e9SFariborz Jahanian   }
193cc04e9f6SJohn McCall }
194cc04e9f6SJohn McCall 
195ca9fc09cSMike Stump /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
196ec3cbfe8SMike Stump void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) {
197ca9fc09cSMike Stump   assert(Src.isAggregate() && "value must be aggregate value!");
1987a51313dSChris Lattner 
1997a626f63SJohn McCall   // If Dest is ignored, then we're evaluating an aggregate expression
2008d752430SJohn McCall   // in a context (like an expression statement) that doesn't care
2018d752430SJohn McCall   // about the result.  C says that an lvalue-to-rvalue conversion is
2028d752430SJohn McCall   // performed in these cases; C++ says that it is not.  In either
2038d752430SJohn McCall   // case, we don't actually need to do anything unless the value is
2048d752430SJohn McCall   // volatile.
2057a626f63SJohn McCall   if (Dest.isIgnored()) {
2068d752430SJohn McCall     if (!Src.isVolatileQualified() ||
2078d752430SJohn McCall         CGF.CGM.getLangOptions().CPlusPlus ||
2088d752430SJohn McCall         (IgnoreResult && Ignore))
209ec3cbfe8SMike Stump       return;
210c123623dSFariborz Jahanian 
211332ec2ceSMike Stump     // If the source is volatile, we must read from it; to do that, we need
212332ec2ceSMike Stump     // some place to put it.
2137a626f63SJohn McCall     Dest = CGF.CreateAggTemp(E->getType(), "agg.tmp");
214332ec2ceSMike Stump   }
2157a51313dSChris Lattner 
21658649dc6SJohn McCall   if (Dest.requiresGCollection()) {
2173b4bd9a1SKen Dyck     CharUnits size = CGF.getContext().getTypeSizeInChars(E->getType());
218*2192fe50SChris Lattner     llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
2193b4bd9a1SKen Dyck     llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
220879d7266SFariborz Jahanian     CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
2217a626f63SJohn McCall                                                       Dest.getAddr(),
2227a626f63SJohn McCall                                                       Src.getAggregateAddr(),
223021510e9SFariborz Jahanian                                                       SizeVal);
224879d7266SFariborz Jahanian     return;
225879d7266SFariborz Jahanian   }
226ca9fc09cSMike Stump   // If the result of the assignment is used, copy the LHS there also.
227ca9fc09cSMike Stump   // FIXME: Pass VolatileDest as well.  I think we also need to merge volatile
228ca9fc09cSMike Stump   // from the source as well, as we can't eliminate it if either operand
229ca9fc09cSMike Stump   // is volatile, unless copy has volatile for both source and destination..
2307a626f63SJohn McCall   CGF.EmitAggregateCopy(Dest.getAddr(), Src.getAggregateAddr(), E->getType(),
2317a626f63SJohn McCall                         Dest.isVolatile()|Src.isVolatileQualified());
232ca9fc09cSMike Stump }
233ca9fc09cSMike Stump 
234ca9fc09cSMike Stump /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
235ec3cbfe8SMike Stump void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) {
236ca9fc09cSMike Stump   assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc");
237ca9fc09cSMike Stump 
238ca9fc09cSMike Stump   EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(),
239ec3cbfe8SMike Stump                                             Src.isVolatileQualified()),
240ec3cbfe8SMike Stump                     Ignore);
2417a51313dSChris Lattner }
2427a51313dSChris Lattner 
2437a51313dSChris Lattner //===----------------------------------------------------------------------===//
2447a51313dSChris Lattner //                            Visitor Methods
2457a51313dSChris Lattner //===----------------------------------------------------------------------===//
2467a51313dSChris Lattner 
247fe31481fSDouglas Gregor void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
248fe31481fSDouglas Gregor   Visit(E->GetTemporaryExpr());
249fe31481fSDouglas Gregor }
250fe31481fSDouglas Gregor 
2511bf5846aSJohn McCall void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
252c07a0c7eSJohn McCall   EmitFinalDestCopy(e, CGF.getOpaqueLValueMapping(e));
2531bf5846aSJohn McCall }
2541bf5846aSJohn McCall 
2559b71f0cfSDouglas Gregor void
2569b71f0cfSDouglas Gregor AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
2576c9d31ebSDouglas Gregor   if (E->getType().isPODType(CGF.getContext())) {
2586c9d31ebSDouglas Gregor     // For a POD type, just emit a load of the lvalue + a copy, because our
2596c9d31ebSDouglas Gregor     // compound literal might alias the destination.
2606c9d31ebSDouglas Gregor     // FIXME: This is a band-aid; the real problem appears to be in our handling
2616c9d31ebSDouglas Gregor     // of assignments, where we store directly into the LHS without checking
2626c9d31ebSDouglas Gregor     // whether anything in the RHS aliases.
2636c9d31ebSDouglas Gregor     EmitAggLoadOfLValue(E);
2646c9d31ebSDouglas Gregor     return;
2656c9d31ebSDouglas Gregor   }
2666c9d31ebSDouglas Gregor 
2679b71f0cfSDouglas Gregor   AggValueSlot Slot = EnsureSlot(E->getType());
2689b71f0cfSDouglas Gregor   CGF.EmitAggExpr(E->getInitializer(), Slot);
2699b71f0cfSDouglas Gregor }
2709b71f0cfSDouglas Gregor 
2719b71f0cfSDouglas Gregor 
272ec143777SAnders Carlsson void AggExprEmitter::VisitCastExpr(CastExpr *E) {
2731fb7ae9eSAnders Carlsson   switch (E->getCastKind()) {
2748a01a751SAnders Carlsson   case CK_Dynamic: {
2751c073f47SDouglas Gregor     assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
2761c073f47SDouglas Gregor     LValue LV = CGF.EmitCheckedLValue(E->getSubExpr());
2771c073f47SDouglas Gregor     // FIXME: Do we also need to handle property references here?
2781c073f47SDouglas Gregor     if (LV.isSimple())
2791c073f47SDouglas Gregor       CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
2801c073f47SDouglas Gregor     else
2811c073f47SDouglas Gregor       CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
2821c073f47SDouglas Gregor 
2837a626f63SJohn McCall     if (!Dest.isIgnored())
2841c073f47SDouglas Gregor       CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
2851c073f47SDouglas Gregor     break;
2861c073f47SDouglas Gregor   }
2871c073f47SDouglas Gregor 
288e302792bSJohn McCall   case CK_ToUnion: {
28958989b71SJohn McCall     if (Dest.isIgnored()) break;
29058989b71SJohn McCall 
2917ffcf93bSNuno Lopes     // GCC union extension
2922e442a00SDaniel Dunbar     QualType Ty = E->getSubExpr()->getType();
2932e442a00SDaniel Dunbar     QualType PtrTy = CGF.getContext().getPointerType(Ty);
2947a626f63SJohn McCall     llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
295dd274848SEli Friedman                                                  CGF.ConvertType(PtrTy));
2961553b190SJohn McCall     EmitInitializationToLValue(E->getSubExpr(),
2971553b190SJohn McCall                                CGF.MakeAddrLValue(CastPtr, Ty));
2981fb7ae9eSAnders Carlsson     break;
2997ffcf93bSNuno Lopes   }
3007ffcf93bSNuno Lopes 
301e302792bSJohn McCall   case CK_DerivedToBase:
302e302792bSJohn McCall   case CK_BaseToDerived:
303e302792bSJohn McCall   case CK_UncheckedDerivedToBase: {
304aae38d66SDouglas Gregor     assert(0 && "cannot perform hierarchy conversion in EmitAggExpr: "
305aae38d66SDouglas Gregor                 "should have been unpacked before we got here");
306aae38d66SDouglas Gregor     break;
307aae38d66SDouglas Gregor   }
308aae38d66SDouglas Gregor 
30934376a68SJohn McCall   case CK_GetObjCProperty: {
31034376a68SJohn McCall     LValue LV = CGF.EmitLValue(E->getSubExpr());
31134376a68SJohn McCall     assert(LV.isPropertyRef());
31234376a68SJohn McCall     RValue RV = CGF.EmitLoadOfPropertyRefLValue(LV, getReturnValueSlot());
31334376a68SJohn McCall     EmitGCMove(E, RV);
31434376a68SJohn McCall     break;
31534376a68SJohn McCall   }
31634376a68SJohn McCall 
31734376a68SJohn McCall   case CK_LValueToRValue: // hope for downstream optimization
318e302792bSJohn McCall   case CK_NoOp:
319e302792bSJohn McCall   case CK_UserDefinedConversion:
320e302792bSJohn McCall   case CK_ConstructorConversion:
3212a69547fSEli Friedman     assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
3222a69547fSEli Friedman                                                    E->getType()) &&
3230f398c44SChris Lattner            "Implicit cast types must be compatible");
3247a51313dSChris Lattner     Visit(E->getSubExpr());
3251fb7ae9eSAnders Carlsson     break;
326b05a3e55SAnders Carlsson 
327e302792bSJohn McCall   case CK_LValueBitCast:
328f3735e01SJohn McCall     llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
32951954276SDouglas Gregor     break;
33031996343SJohn McCall 
331f3735e01SJohn McCall   case CK_Dependent:
332f3735e01SJohn McCall   case CK_BitCast:
333f3735e01SJohn McCall   case CK_ArrayToPointerDecay:
334f3735e01SJohn McCall   case CK_FunctionToPointerDecay:
335f3735e01SJohn McCall   case CK_NullToPointer:
336f3735e01SJohn McCall   case CK_NullToMemberPointer:
337f3735e01SJohn McCall   case CK_BaseToDerivedMemberPointer:
338f3735e01SJohn McCall   case CK_DerivedToBaseMemberPointer:
339f3735e01SJohn McCall   case CK_MemberPointerToBoolean:
340f3735e01SJohn McCall   case CK_IntegralToPointer:
341f3735e01SJohn McCall   case CK_PointerToIntegral:
342f3735e01SJohn McCall   case CK_PointerToBoolean:
343f3735e01SJohn McCall   case CK_ToVoid:
344f3735e01SJohn McCall   case CK_VectorSplat:
345f3735e01SJohn McCall   case CK_IntegralCast:
346f3735e01SJohn McCall   case CK_IntegralToBoolean:
347f3735e01SJohn McCall   case CK_IntegralToFloating:
348f3735e01SJohn McCall   case CK_FloatingToIntegral:
349f3735e01SJohn McCall   case CK_FloatingToBoolean:
350f3735e01SJohn McCall   case CK_FloatingCast:
351f3735e01SJohn McCall   case CK_AnyPointerToObjCPointerCast:
352f3735e01SJohn McCall   case CK_AnyPointerToBlockPointerCast:
353f3735e01SJohn McCall   case CK_ObjCObjectLValueCast:
354f3735e01SJohn McCall   case CK_FloatingRealToComplex:
355f3735e01SJohn McCall   case CK_FloatingComplexToReal:
356f3735e01SJohn McCall   case CK_FloatingComplexToBoolean:
357f3735e01SJohn McCall   case CK_FloatingComplexCast:
358f3735e01SJohn McCall   case CK_FloatingComplexToIntegralComplex:
359f3735e01SJohn McCall   case CK_IntegralRealToComplex:
360f3735e01SJohn McCall   case CK_IntegralComplexToReal:
361f3735e01SJohn McCall   case CK_IntegralComplexToBoolean:
362f3735e01SJohn McCall   case CK_IntegralComplexCast:
363f3735e01SJohn McCall   case CK_IntegralComplexToFloatingComplex:
36431168b07SJohn McCall   case CK_ObjCProduceObject:
36531168b07SJohn McCall   case CK_ObjCConsumeObject:
3664db5c3c8SJohn McCall   case CK_ObjCReclaimReturnedObject:
367f3735e01SJohn McCall     llvm_unreachable("cast kind invalid for aggregate types");
3681fb7ae9eSAnders Carlsson   }
3697a51313dSChris Lattner }
3707a51313dSChris Lattner 
3710f398c44SChris Lattner void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
372ddcbfe7bSAnders Carlsson   if (E->getCallReturnType()->isReferenceType()) {
373ddcbfe7bSAnders Carlsson     EmitAggLoadOfLValue(E);
374ddcbfe7bSAnders Carlsson     return;
375ddcbfe7bSAnders Carlsson   }
376ddcbfe7bSAnders Carlsson 
377cc04e9f6SJohn McCall   RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
378cc04e9f6SJohn McCall   EmitGCMove(E, RV);
3797a51313dSChris Lattner }
3800f398c44SChris Lattner 
3810f398c44SChris Lattner void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
382cc04e9f6SJohn McCall   RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
383cc04e9f6SJohn McCall   EmitGCMove(E, RV);
384b1d329daSChris Lattner }
3857a51313dSChris Lattner 
38655310df7SDaniel Dunbar void AggExprEmitter::VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
38734376a68SJohn McCall   llvm_unreachable("direct property access not surrounded by "
38834376a68SJohn McCall                    "lvalue-to-rvalue cast");
38955310df7SDaniel Dunbar }
39055310df7SDaniel Dunbar 
3910f398c44SChris Lattner void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
392a2342eb8SJohn McCall   CGF.EmitIgnoredExpr(E->getLHS());
3937a626f63SJohn McCall   Visit(E->getRHS());
3944b0e2a30SEli Friedman }
3954b0e2a30SEli Friedman 
3967a51313dSChris Lattner void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
397ce1de617SJohn McCall   CodeGenFunction::StmtExprEvaluation eval(CGF);
3987a626f63SJohn McCall   CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
3997a51313dSChris Lattner }
4007a51313dSChris Lattner 
4017a51313dSChris Lattner void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
402e302792bSJohn McCall   if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
403ffba662dSFariborz Jahanian     VisitPointerToDataMemberBinaryOperator(E);
404ffba662dSFariborz Jahanian   else
405a7c8cf62SDaniel Dunbar     CGF.ErrorUnsupported(E, "aggregate binary expression");
4067a51313dSChris Lattner }
4077a51313dSChris Lattner 
408ffba662dSFariborz Jahanian void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
409ffba662dSFariborz Jahanian                                                     const BinaryOperator *E) {
410ffba662dSFariborz Jahanian   LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
411ffba662dSFariborz Jahanian   EmitFinalDestCopy(E, LV);
412ffba662dSFariborz Jahanian }
413ffba662dSFariborz Jahanian 
4147a51313dSChris Lattner void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
4157a51313dSChris Lattner   // For an assignment to work, the value on the right has
4167a51313dSChris Lattner   // to be compatible with the value on the left.
4172a69547fSEli Friedman   assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
4182a69547fSEli Friedman                                                  E->getRHS()->getType())
4197a51313dSChris Lattner          && "Invalid assignment");
420d0a30016SJohn McCall 
42199514b91SFariborz Jahanian   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getLHS()))
42252a8cca5SFariborz Jahanian     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
42399514b91SFariborz Jahanian       if (VD->hasAttr<BlocksAttr>() &&
42499514b91SFariborz Jahanian           E->getRHS()->HasSideEffects(CGF.getContext())) {
42599514b91SFariborz Jahanian         // When __block variable on LHS, the RHS must be evaluated first
42699514b91SFariborz Jahanian         // as it may change the 'forwarding' field via call to Block_copy.
42799514b91SFariborz Jahanian         LValue RHS = CGF.EmitLValue(E->getRHS());
42899514b91SFariborz Jahanian         LValue LHS = CGF.EmitLValue(E->getLHS());
42999514b91SFariborz Jahanian         bool GCollection = false;
43099514b91SFariborz Jahanian         if (CGF.getContext().getLangOptions().getGCMode())
43199514b91SFariborz Jahanian           GCollection = TypeRequiresGCollection(E->getLHS()->getType());
43299514b91SFariborz Jahanian         Dest = AggValueSlot::forLValue(LHS, true, GCollection);
43399514b91SFariborz Jahanian         EmitFinalDestCopy(E, RHS, true);
43499514b91SFariborz Jahanian         return;
43599514b91SFariborz Jahanian       }
43699514b91SFariborz Jahanian 
4377a51313dSChris Lattner   LValue LHS = CGF.EmitLValue(E->getLHS());
4387a51313dSChris Lattner 
4394b8c6db9SDaniel Dunbar   // We have to special case property setters, otherwise we must have
4404b8c6db9SDaniel Dunbar   // a simple lvalue (no aggregates inside vectors, bitfields).
4414b8c6db9SDaniel Dunbar   if (LHS.isPropertyRef()) {
4427a26ba4dSFariborz Jahanian     const ObjCPropertyRefExpr *RE = LHS.getPropertyRefExpr();
4437a26ba4dSFariborz Jahanian     QualType ArgType = RE->getSetterArgType();
4447a26ba4dSFariborz Jahanian     RValue Src;
4457a26ba4dSFariborz Jahanian     if (ArgType->isReferenceType())
4467a26ba4dSFariborz Jahanian       Src = CGF.EmitReferenceBindingToExpr(E->getRHS(), 0);
4477a26ba4dSFariborz Jahanian     else {
4487a626f63SJohn McCall       AggValueSlot Slot = EnsureSlot(E->getRHS()->getType());
4497a626f63SJohn McCall       CGF.EmitAggExpr(E->getRHS(), Slot);
4507a26ba4dSFariborz Jahanian       Src = Slot.asRValue();
4517a26ba4dSFariborz Jahanian     }
4527a26ba4dSFariborz Jahanian     CGF.EmitStoreThroughPropertyRefLValue(Src, LHS);
4534b8c6db9SDaniel Dunbar   } else {
454b60e70f9SFariborz Jahanian     bool GCollection = false;
455cc04e9f6SJohn McCall     if (CGF.getContext().getLangOptions().getGCMode())
456b60e70f9SFariborz Jahanian       GCollection = TypeRequiresGCollection(E->getLHS()->getType());
457cc04e9f6SJohn McCall 
4587a51313dSChris Lattner     // Codegen the RHS so that it stores directly into the LHS.
459b60e70f9SFariborz Jahanian     AggValueSlot LHSSlot = AggValueSlot::forLValue(LHS, true,
460b60e70f9SFariborz Jahanian                                                    GCollection);
461b60e70f9SFariborz Jahanian     CGF.EmitAggExpr(E->getRHS(), LHSSlot, false);
462ec3cbfe8SMike Stump     EmitFinalDestCopy(E, LHS, true);
4637a51313dSChris Lattner   }
4644b8c6db9SDaniel Dunbar }
4657a51313dSChris Lattner 
466c07a0c7eSJohn McCall void AggExprEmitter::
467c07a0c7eSJohn McCall VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
468a612e79bSDaniel Dunbar   llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
469a612e79bSDaniel Dunbar   llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
470a612e79bSDaniel Dunbar   llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
4717a51313dSChris Lattner 
472c07a0c7eSJohn McCall   // Bind the common expression if necessary.
473c07a0c7eSJohn McCall   CodeGenFunction::OpaqueValueMapping binding(CGF, E);
474c07a0c7eSJohn McCall 
475ce1de617SJohn McCall   CodeGenFunction::ConditionalEvaluation eval(CGF);
476b8841af8SEli Friedman   CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
4777a51313dSChris Lattner 
4785b26f65bSJohn McCall   // Save whether the destination's lifetime is externally managed.
4795b26f65bSJohn McCall   bool DestLifetimeManaged = Dest.isLifetimeExternallyManaged();
4807a51313dSChris Lattner 
481ce1de617SJohn McCall   eval.begin(CGF);
482ce1de617SJohn McCall   CGF.EmitBlock(LHSBlock);
483c07a0c7eSJohn McCall   Visit(E->getTrueExpr());
484ce1de617SJohn McCall   eval.end(CGF);
4857a51313dSChris Lattner 
486ce1de617SJohn McCall   assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
487ce1de617SJohn McCall   CGF.Builder.CreateBr(ContBlock);
4887a51313dSChris Lattner 
4895b26f65bSJohn McCall   // If the result of an agg expression is unused, then the emission
4905b26f65bSJohn McCall   // of the LHS might need to create a destination slot.  That's fine
4915b26f65bSJohn McCall   // with us, and we can safely emit the RHS into the same slot, but
4925b26f65bSJohn McCall   // we shouldn't claim that its lifetime is externally managed.
4935b26f65bSJohn McCall   Dest.setLifetimeExternallyManaged(DestLifetimeManaged);
4945b26f65bSJohn McCall 
495ce1de617SJohn McCall   eval.begin(CGF);
496ce1de617SJohn McCall   CGF.EmitBlock(RHSBlock);
497c07a0c7eSJohn McCall   Visit(E->getFalseExpr());
498ce1de617SJohn McCall   eval.end(CGF);
4997a51313dSChris Lattner 
5007a51313dSChris Lattner   CGF.EmitBlock(ContBlock);
5017a51313dSChris Lattner }
5027a51313dSChris Lattner 
5035b2095ceSAnders Carlsson void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
5045b2095ceSAnders Carlsson   Visit(CE->getChosenSubExpr(CGF.getContext()));
5055b2095ceSAnders Carlsson }
5065b2095ceSAnders Carlsson 
50721911e89SEli Friedman void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
508e9fcadd2SDaniel Dunbar   llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
50913abd7e9SAnders Carlsson   llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
51013abd7e9SAnders Carlsson 
511020cddcfSSebastian Redl   if (!ArgPtr) {
51213abd7e9SAnders Carlsson     CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
513020cddcfSSebastian Redl     return;
514020cddcfSSebastian Redl   }
51513abd7e9SAnders Carlsson 
5162e442a00SDaniel Dunbar   EmitFinalDestCopy(VE, CGF.MakeAddrLValue(ArgPtr, VE->getType()));
51721911e89SEli Friedman }
51821911e89SEli Friedman 
5193be22e27SAnders Carlsson void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
5207a626f63SJohn McCall   // Ensure that we have a slot, but if we already do, remember
5217a626f63SJohn McCall   // whether its lifetime was externally managed.
5227a626f63SJohn McCall   bool WasManaged = Dest.isLifetimeExternallyManaged();
5237a626f63SJohn McCall   Dest = EnsureSlot(E->getType());
5247a626f63SJohn McCall   Dest.setLifetimeExternallyManaged();
5253be22e27SAnders Carlsson 
5263be22e27SAnders Carlsson   Visit(E->getSubExpr());
5273be22e27SAnders Carlsson 
5287a626f63SJohn McCall   // Set up the temporary's destructor if its lifetime wasn't already
5297a626f63SJohn McCall   // being managed.
5307a626f63SJohn McCall   if (!WasManaged)
5317a626f63SJohn McCall     CGF.EmitCXXTemporary(E->getTemporary(), Dest.getAddr());
5323be22e27SAnders Carlsson }
5333be22e27SAnders Carlsson 
534b7f8f594SAnders Carlsson void
5351619a504SAnders Carlsson AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5367a626f63SJohn McCall   AggValueSlot Slot = EnsureSlot(E->getType());
5377a626f63SJohn McCall   CGF.EmitCXXConstructExpr(E, Slot);
538c82b86dfSAnders Carlsson }
539c82b86dfSAnders Carlsson 
5405d413781SJohn McCall void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
5415d413781SJohn McCall   CGF.EmitExprWithCleanups(E, Dest);
542b7f8f594SAnders Carlsson }
543b7f8f594SAnders Carlsson 
544747eb784SDouglas Gregor void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
5457a626f63SJohn McCall   QualType T = E->getType();
5467a626f63SJohn McCall   AggValueSlot Slot = EnsureSlot(T);
5471553b190SJohn McCall   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
54818ada985SAnders Carlsson }
54918ada985SAnders Carlsson 
55018ada985SAnders Carlsson void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
5517a626f63SJohn McCall   QualType T = E->getType();
5527a626f63SJohn McCall   AggValueSlot Slot = EnsureSlot(T);
5531553b190SJohn McCall   EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
554ff3507b9SNuno Lopes }
555ff3507b9SNuno Lopes 
55627a3631bSChris Lattner /// isSimpleZero - If emitting this value will obviously just cause a store of
55727a3631bSChris Lattner /// zero to memory, return true.  This can return false if uncertain, so it just
55827a3631bSChris Lattner /// handles simple cases.
55927a3631bSChris Lattner static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
56091147596SPeter Collingbourne   E = E->IgnoreParens();
56191147596SPeter Collingbourne 
56227a3631bSChris Lattner   // 0
56327a3631bSChris Lattner   if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
56427a3631bSChris Lattner     return IL->getValue() == 0;
56527a3631bSChris Lattner   // +0.0
56627a3631bSChris Lattner   if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
56727a3631bSChris Lattner     return FL->getValue().isPosZero();
56827a3631bSChris Lattner   // int()
56927a3631bSChris Lattner   if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
57027a3631bSChris Lattner       CGF.getTypes().isZeroInitializable(E->getType()))
57127a3631bSChris Lattner     return true;
57227a3631bSChris Lattner   // (int*)0 - Null pointer expressions.
57327a3631bSChris Lattner   if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
57427a3631bSChris Lattner     return ICE->getCastKind() == CK_NullToPointer;
57527a3631bSChris Lattner   // '\0'
57627a3631bSChris Lattner   if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
57727a3631bSChris Lattner     return CL->getValue() == 0;
57827a3631bSChris Lattner 
57927a3631bSChris Lattner   // Otherwise, hard case: conservatively return false.
58027a3631bSChris Lattner   return false;
58127a3631bSChris Lattner }
58227a3631bSChris Lattner 
58327a3631bSChris Lattner 
584b247350eSAnders Carlsson void
5851553b190SJohn McCall AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) {
5861553b190SJohn McCall   QualType type = LV.getType();
587df0fe27bSMike Stump   // FIXME: Ignore result?
588579a05d7SChris Lattner   // FIXME: Are initializers affected by volatile?
58927a3631bSChris Lattner   if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
59027a3631bSChris Lattner     // Storing "i32 0" to a zero'd memory location is a noop.
59127a3631bSChris Lattner   } else if (isa<ImplicitValueInitExpr>(E)) {
5921553b190SJohn McCall     EmitNullInitializationToLValue(LV);
5931553b190SJohn McCall   } else if (type->isReferenceType()) {
59404775f84SAnders Carlsson     RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
59555e1fbc8SJohn McCall     CGF.EmitStoreThroughLValue(RV, LV);
5961553b190SJohn McCall   } else if (type->isAnyComplexType()) {
5970202cb40SDouglas Gregor     CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
5981553b190SJohn McCall   } else if (CGF.hasAggregateLLVMType(type)) {
5991553b190SJohn McCall     CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV, true, false,
6001553b190SJohn McCall                                                Dest.isZeroed()));
60131168b07SJohn McCall   } else if (LV.isSimple()) {
6021553b190SJohn McCall     CGF.EmitScalarInit(E, /*D=*/0, LV, /*Captured=*/false);
6036e313210SEli Friedman   } else {
60455e1fbc8SJohn McCall     CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
6057a51313dSChris Lattner   }
606579a05d7SChris Lattner }
607579a05d7SChris Lattner 
6081553b190SJohn McCall void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
6091553b190SJohn McCall   QualType type = lv.getType();
6101553b190SJohn McCall 
61127a3631bSChris Lattner   // If the destination slot is already zeroed out before the aggregate is
61227a3631bSChris Lattner   // copied into it, we don't have to emit any zeros here.
6131553b190SJohn McCall   if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
61427a3631bSChris Lattner     return;
61527a3631bSChris Lattner 
6161553b190SJohn McCall   if (!CGF.hasAggregateLLVMType(type)) {
617579a05d7SChris Lattner     // For non-aggregates, we can store zero
6181553b190SJohn McCall     llvm::Value *null = llvm::Constant::getNullValue(CGF.ConvertType(type));
61955e1fbc8SJohn McCall     CGF.EmitStoreThroughLValue(RValue::get(null), lv);
620579a05d7SChris Lattner   } else {
621579a05d7SChris Lattner     // There's a potential optimization opportunity in combining
622579a05d7SChris Lattner     // memsets; that would be easy for arrays, but relatively
623579a05d7SChris Lattner     // difficult for structures with the current code.
6241553b190SJohn McCall     CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
625579a05d7SChris Lattner   }
626579a05d7SChris Lattner }
627579a05d7SChris Lattner 
628579a05d7SChris Lattner void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
629f5d08c9eSEli Friedman #if 0
6306d11ec8cSEli Friedman   // FIXME: Assess perf here?  Figure out what cases are worth optimizing here
6316d11ec8cSEli Friedman   // (Length of globals? Chunks of zeroed-out space?).
632f5d08c9eSEli Friedman   //
63318bb9284SMike Stump   // If we can, prefer a copy from a global; this is a lot less code for long
63418bb9284SMike Stump   // globals, and it's easier for the current optimizers to analyze.
6356d11ec8cSEli Friedman   if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
636c59bb48eSEli Friedman     llvm::GlobalVariable* GV =
6376d11ec8cSEli Friedman     new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
6386d11ec8cSEli Friedman                              llvm::GlobalValue::InternalLinkage, C, "");
6392e442a00SDaniel Dunbar     EmitFinalDestCopy(E, CGF.MakeAddrLValue(GV, E->getType()));
640c59bb48eSEli Friedman     return;
641c59bb48eSEli Friedman   }
642f5d08c9eSEli Friedman #endif
643f53c0968SChris Lattner   if (E->hadArrayRangeDesignator())
644bf7207a1SDouglas Gregor     CGF.ErrorUnsupported(E, "GNU array range designator extension");
645bf7207a1SDouglas Gregor 
6467a626f63SJohn McCall   llvm::Value *DestPtr = Dest.getAddr();
6477a626f63SJohn McCall 
648579a05d7SChris Lattner   // Handle initialization of an array.
649579a05d7SChris Lattner   if (E->getType()->isArrayType()) {
650*2192fe50SChris Lattner     llvm::PointerType *APType =
651579a05d7SChris Lattner       cast<llvm::PointerType>(DestPtr->getType());
652*2192fe50SChris Lattner     llvm::ArrayType *AType =
653579a05d7SChris Lattner       cast<llvm::ArrayType>(APType->getElementType());
654579a05d7SChris Lattner 
655579a05d7SChris Lattner     uint64_t NumInitElements = E->getNumInits();
656f23b6fa4SEli Friedman 
6570f398c44SChris Lattner     if (E->getNumInits() > 0) {
6580f398c44SChris Lattner       QualType T1 = E->getType();
6590f398c44SChris Lattner       QualType T2 = E->getInit(0)->getType();
6602a69547fSEli Friedman       if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
661f23b6fa4SEli Friedman         EmitAggLoadOfLValue(E->getInit(0));
662f23b6fa4SEli Friedman         return;
663f23b6fa4SEli Friedman       }
6640f398c44SChris Lattner     }
665f23b6fa4SEli Friedman 
666579a05d7SChris Lattner     uint64_t NumArrayElements = AType->getNumElements();
66782fe67bbSJohn McCall     assert(NumInitElements <= NumArrayElements);
668579a05d7SChris Lattner 
66982fe67bbSJohn McCall     QualType elementType = E->getType().getCanonicalType();
67082fe67bbSJohn McCall     elementType = CGF.getContext().getQualifiedType(
67182fe67bbSJohn McCall                     cast<ArrayType>(elementType)->getElementType(),
67282fe67bbSJohn McCall                     elementType.getQualifiers() + Dest.getQualifiers());
67382fe67bbSJohn McCall 
67482fe67bbSJohn McCall     // DestPtr is an array*.  Construct an elementType* by drilling
67582fe67bbSJohn McCall     // down a level.
67682fe67bbSJohn McCall     llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
67782fe67bbSJohn McCall     llvm::Value *indices[] = { zero, zero };
67882fe67bbSJohn McCall     llvm::Value *begin =
67982fe67bbSJohn McCall       Builder.CreateInBoundsGEP(DestPtr, indices, indices+2, "arrayinit.begin");
68082fe67bbSJohn McCall 
68182fe67bbSJohn McCall     // Exception safety requires us to destroy all the
68282fe67bbSJohn McCall     // already-constructed members if an initializer throws.
68382fe67bbSJohn McCall     // For that, we'll need an EH cleanup.
68482fe67bbSJohn McCall     QualType::DestructionKind dtorKind = elementType.isDestructedType();
68582fe67bbSJohn McCall     llvm::AllocaInst *endOfInit = 0;
68682fe67bbSJohn McCall     EHScopeStack::stable_iterator cleanup;
68782fe67bbSJohn McCall     if (CGF.needsEHCleanup(dtorKind)) {
68882fe67bbSJohn McCall       // In principle we could tell the cleanup where we are more
68982fe67bbSJohn McCall       // directly, but the control flow can get so varied here that it
69082fe67bbSJohn McCall       // would actually be quite complex.  Therefore we go through an
69182fe67bbSJohn McCall       // alloca.
69282fe67bbSJohn McCall       endOfInit = CGF.CreateTempAlloca(begin->getType(),
69382fe67bbSJohn McCall                                        "arrayinit.endOfInit");
69482fe67bbSJohn McCall       Builder.CreateStore(begin, endOfInit);
695178360e1SJohn McCall       CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
696178360e1SJohn McCall                                            CGF.getDestroyer(dtorKind));
69782fe67bbSJohn McCall       cleanup = CGF.EHStack.stable_begin();
69882fe67bbSJohn McCall 
69982fe67bbSJohn McCall     // Otherwise, remember that we didn't need a cleanup.
70082fe67bbSJohn McCall     } else {
70182fe67bbSJohn McCall       dtorKind = QualType::DK_none;
702e07425a5SArgyrios Kyrtzidis     }
703e07425a5SArgyrios Kyrtzidis 
70482fe67bbSJohn McCall     llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
70527a3631bSChris Lattner 
70682fe67bbSJohn McCall     // The 'current element to initialize'.  The invariants on this
70782fe67bbSJohn McCall     // variable are complicated.  Essentially, after each iteration of
70882fe67bbSJohn McCall     // the loop, it points to the last initialized element, except
70982fe67bbSJohn McCall     // that it points to the beginning of the array before any
71082fe67bbSJohn McCall     // elements have been initialized.
71182fe67bbSJohn McCall     llvm::Value *element = begin;
71227a3631bSChris Lattner 
71382fe67bbSJohn McCall     // Emit the explicit initializers.
71482fe67bbSJohn McCall     for (uint64_t i = 0; i != NumInitElements; ++i) {
71582fe67bbSJohn McCall       // Advance to the next element.
716178360e1SJohn McCall       if (i > 0) {
71782fe67bbSJohn McCall         element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element");
71882fe67bbSJohn McCall 
719178360e1SJohn McCall         // Tell the cleanup that it needs to destroy up to this
720178360e1SJohn McCall         // element.  TODO: some of these stores can be trivially
721178360e1SJohn McCall         // observed to be unnecessary.
722178360e1SJohn McCall         if (endOfInit) Builder.CreateStore(element, endOfInit);
723178360e1SJohn McCall       }
724178360e1SJohn McCall 
72582fe67bbSJohn McCall       LValue elementLV = CGF.MakeAddrLValue(element, elementType);
72682fe67bbSJohn McCall       EmitInitializationToLValue(E->getInit(i), elementLV);
72782fe67bbSJohn McCall     }
72882fe67bbSJohn McCall 
72982fe67bbSJohn McCall     // Check whether there's a non-trivial array-fill expression.
73082fe67bbSJohn McCall     // Note that this will be a CXXConstructExpr even if the element
73182fe67bbSJohn McCall     // type is an array (or array of array, etc.) of class type.
73282fe67bbSJohn McCall     Expr *filler = E->getArrayFiller();
73382fe67bbSJohn McCall     bool hasTrivialFiller = true;
73482fe67bbSJohn McCall     if (CXXConstructExpr *cons = dyn_cast_or_null<CXXConstructExpr>(filler)) {
73582fe67bbSJohn McCall       assert(cons->getConstructor()->isDefaultConstructor());
73682fe67bbSJohn McCall       hasTrivialFiller = cons->getConstructor()->isTrivial();
73782fe67bbSJohn McCall     }
73882fe67bbSJohn McCall 
73982fe67bbSJohn McCall     // Any remaining elements need to be zero-initialized, possibly
74082fe67bbSJohn McCall     // using the filler expression.  We can skip this if the we're
74182fe67bbSJohn McCall     // emitting to zeroed memory.
74282fe67bbSJohn McCall     if (NumInitElements != NumArrayElements &&
74382fe67bbSJohn McCall         !(Dest.isZeroed() && hasTrivialFiller &&
74482fe67bbSJohn McCall           CGF.getTypes().isZeroInitializable(elementType))) {
74582fe67bbSJohn McCall 
74682fe67bbSJohn McCall       // Use an actual loop.  This is basically
74782fe67bbSJohn McCall       //   do { *array++ = filler; } while (array != end);
74882fe67bbSJohn McCall 
74982fe67bbSJohn McCall       // Advance to the start of the rest of the array.
750178360e1SJohn McCall       if (NumInitElements) {
75182fe67bbSJohn McCall         element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start");
752178360e1SJohn McCall         if (endOfInit) Builder.CreateStore(element, endOfInit);
753178360e1SJohn McCall       }
75482fe67bbSJohn McCall 
75582fe67bbSJohn McCall       // Compute the end of the array.
75682fe67bbSJohn McCall       llvm::Value *end = Builder.CreateInBoundsGEP(begin,
75782fe67bbSJohn McCall                         llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
75882fe67bbSJohn McCall                                                    "arrayinit.end");
75982fe67bbSJohn McCall 
76082fe67bbSJohn McCall       llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
76182fe67bbSJohn McCall       llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
76282fe67bbSJohn McCall 
76382fe67bbSJohn McCall       // Jump into the body.
76482fe67bbSJohn McCall       CGF.EmitBlock(bodyBB);
76582fe67bbSJohn McCall       llvm::PHINode *currentElement =
76682fe67bbSJohn McCall         Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
76782fe67bbSJohn McCall       currentElement->addIncoming(element, entryBB);
76882fe67bbSJohn McCall 
76982fe67bbSJohn McCall       // Emit the actual filler expression.
77082fe67bbSJohn McCall       LValue elementLV = CGF.MakeAddrLValue(currentElement, elementType);
77182fe67bbSJohn McCall       if (filler)
77282fe67bbSJohn McCall         EmitInitializationToLValue(filler, elementLV);
773579a05d7SChris Lattner       else
77482fe67bbSJohn McCall         EmitNullInitializationToLValue(elementLV);
77527a3631bSChris Lattner 
77682fe67bbSJohn McCall       // Move on to the next element.
77782fe67bbSJohn McCall       llvm::Value *nextElement =
77882fe67bbSJohn McCall         Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
77982fe67bbSJohn McCall 
780178360e1SJohn McCall       // Tell the EH cleanup that we finished with the last element.
781178360e1SJohn McCall       if (endOfInit) Builder.CreateStore(nextElement, endOfInit);
782178360e1SJohn McCall 
78382fe67bbSJohn McCall       // Leave the loop if we're done.
78482fe67bbSJohn McCall       llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
78582fe67bbSJohn McCall                                                "arrayinit.done");
78682fe67bbSJohn McCall       llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
78782fe67bbSJohn McCall       Builder.CreateCondBr(done, endBB, bodyBB);
78882fe67bbSJohn McCall       currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
78982fe67bbSJohn McCall 
79082fe67bbSJohn McCall       CGF.EmitBlock(endBB);
791579a05d7SChris Lattner     }
79282fe67bbSJohn McCall 
79382fe67bbSJohn McCall     // Leave the partial-array cleanup if we entered one.
79482fe67bbSJohn McCall     if (dtorKind) CGF.DeactivateCleanupBlock(cleanup);
79582fe67bbSJohn McCall 
796579a05d7SChris Lattner     return;
797579a05d7SChris Lattner   }
798579a05d7SChris Lattner 
799579a05d7SChris Lattner   assert(E->getType()->isRecordType() && "Only support structs/unions here!");
800579a05d7SChris Lattner 
801579a05d7SChris Lattner   // Do struct initialization; this code just sets each individual member
802579a05d7SChris Lattner   // to the approprate value.  This makes bitfield support automatic;
803579a05d7SChris Lattner   // the disadvantage is that the generated code is more difficult for
804579a05d7SChris Lattner   // the optimizer, especially with bitfields.
805579a05d7SChris Lattner   unsigned NumInitElements = E->getNumInits();
8063b935d33SJohn McCall   RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
80752bcf963SChris Lattner 
8083b935d33SJohn McCall   if (record->isUnion()) {
8095169570eSDouglas Gregor     // Only initialize one field of a union. The field itself is
8105169570eSDouglas Gregor     // specified by the initializer list.
8115169570eSDouglas Gregor     if (!E->getInitializedFieldInUnion()) {
8125169570eSDouglas Gregor       // Empty union; we have nothing to do.
8135169570eSDouglas Gregor 
8145169570eSDouglas Gregor #ifndef NDEBUG
8155169570eSDouglas Gregor       // Make sure that it's really an empty and not a failure of
8165169570eSDouglas Gregor       // semantic analysis.
8173b935d33SJohn McCall       for (RecordDecl::field_iterator Field = record->field_begin(),
8183b935d33SJohn McCall                                    FieldEnd = record->field_end();
8195169570eSDouglas Gregor            Field != FieldEnd; ++Field)
8205169570eSDouglas Gregor         assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
8215169570eSDouglas Gregor #endif
8225169570eSDouglas Gregor       return;
8235169570eSDouglas Gregor     }
8245169570eSDouglas Gregor 
8255169570eSDouglas Gregor     // FIXME: volatility
8265169570eSDouglas Gregor     FieldDecl *Field = E->getInitializedFieldInUnion();
8275169570eSDouglas Gregor 
82827a3631bSChris Lattner     LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0);
8295169570eSDouglas Gregor     if (NumInitElements) {
8305169570eSDouglas Gregor       // Store the initializer into the field
8311553b190SJohn McCall       EmitInitializationToLValue(E->getInit(0), FieldLoc);
8325169570eSDouglas Gregor     } else {
83327a3631bSChris Lattner       // Default-initialize to null.
8341553b190SJohn McCall       EmitNullInitializationToLValue(FieldLoc);
8355169570eSDouglas Gregor     }
8365169570eSDouglas Gregor 
8375169570eSDouglas Gregor     return;
8385169570eSDouglas Gregor   }
839579a05d7SChris Lattner 
8403b935d33SJohn McCall   // We'll need to enter cleanup scopes in case any of the member
8413b935d33SJohn McCall   // initializers throw an exception.
8423b935d33SJohn McCall   llvm::SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
8433b935d33SJohn McCall 
844579a05d7SChris Lattner   // Here we iterate over the fields; this makes it simpler to both
845579a05d7SChris Lattner   // default-initialize fields and skip over unnamed fields.
8463b935d33SJohn McCall   unsigned curInitIndex = 0;
8473b935d33SJohn McCall   for (RecordDecl::field_iterator field = record->field_begin(),
8483b935d33SJohn McCall                                fieldEnd = record->field_end();
8493b935d33SJohn McCall        field != fieldEnd; ++field) {
8503b935d33SJohn McCall     // We're done once we hit the flexible array member.
8513b935d33SJohn McCall     if (field->getType()->isIncompleteArrayType())
85291f84216SDouglas Gregor       break;
85391f84216SDouglas Gregor 
8543b935d33SJohn McCall     // Always skip anonymous bitfields.
8553b935d33SJohn McCall     if (field->isUnnamedBitfield())
856579a05d7SChris Lattner       continue;
85717bd094aSDouglas Gregor 
8583b935d33SJohn McCall     // We're done if we reach the end of the explicit initializers, we
8593b935d33SJohn McCall     // have a zeroed object, and the rest of the fields are
8603b935d33SJohn McCall     // zero-initializable.
8613b935d33SJohn McCall     if (curInitIndex == NumInitElements && Dest.isZeroed() &&
86227a3631bSChris Lattner         CGF.getTypes().isZeroInitializable(E->getType()))
86327a3631bSChris Lattner       break;
86427a3631bSChris Lattner 
865327944b3SEli Friedman     // FIXME: volatility
8663b935d33SJohn McCall     LValue LV = CGF.EmitLValueForFieldInitialization(DestPtr, *field, 0);
8677c1baf46SFariborz Jahanian     // We never generate write-barries for initialized fields.
8683b935d33SJohn McCall     LV.setNonGC(true);
86927a3631bSChris Lattner 
8703b935d33SJohn McCall     if (curInitIndex < NumInitElements) {
871e18aaf2cSChris Lattner       // Store the initializer into the field.
8723b935d33SJohn McCall       EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
873579a05d7SChris Lattner     } else {
874579a05d7SChris Lattner       // We're out of initalizers; default-initialize to null
8753b935d33SJohn McCall       EmitNullInitializationToLValue(LV);
8763b935d33SJohn McCall     }
8773b935d33SJohn McCall 
8783b935d33SJohn McCall     // Push a destructor if necessary.
8793b935d33SJohn McCall     // FIXME: if we have an array of structures, all explicitly
8803b935d33SJohn McCall     // initialized, we can end up pushing a linear number of cleanups.
8813b935d33SJohn McCall     bool pushedCleanup = false;
8823b935d33SJohn McCall     if (QualType::DestructionKind dtorKind
8833b935d33SJohn McCall           = field->getType().isDestructedType()) {
8843b935d33SJohn McCall       assert(LV.isSimple());
8853b935d33SJohn McCall       if (CGF.needsEHCleanup(dtorKind)) {
8863b935d33SJohn McCall         CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
8873b935d33SJohn McCall                         CGF.getDestroyer(dtorKind), false);
8883b935d33SJohn McCall         cleanups.push_back(CGF.EHStack.stable_begin());
8893b935d33SJohn McCall         pushedCleanup = true;
8903b935d33SJohn McCall       }
891579a05d7SChris Lattner     }
89227a3631bSChris Lattner 
89327a3631bSChris Lattner     // If the GEP didn't get used because of a dead zero init or something
89427a3631bSChris Lattner     // else, clean it up for -O0 builds and general tidiness.
8953b935d33SJohn McCall     if (!pushedCleanup && LV.isSimple())
89627a3631bSChris Lattner       if (llvm::GetElementPtrInst *GEP =
8973b935d33SJohn McCall             dyn_cast<llvm::GetElementPtrInst>(LV.getAddress()))
89827a3631bSChris Lattner         if (GEP->use_empty())
89927a3631bSChris Lattner           GEP->eraseFromParent();
9007a51313dSChris Lattner   }
9013b935d33SJohn McCall 
9023b935d33SJohn McCall   // Deactivate all the partial cleanups in reverse order, which
9033b935d33SJohn McCall   // generally means popping them.
9043b935d33SJohn McCall   for (unsigned i = cleanups.size(); i != 0; --i)
9053b935d33SJohn McCall     CGF.DeactivateCleanupBlock(cleanups[i-1]);
9067a51313dSChris Lattner }
9077a51313dSChris Lattner 
9087a51313dSChris Lattner //===----------------------------------------------------------------------===//
9097a51313dSChris Lattner //                        Entry Points into this File
9107a51313dSChris Lattner //===----------------------------------------------------------------------===//
9117a51313dSChris Lattner 
91227a3631bSChris Lattner /// GetNumNonZeroBytesInInit - Get an approximate count of the number of
91327a3631bSChris Lattner /// non-zero bytes that will be stored when outputting the initializer for the
91427a3631bSChris Lattner /// specified initializer expression.
915df94cb7dSKen Dyck static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
91691147596SPeter Collingbourne   E = E->IgnoreParens();
91727a3631bSChris Lattner 
91827a3631bSChris Lattner   // 0 and 0.0 won't require any non-zero stores!
919df94cb7dSKen Dyck   if (isSimpleZero(E, CGF)) return CharUnits::Zero();
92027a3631bSChris Lattner 
92127a3631bSChris Lattner   // If this is an initlist expr, sum up the size of sizes of the (present)
92227a3631bSChris Lattner   // elements.  If this is something weird, assume the whole thing is non-zero.
92327a3631bSChris Lattner   const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
92427a3631bSChris Lattner   if (ILE == 0 || !CGF.getTypes().isZeroInitializable(ILE->getType()))
925df94cb7dSKen Dyck     return CGF.getContext().getTypeSizeInChars(E->getType());
92627a3631bSChris Lattner 
927c5cc2fb9SChris Lattner   // InitListExprs for structs have to be handled carefully.  If there are
928c5cc2fb9SChris Lattner   // reference members, we need to consider the size of the reference, not the
929c5cc2fb9SChris Lattner   // referencee.  InitListExprs for unions and arrays can't have references.
9305cd84755SChris Lattner   if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
9315cd84755SChris Lattner     if (!RT->isUnionType()) {
932c5cc2fb9SChris Lattner       RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
933df94cb7dSKen Dyck       CharUnits NumNonZeroBytes = CharUnits::Zero();
934c5cc2fb9SChris Lattner 
935c5cc2fb9SChris Lattner       unsigned ILEElement = 0;
936c5cc2fb9SChris Lattner       for (RecordDecl::field_iterator Field = SD->field_begin(),
937c5cc2fb9SChris Lattner            FieldEnd = SD->field_end(); Field != FieldEnd; ++Field) {
938c5cc2fb9SChris Lattner         // We're done once we hit the flexible array member or run out of
939c5cc2fb9SChris Lattner         // InitListExpr elements.
940c5cc2fb9SChris Lattner         if (Field->getType()->isIncompleteArrayType() ||
941c5cc2fb9SChris Lattner             ILEElement == ILE->getNumInits())
942c5cc2fb9SChris Lattner           break;
943c5cc2fb9SChris Lattner         if (Field->isUnnamedBitfield())
944c5cc2fb9SChris Lattner           continue;
945c5cc2fb9SChris Lattner 
946c5cc2fb9SChris Lattner         const Expr *E = ILE->getInit(ILEElement++);
947c5cc2fb9SChris Lattner 
948c5cc2fb9SChris Lattner         // Reference values are always non-null and have the width of a pointer.
9495cd84755SChris Lattner         if (Field->getType()->isReferenceType())
950df94cb7dSKen Dyck           NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
951df94cb7dSKen Dyck               CGF.getContext().Target.getPointerWidth(0));
9525cd84755SChris Lattner         else
953c5cc2fb9SChris Lattner           NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
954c5cc2fb9SChris Lattner       }
955c5cc2fb9SChris Lattner 
956c5cc2fb9SChris Lattner       return NumNonZeroBytes;
957c5cc2fb9SChris Lattner     }
9585cd84755SChris Lattner   }
959c5cc2fb9SChris Lattner 
960c5cc2fb9SChris Lattner 
961df94cb7dSKen Dyck   CharUnits NumNonZeroBytes = CharUnits::Zero();
96227a3631bSChris Lattner   for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
96327a3631bSChris Lattner     NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
96427a3631bSChris Lattner   return NumNonZeroBytes;
96527a3631bSChris Lattner }
96627a3631bSChris Lattner 
96727a3631bSChris Lattner /// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
96827a3631bSChris Lattner /// zeros in it, emit a memset and avoid storing the individual zeros.
96927a3631bSChris Lattner ///
97027a3631bSChris Lattner static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
97127a3631bSChris Lattner                                      CodeGenFunction &CGF) {
97227a3631bSChris Lattner   // If the slot is already known to be zeroed, nothing to do.  Don't mess with
97327a3631bSChris Lattner   // volatile stores.
97427a3631bSChris Lattner   if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == 0) return;
97527a3631bSChris Lattner 
97603535265SArgyrios Kyrtzidis   // C++ objects with a user-declared constructor don't need zero'ing.
97703535265SArgyrios Kyrtzidis   if (CGF.getContext().getLangOptions().CPlusPlus)
97803535265SArgyrios Kyrtzidis     if (const RecordType *RT = CGF.getContext()
97903535265SArgyrios Kyrtzidis                        .getBaseElementType(E->getType())->getAs<RecordType>()) {
98003535265SArgyrios Kyrtzidis       const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
98103535265SArgyrios Kyrtzidis       if (RD->hasUserDeclaredConstructor())
98203535265SArgyrios Kyrtzidis         return;
98303535265SArgyrios Kyrtzidis     }
98403535265SArgyrios Kyrtzidis 
98527a3631bSChris Lattner   // If the type is 16-bytes or smaller, prefer individual stores over memset.
986239a3357SKen Dyck   std::pair<CharUnits, CharUnits> TypeInfo =
987239a3357SKen Dyck     CGF.getContext().getTypeInfoInChars(E->getType());
988239a3357SKen Dyck   if (TypeInfo.first <= CharUnits::fromQuantity(16))
98927a3631bSChris Lattner     return;
99027a3631bSChris Lattner 
99127a3631bSChris Lattner   // Check to see if over 3/4 of the initializer are known to be zero.  If so,
99227a3631bSChris Lattner   // we prefer to emit memset + individual stores for the rest.
993239a3357SKen Dyck   CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
994239a3357SKen Dyck   if (NumNonZeroBytes*4 > TypeInfo.first)
99527a3631bSChris Lattner     return;
99627a3631bSChris Lattner 
99727a3631bSChris Lattner   // Okay, it seems like a good idea to use an initial memset, emit the call.
998239a3357SKen Dyck   llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first.getQuantity());
999239a3357SKen Dyck   CharUnits Align = TypeInfo.second;
100027a3631bSChris Lattner 
100127a3631bSChris Lattner   llvm::Value *Loc = Slot.getAddr();
1002*2192fe50SChris Lattner   llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
100327a3631bSChris Lattner 
100427a3631bSChris Lattner   Loc = CGF.Builder.CreateBitCast(Loc, BP);
1005239a3357SKen Dyck   CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal,
1006239a3357SKen Dyck                            Align.getQuantity(), false);
100727a3631bSChris Lattner 
100827a3631bSChris Lattner   // Tell the AggExprEmitter that the slot is known zero.
100927a3631bSChris Lattner   Slot.setZeroed();
101027a3631bSChris Lattner }
101127a3631bSChris Lattner 
101227a3631bSChris Lattner 
101327a3631bSChris Lattner 
101427a3631bSChris Lattner 
101525306cacSMike Stump /// EmitAggExpr - Emit the computation of the specified expression of aggregate
101625306cacSMike Stump /// type.  The result is computed into DestPtr.  Note that if DestPtr is null,
101725306cacSMike Stump /// the value of the aggregate expression is not needed.  If VolatileDest is
101825306cacSMike Stump /// true, DestPtr cannot be 0.
10197a626f63SJohn McCall ///
10207a626f63SJohn McCall /// \param IsInitializer - true if this evaluation is initializing an
10217a626f63SJohn McCall /// object whose lifetime is already being managed.
10227a626f63SJohn McCall void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot,
1023b60e70f9SFariborz Jahanian                                   bool IgnoreResult) {
10247a51313dSChris Lattner   assert(E && hasAggregateLLVMType(E->getType()) &&
10257a51313dSChris Lattner          "Invalid aggregate expression to emit");
102627a3631bSChris Lattner   assert((Slot.getAddr() != 0 || Slot.isIgnored()) &&
102727a3631bSChris Lattner          "slot has bits but no address");
10287a51313dSChris Lattner 
102927a3631bSChris Lattner   // Optimize the slot if possible.
103027a3631bSChris Lattner   CheckAggExprForMemSetUse(Slot, E, *this);
103127a3631bSChris Lattner 
103227a3631bSChris Lattner   AggExprEmitter(*this, Slot, IgnoreResult).Visit(const_cast<Expr*>(E));
10337a51313dSChris Lattner }
10340bc8e86dSDaniel Dunbar 
1035d0bc7b9dSDaniel Dunbar LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
1036d0bc7b9dSDaniel Dunbar   assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!");
1037a7566f16SDaniel Dunbar   llvm::Value *Temp = CreateMemTemp(E->getType());
10382e442a00SDaniel Dunbar   LValue LV = MakeAddrLValue(Temp, E->getType());
103931168b07SJohn McCall   EmitAggExpr(E, AggValueSlot::forLValue(LV, false));
10402e442a00SDaniel Dunbar   return LV;
1041d0bc7b9dSDaniel Dunbar }
1042d0bc7b9dSDaniel Dunbar 
10430bc8e86dSDaniel Dunbar void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
10445e9e61b8SMike Stump                                         llvm::Value *SrcPtr, QualType Ty,
10455e9e61b8SMike Stump                                         bool isVolatile) {
10460bc8e86dSDaniel Dunbar   assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
10470bc8e86dSDaniel Dunbar 
104816e94af6SAnders Carlsson   if (getContext().getLangOptions().CPlusPlus) {
104916e94af6SAnders Carlsson     if (const RecordType *RT = Ty->getAs<RecordType>()) {
1050f22101a0SDouglas Gregor       CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
1051f22101a0SDouglas Gregor       assert((Record->hasTrivialCopyConstructor() ||
10526855ba2cSFariborz Jahanian               Record->hasTrivialCopyAssignment()) &&
1053f22101a0SDouglas Gregor              "Trying to aggregate-copy a type without a trivial copy "
1054f22101a0SDouglas Gregor              "constructor or assignment operator");
1055265b8b8dSDouglas Gregor       // Ignore empty classes in C++.
1056f22101a0SDouglas Gregor       if (Record->isEmpty())
105716e94af6SAnders Carlsson         return;
105816e94af6SAnders Carlsson     }
105916e94af6SAnders Carlsson   }
106016e94af6SAnders Carlsson 
1061ca05dfefSChris Lattner   // Aggregate assignment turns into llvm.memcpy.  This is almost valid per
10623ef668c2SChris Lattner   // C99 6.5.16.1p3, which states "If the value being stored in an object is
10633ef668c2SChris Lattner   // read from another object that overlaps in anyway the storage of the first
10643ef668c2SChris Lattner   // object, then the overlap shall be exact and the two objects shall have
10653ef668c2SChris Lattner   // qualified or unqualified versions of a compatible type."
10663ef668c2SChris Lattner   //
1067ca05dfefSChris Lattner   // memcpy is not defined if the source and destination pointers are exactly
10683ef668c2SChris Lattner   // equal, but other compilers do this optimization, and almost every memcpy
10693ef668c2SChris Lattner   // implementation handles this case safely.  If there is a libc that does not
10703ef668c2SChris Lattner   // safely handle this, we can add a target hook.
10710bc8e86dSDaniel Dunbar 
10720bc8e86dSDaniel Dunbar   // Get size and alignment info for this aggregate.
1073bb2c2400SKen Dyck   std::pair<CharUnits, CharUnits> TypeInfo =
1074bb2c2400SKen Dyck     getContext().getTypeInfoInChars(Ty);
10750bc8e86dSDaniel Dunbar 
10760bc8e86dSDaniel Dunbar   // FIXME: Handle variable sized types.
10770bc8e86dSDaniel Dunbar 
107886736572SMike Stump   // FIXME: If we have a volatile struct, the optimizer can remove what might
107986736572SMike Stump   // appear to be `extra' memory ops:
108086736572SMike Stump   //
108186736572SMike Stump   // volatile struct { int i; } a, b;
108286736572SMike Stump   //
108386736572SMike Stump   // int main() {
108486736572SMike Stump   //   a = b;
108586736572SMike Stump   //   a = b;
108686736572SMike Stump   // }
108786736572SMike Stump   //
1088cc2ab0cdSMon P Wang   // we need to use a different call here.  We use isVolatile to indicate when
1089ec3cbfe8SMike Stump   // either the source or the destination is volatile.
1090cc2ab0cdSMon P Wang 
1091*2192fe50SChris Lattner   llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
1092*2192fe50SChris Lattner   llvm::Type *DBP =
1093ad7c5c16SJohn McCall     llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace());
1094cc2ab0cdSMon P Wang   DestPtr = Builder.CreateBitCast(DestPtr, DBP, "tmp");
1095cc2ab0cdSMon P Wang 
1096*2192fe50SChris Lattner   llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
1097*2192fe50SChris Lattner   llvm::Type *SBP =
1098ad7c5c16SJohn McCall     llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace());
1099cc2ab0cdSMon P Wang   SrcPtr = Builder.CreateBitCast(SrcPtr, SBP, "tmp");
1100cc2ab0cdSMon P Wang 
110131168b07SJohn McCall   // Don't do any of the memmove_collectable tests if GC isn't set.
110231168b07SJohn McCall   if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC) {
110331168b07SJohn McCall     // fall through
110431168b07SJohn McCall   } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1105021510e9SFariborz Jahanian     RecordDecl *Record = RecordTy->getDecl();
1106021510e9SFariborz Jahanian     if (Record->hasObjectMember()) {
1107bb2c2400SKen Dyck       CharUnits size = TypeInfo.first;
1108*2192fe50SChris Lattner       llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1109bb2c2400SKen Dyck       llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
1110021510e9SFariborz Jahanian       CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1111021510e9SFariborz Jahanian                                                     SizeVal);
1112021510e9SFariborz Jahanian       return;
1113021510e9SFariborz Jahanian     }
111431168b07SJohn McCall   } else if (Ty->isArrayType()) {
1115021510e9SFariborz Jahanian     QualType BaseType = getContext().getBaseElementType(Ty);
1116021510e9SFariborz Jahanian     if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
1117021510e9SFariborz Jahanian       if (RecordTy->getDecl()->hasObjectMember()) {
1118bb2c2400SKen Dyck         CharUnits size = TypeInfo.first;
1119*2192fe50SChris Lattner         llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1120bb2c2400SKen Dyck         llvm::Value *SizeVal =
1121bb2c2400SKen Dyck           llvm::ConstantInt::get(SizeTy, size.getQuantity());
1122021510e9SFariborz Jahanian         CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1123021510e9SFariborz Jahanian                                                       SizeVal);
1124021510e9SFariborz Jahanian         return;
1125021510e9SFariborz Jahanian       }
1126021510e9SFariborz Jahanian     }
1127021510e9SFariborz Jahanian   }
1128021510e9SFariborz Jahanian 
1129acc6b4e2SBenjamin Kramer   Builder.CreateMemCpy(DestPtr, SrcPtr,
1130bb2c2400SKen Dyck                        llvm::ConstantInt::get(IntPtrTy,
1131bb2c2400SKen Dyck                                               TypeInfo.first.getQuantity()),
1132bb2c2400SKen Dyck                        TypeInfo.second.getQuantity(), isVolatile);
11330bc8e86dSDaniel Dunbar }
1134