blob: cbb5dfee0dbbf554e9f3376da8c184403b32fd2a [file] [log] [blame]
Chris Lattner11e0de52007-08-24 02:22:53 +00001//===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===//
Chris Lattnerd79671f2007-08-10 20:13:28 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerd79671f2007-08-10 20:13:28 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Aggregate Expr nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
Chris Lattner6278e6a2007-08-11 00:04:45 +000015#include "CodeGenModule.h"
Fariborz Jahanian5f21d2f2009-07-08 01:18:33 +000016#include "CGObjCRuntime.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000017#include "clang/AST/ASTContext.h"
Anders Carlssonb7f8f592009-04-17 00:06:03 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000019#include "clang/AST/StmtVisitor.h"
Chris Lattner6278e6a2007-08-11 00:04:45 +000020#include "llvm/Constants.h"
21#include "llvm/Function.h"
Devang Patel87174172007-10-26 17:44:44 +000022#include "llvm/GlobalVariable.h"
Chris Lattner579a05d2008-04-04 18:42:16 +000023#include "llvm/Intrinsics.h"
Chris Lattnerd79671f2007-08-10 20:13:28 +000024using namespace clang;
25using namespace CodeGen;
Chris Lattner6278e6a2007-08-11 00:04:45 +000026
Chris Lattner4758b402007-08-21 04:25:47 +000027//===----------------------------------------------------------------------===//
28// Aggregate Expression Emitter
29//===----------------------------------------------------------------------===//
30
31namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +000032class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
Chris Lattner4758b402007-08-21 04:25:47 +000033 CodeGenFunction &CGF;
Daniel Dunbarcb463852008-11-01 01:53:16 +000034 CGBuilderTy &Builder;
John McCall7a626f62010-09-15 10:14:12 +000035 AggValueSlot Dest;
Mike Stumpec3cbfe2009-05-26 22:03:21 +000036 bool IgnoreResult;
John McCall78a15112010-05-22 01:48:05 +000037
John McCalla5efa732011-08-25 23:04:34 +000038 /// We want to use 'dest' as the return slot except under two
39 /// conditions:
40 /// - The destination slot requires garbage collection, so we
41 /// need to use the GC API.
42 /// - The destination slot is potentially aliased.
43 bool shouldUseDestForReturnSlot() const {
44 return !(Dest.requiresGCollection() || Dest.isPotentiallyAliased());
45 }
46
John McCall78a15112010-05-22 01:48:05 +000047 ReturnValueSlot getReturnValueSlot() const {
John McCalla5efa732011-08-25 23:04:34 +000048 if (!shouldUseDestForReturnSlot())
49 return ReturnValueSlot();
John McCallcc04e9f2010-05-22 22:13:32 +000050
John McCall7a626f62010-09-15 10:14:12 +000051 return ReturnValueSlot(Dest.getAddr(), Dest.isVolatile());
52 }
53
54 AggValueSlot EnsureSlot(QualType T) {
55 if (!Dest.isIgnored()) return Dest;
56 return CGF.CreateAggTemp(T, "agg.tmp.ensured");
John McCall78a15112010-05-22 01:48:05 +000057 }
John McCallcc04e9f2010-05-22 22:13:32 +000058
Chris Lattner4758b402007-08-21 04:25:47 +000059public:
John McCall7a626f62010-09-15 10:14:12 +000060 AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest,
Fariborz Jahanianb60e70f2010-09-16 00:20:07 +000061 bool ignore)
John McCall7a626f62010-09-15 10:14:12 +000062 : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
Fariborz Jahanianb60e70f2010-09-16 00:20:07 +000063 IgnoreResult(ignore) {
Chris Lattner4758b402007-08-21 04:25:47 +000064 }
65
Chris Lattner835635d2007-08-21 04:59:27 +000066 //===--------------------------------------------------------------------===//
67 // Utilities
68 //===--------------------------------------------------------------------===//
69
Chris Lattner4758b402007-08-21 04:25:47 +000070 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
71 /// represents a value lvalue, this method emits the address of the lvalue,
72 /// then loads the result into DestPtr.
73 void EmitAggLoadOfLValue(const Expr *E);
Eli Friedmanf23b6fa2008-05-19 17:51:16 +000074
Mike Stumpca9fc092009-05-23 20:28:01 +000075 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
Mike Stumpec3cbfe2009-05-26 22:03:21 +000076 void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false);
77 void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false);
Mike Stumpca9fc092009-05-23 20:28:01 +000078
John McCalla5efa732011-08-25 23:04:34 +000079 void EmitMoveFromReturnSlot(const Expr *E, RValue Src);
John McCallcc04e9f2010-05-22 22:13:32 +000080
John McCall8d6fc952011-08-25 20:40:09 +000081 AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
Douglas Gregor79a91412011-09-13 17:21:33 +000082 if (CGF.getLangOptions().getGC() && TypeRequiresGCollection(T))
John McCall8d6fc952011-08-25 20:40:09 +000083 return AggValueSlot::NeedsGCBarriers;
84 return AggValueSlot::DoesNotNeedGCBarriers;
85 }
86
John McCallcc04e9f2010-05-22 22:13:32 +000087 bool TypeRequiresGCollection(QualType T);
88
Chris Lattner835635d2007-08-21 04:59:27 +000089 //===--------------------------------------------------------------------===//
90 // Visitor Methods
91 //===--------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +000092
Chris Lattner4758b402007-08-21 04:25:47 +000093 void VisitStmt(Stmt *S) {
Daniel Dunbara7c8cf62008-08-16 00:56:44 +000094 CGF.ErrorUnsupported(S, "aggregate expression");
Chris Lattner4758b402007-08-21 04:25:47 +000095 }
96 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
Peter Collingbourne91147592011-04-15 00:35:48 +000097 void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
98 Visit(GE->getResultExpr());
99 }
Eli Friedman3f66b842009-01-27 09:03:41 +0000100 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000101 void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
102 return Visit(E->getReplacement());
103 }
Chris Lattner4758b402007-08-21 04:25:47 +0000104
105 // l-values.
Seo Sanghyeond4d8c3c2007-12-14 02:04:12 +0000106 void VisitDeclRefExpr(DeclRefExpr *DRE) { EmitAggLoadOfLValue(DRE); }
107 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
108 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
Daniel Dunbard443c0a2010-01-04 18:47:06 +0000109 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
Douglas Gregor9b71f0c2011-06-17 04:59:12 +0000110 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Seo Sanghyeond4d8c3c2007-12-14 02:04:12 +0000111 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
112 EmitAggLoadOfLValue(E);
113 }
Chris Lattner2f343dd2009-04-21 23:00:09 +0000114 void VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +0000115 EmitAggLoadOfLValue(E);
Chris Lattner2f343dd2009-04-21 23:00:09 +0000116 }
117 void VisitPredefinedExpr(const PredefinedExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +0000118 EmitAggLoadOfLValue(E);
Chris Lattner2f343dd2009-04-21 23:00:09 +0000119 }
Mike Stump11289f42009-09-09 15:08:12 +0000120
Chris Lattner4758b402007-08-21 04:25:47 +0000121 // Operators.
Anders Carlssonec143772009-08-07 23:22:37 +0000122 void VisitCastExpr(CastExpr *E);
Anders Carlsson0370eb22007-10-31 22:04:46 +0000123 void VisitCallExpr(const CallExpr *E);
Chris Lattner49e3bfa2007-08-31 22:54:14 +0000124 void VisitStmtExpr(const StmtExpr *E);
Chris Lattner4758b402007-08-21 04:25:47 +0000125 void VisitBinaryOperator(const BinaryOperator *BO);
Fariborz Jahanianffba6622009-10-22 22:57:31 +0000126 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
Chris Lattnercd9fb242007-08-21 04:43:17 +0000127 void VisitBinAssign(const BinaryOperator *E);
Eli Friedman4b0e2a32008-05-20 07:56:31 +0000128 void VisitBinComma(const BinaryOperator *E);
Chris Lattner4758b402007-08-21 04:25:47 +0000129
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000130 void VisitObjCMessageExpr(ObjCMessageExpr *E);
Daniel Dunbarc8317a42008-08-23 10:51:21 +0000131 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
132 EmitAggLoadOfLValue(E);
133 }
Mike Stump11289f42009-09-09 15:08:12 +0000134
John McCallc07a0c72011-02-17 10:25:35 +0000135 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
Anders Carlsson5b2095c2009-07-08 18:33:14 +0000136 void VisitChooseExpr(const ChooseExpr *CE);
Devang Patel87174172007-10-26 17:44:44 +0000137 void VisitInitListExpr(InitListExpr *E);
Anders Carlsson18ada982009-12-16 06:57:54 +0000138 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000139 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
140 Visit(DAE->getExpr());
141 }
Anders Carlsson3be22e22009-05-30 23:23:33 +0000142 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
Anders Carlsson1619a5042009-05-03 17:47:16 +0000143 void VisitCXXConstructExpr(const CXXConstructExpr *E);
John McCall5d413782010-12-06 08:20:24 +0000144 void VisitExprWithCleanups(ExprWithCleanups *E);
Douglas Gregor747eb782010-07-08 06:14:04 +0000145 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Mike Stump5bbbb132009-11-18 00:40:12 +0000146 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
Douglas Gregorfe314812011-06-21 17:03:29 +0000147 void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
John McCall1bf58462011-02-16 08:02:54 +0000148 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
149
John McCallfe96e0b2011-11-06 09:01:30 +0000150 void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
151 if (E->isGLValue()) {
152 LValue LV = CGF.EmitPseudoObjectLValue(E);
153 return EmitFinalDestCopy(E, LV);
154 }
155
156 CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
157 }
158
Eli Friedman21911e82008-05-27 15:51:49 +0000159 void VisitVAArgExpr(VAArgExpr *E);
Chris Lattner579a05d2008-04-04 18:42:16 +0000160
John McCall1553b192011-06-16 04:16:24 +0000161 void EmitInitializationToLValue(Expr *E, LValue Address);
162 void EmitNullInitializationToLValue(LValue Address);
Chris Lattner4758b402007-08-21 04:25:47 +0000163 // case Expr::ChooseExprClass:
Mike Stumpf16b8c32009-12-09 19:24:08 +0000164 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000165 void VisitAtomicExpr(AtomicExpr *E) {
166 CGF.EmitAtomicExpr(E, EnsureSlot(E->getType()).getAddr());
167 }
Chris Lattner4758b402007-08-21 04:25:47 +0000168};
169} // end anonymous namespace.
170
Chris Lattner835635d2007-08-21 04:59:27 +0000171//===----------------------------------------------------------------------===//
172// Utilities
173//===----------------------------------------------------------------------===//
Chris Lattner4758b402007-08-21 04:25:47 +0000174
Chris Lattner6278e6a2007-08-11 00:04:45 +0000175/// EmitAggLoadOfLValue - Given an expression with aggregate type that
176/// represents a value lvalue, this method emits the address of the lvalue,
177/// then loads the result into DestPtr.
Chris Lattner4758b402007-08-21 04:25:47 +0000178void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
179 LValue LV = CGF.EmitLValue(E);
Mike Stumpca9fc092009-05-23 20:28:01 +0000180 EmitFinalDestCopy(E, LV);
181}
182
John McCallcc04e9f2010-05-22 22:13:32 +0000183/// \brief True if the given aggregate type requires special GC API calls.
184bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
185 // Only record types have members that might require garbage collection.
186 const RecordType *RecordTy = T->getAs<RecordType>();
187 if (!RecordTy) return false;
188
189 // Don't mess with non-trivial C++ types.
190 RecordDecl *Record = RecordTy->getDecl();
191 if (isa<CXXRecordDecl>(Record) &&
192 (!cast<CXXRecordDecl>(Record)->hasTrivialCopyConstructor() ||
193 !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
194 return false;
195
196 // Check whether the type has an object member.
197 return Record->hasObjectMember();
198}
199
John McCalla5efa732011-08-25 23:04:34 +0000200/// \brief Perform the final move to DestPtr if for some reason
201/// getReturnValueSlot() didn't use it directly.
John McCallcc04e9f2010-05-22 22:13:32 +0000202///
203/// The idea is that you do something like this:
204/// RValue Result = EmitSomething(..., getReturnValueSlot());
John McCalla5efa732011-08-25 23:04:34 +0000205/// EmitMoveFromReturnSlot(E, Result);
206///
207/// If nothing interferes, this will cause the result to be emitted
208/// directly into the return value slot. Otherwise, a final move
209/// will be performed.
210void AggExprEmitter::EmitMoveFromReturnSlot(const Expr *E, RValue Src) {
211 if (shouldUseDestForReturnSlot()) {
212 // Logically, Dest.getAddr() should equal Src.getAggregateAddr().
213 // The possibility of undef rvalues complicates that a lot,
214 // though, so we can't really assert.
215 return;
Fariborz Jahanian021510e2010-06-15 22:44:06 +0000216 }
John McCalla5efa732011-08-25 23:04:34 +0000217
218 // Otherwise, do a final copy,
219 assert(Dest.getAddr() != Src.getAggregateAddr());
220 EmitFinalDestCopy(E, Src, /*Ignore*/ true);
John McCallcc04e9f2010-05-22 22:13:32 +0000221}
222
Mike Stumpca9fc092009-05-23 20:28:01 +0000223/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
Mike Stumpec3cbfe2009-05-26 22:03:21 +0000224void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore) {
Mike Stumpca9fc092009-05-23 20:28:01 +0000225 assert(Src.isAggregate() && "value must be aggregate value!");
226
John McCall7a626f62010-09-15 10:14:12 +0000227 // If Dest is ignored, then we're evaluating an aggregate expression
John McCall8d752432010-08-25 02:50:31 +0000228 // in a context (like an expression statement) that doesn't care
229 // about the result. C says that an lvalue-to-rvalue conversion is
230 // performed in these cases; C++ says that it is not. In either
231 // case, we don't actually need to do anything unless the value is
232 // volatile.
John McCall7a626f62010-09-15 10:14:12 +0000233 if (Dest.isIgnored()) {
John McCall8d752432010-08-25 02:50:31 +0000234 if (!Src.isVolatileQualified() ||
235 CGF.CGM.getLangOptions().CPlusPlus ||
236 (IgnoreResult && Ignore))
Mike Stump332ec2c2009-05-23 22:01:27 +0000237 return;
Fariborz Jahanianc1236232010-10-22 22:05:03 +0000238
Mike Stumpec3cbfe2009-05-26 22:03:21 +0000239 // If the source is volatile, we must read from it; to do that, we need
240 // some place to put it.
John McCall7a626f62010-09-15 10:14:12 +0000241 Dest = CGF.CreateAggTemp(E->getType(), "agg.tmp");
Mike Stump332ec2c2009-05-23 22:01:27 +0000242 }
Chris Lattner6278e6a2007-08-11 00:04:45 +0000243
John McCall58649dc2010-09-16 03:13:23 +0000244 if (Dest.requiresGCollection()) {
Ken Dyck3b4bd9a2011-04-24 17:08:00 +0000245 CharUnits size = CGF.getContext().getTypeSizeInChars(E->getType());
Chris Lattner2192fe52011-07-18 04:24:23 +0000246 llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
Ken Dyck3b4bd9a2011-04-24 17:08:00 +0000247 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
Fariborz Jahanian879d7262009-08-31 19:33:16 +0000248 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
John McCall7a626f62010-09-15 10:14:12 +0000249 Dest.getAddr(),
250 Src.getAggregateAddr(),
251 SizeVal);
Fariborz Jahanian879d7262009-08-31 19:33:16 +0000252 return;
253 }
Mike Stumpca9fc092009-05-23 20:28:01 +0000254 // If the result of the assignment is used, copy the LHS there also.
255 // FIXME: Pass VolatileDest as well. I think we also need to merge volatile
256 // from the source as well, as we can't eliminate it if either operand
257 // is volatile, unless copy has volatile for both source and destination..
John McCall7a626f62010-09-15 10:14:12 +0000258 CGF.EmitAggregateCopy(Dest.getAddr(), Src.getAggregateAddr(), E->getType(),
259 Dest.isVolatile()|Src.isVolatileQualified());
Mike Stumpca9fc092009-05-23 20:28:01 +0000260}
261
262/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
Mike Stumpec3cbfe2009-05-26 22:03:21 +0000263void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) {
Mike Stumpca9fc092009-05-23 20:28:01 +0000264 assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc");
265
266 EmitFinalDestCopy(E, RValue::getAggregate(Src.getAddress(),
Mike Stumpec3cbfe2009-05-26 22:03:21 +0000267 Src.isVolatileQualified()),
268 Ignore);
Chris Lattner6278e6a2007-08-11 00:04:45 +0000269}
270
Chris Lattner835635d2007-08-21 04:59:27 +0000271//===----------------------------------------------------------------------===//
272// Visitor Methods
273//===----------------------------------------------------------------------===//
274
Douglas Gregorfe314812011-06-21 17:03:29 +0000275void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
276 Visit(E->GetTemporaryExpr());
277}
278
John McCall1bf58462011-02-16 08:02:54 +0000279void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
John McCallc07a0c72011-02-17 10:25:35 +0000280 EmitFinalDestCopy(e, CGF.getOpaqueLValueMapping(e));
John McCall1bf58462011-02-16 08:02:54 +0000281}
282
Douglas Gregor9b71f0c2011-06-17 04:59:12 +0000283void
284AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
Douglas Gregor6c9d31e2011-06-17 16:37:20 +0000285 if (E->getType().isPODType(CGF.getContext())) {
286 // For a POD type, just emit a load of the lvalue + a copy, because our
287 // compound literal might alias the destination.
288 // FIXME: This is a band-aid; the real problem appears to be in our handling
289 // of assignments, where we store directly into the LHS without checking
290 // whether anything in the RHS aliases.
291 EmitAggLoadOfLValue(E);
292 return;
293 }
294
Douglas Gregor9b71f0c2011-06-17 04:59:12 +0000295 AggValueSlot Slot = EnsureSlot(E->getType());
296 CGF.EmitAggExpr(E->getInitializer(), Slot);
297}
298
299
Anders Carlssonec143772009-08-07 23:22:37 +0000300void AggExprEmitter::VisitCastExpr(CastExpr *E) {
Anders Carlsson1fb7ae92009-09-29 01:23:39 +0000301 switch (E->getCastKind()) {
Anders Carlsson8a01a752011-04-11 02:03:26 +0000302 case CK_Dynamic: {
Douglas Gregor1c073f42010-05-14 21:31:02 +0000303 assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
304 LValue LV = CGF.EmitCheckedLValue(E->getSubExpr());
305 // FIXME: Do we also need to handle property references here?
306 if (LV.isSimple())
307 CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
308 else
309 CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
310
John McCall7a626f62010-09-15 10:14:12 +0000311 if (!Dest.isIgnored())
312 CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
Douglas Gregor1c073f42010-05-14 21:31:02 +0000313 break;
314 }
315
John McCalle3027922010-08-25 11:45:40 +0000316 case CK_ToUnion: {
John McCall58989b72011-04-12 22:02:02 +0000317 if (Dest.isIgnored()) break;
318
Anders Carlssonec143772009-08-07 23:22:37 +0000319 // GCC union extension
Daniel Dunbar2e442a02010-08-21 03:15:20 +0000320 QualType Ty = E->getSubExpr()->getType();
321 QualType PtrTy = CGF.getContext().getPointerType(Ty);
John McCall7a626f62010-09-15 10:14:12 +0000322 llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
Eli Friedmandd274842009-06-03 20:45:06 +0000323 CGF.ConvertType(PtrTy));
John McCall1553b192011-06-16 04:16:24 +0000324 EmitInitializationToLValue(E->getSubExpr(),
325 CGF.MakeAddrLValue(CastPtr, Ty));
Anders Carlsson1fb7ae92009-09-29 01:23:39 +0000326 break;
Nuno Lopes7ffcf932009-01-15 20:14:33 +0000327 }
Mike Stump11289f42009-09-09 15:08:12 +0000328
John McCalle3027922010-08-25 11:45:40 +0000329 case CK_DerivedToBase:
330 case CK_BaseToDerived:
331 case CK_UncheckedDerivedToBase: {
David Blaikie83d382b2011-09-23 05:06:16 +0000332 llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
Douglas Gregoraae38d62010-05-22 05:17:18 +0000333 "should have been unpacked before we got here");
Douglas Gregoraae38d62010-05-22 05:17:18 +0000334 }
335
John McCallc109a252011-11-07 03:59:57 +0000336 case CK_GetObjCProperty: llvm_unreachable("GetObjCProperty!");
John McCall34376a62010-12-04 03:47:34 +0000337
338 case CK_LValueToRValue: // hope for downstream optimization
John McCalle3027922010-08-25 11:45:40 +0000339 case CK_NoOp:
340 case CK_UserDefinedConversion:
341 case CK_ConstructorConversion:
Anders Carlsson1fb7ae92009-09-29 01:23:39 +0000342 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
343 E->getType()) &&
344 "Implicit cast types must be compatible");
345 Visit(E->getSubExpr());
346 break;
John McCallf3735e02010-12-01 04:43:34 +0000347
John McCalle3027922010-08-25 11:45:40 +0000348 case CK_LValueBitCast:
John McCallf3735e02010-12-01 04:43:34 +0000349 llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
Douglas Gregor51954272010-07-13 23:17:26 +0000350 break;
John McCall31996342011-04-07 08:22:57 +0000351
John McCallf3735e02010-12-01 04:43:34 +0000352 case CK_Dependent:
353 case CK_BitCast:
354 case CK_ArrayToPointerDecay:
355 case CK_FunctionToPointerDecay:
356 case CK_NullToPointer:
357 case CK_NullToMemberPointer:
358 case CK_BaseToDerivedMemberPointer:
359 case CK_DerivedToBaseMemberPointer:
360 case CK_MemberPointerToBoolean:
361 case CK_IntegralToPointer:
362 case CK_PointerToIntegral:
363 case CK_PointerToBoolean:
364 case CK_ToVoid:
365 case CK_VectorSplat:
366 case CK_IntegralCast:
367 case CK_IntegralToBoolean:
368 case CK_IntegralToFloating:
369 case CK_FloatingToIntegral:
370 case CK_FloatingToBoolean:
371 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +0000372 case CK_CPointerToObjCPointerCast:
373 case CK_BlockPointerToObjCPointerCast:
John McCallf3735e02010-12-01 04:43:34 +0000374 case CK_AnyPointerToBlockPointerCast:
375 case CK_ObjCObjectLValueCast:
376 case CK_FloatingRealToComplex:
377 case CK_FloatingComplexToReal:
378 case CK_FloatingComplexToBoolean:
379 case CK_FloatingComplexCast:
380 case CK_FloatingComplexToIntegralComplex:
381 case CK_IntegralRealToComplex:
382 case CK_IntegralComplexToReal:
383 case CK_IntegralComplexToBoolean:
384 case CK_IntegralComplexCast:
385 case CK_IntegralComplexToFloatingComplex:
John McCall2d637d22011-09-10 06:18:15 +0000386 case CK_ARCProduceObject:
387 case CK_ARCConsumeObject:
388 case CK_ARCReclaimReturnedObject:
389 case CK_ARCExtendBlockObject:
John McCallf3735e02010-12-01 04:43:34 +0000390 llvm_unreachable("cast kind invalid for aggregate types");
Anders Carlsson1fb7ae92009-09-29 01:23:39 +0000391 }
Anders Carlsson1ba25ca2008-01-14 06:28:57 +0000392}
393
Chris Lattner0f398c42008-07-26 22:37:01 +0000394void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
Anders Carlssonddcbfe72009-05-27 16:45:02 +0000395 if (E->getCallReturnType()->isReferenceType()) {
396 EmitAggLoadOfLValue(E);
397 return;
398 }
Mike Stump11289f42009-09-09 15:08:12 +0000399
John McCallcc04e9f2010-05-22 22:13:32 +0000400 RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
John McCalla5efa732011-08-25 23:04:34 +0000401 EmitMoveFromReturnSlot(E, RV);
Anders Carlsson0370eb22007-10-31 22:04:46 +0000402}
Chris Lattner0f398c42008-07-26 22:37:01 +0000403
404void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCallcc04e9f2010-05-22 22:13:32 +0000405 RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
John McCalla5efa732011-08-25 23:04:34 +0000406 EmitMoveFromReturnSlot(E, RV);
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000407}
Anders Carlsson0370eb22007-10-31 22:04:46 +0000408
Chris Lattner0f398c42008-07-26 22:37:01 +0000409void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCalla2342eb2010-12-05 02:00:02 +0000410 CGF.EmitIgnoredExpr(E->getLHS());
John McCall7a626f62010-09-15 10:14:12 +0000411 Visit(E->getRHS());
Eli Friedman4b0e2a32008-05-20 07:56:31 +0000412}
413
Chris Lattner49e3bfa2007-08-31 22:54:14 +0000414void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCallce1de612011-01-26 04:00:11 +0000415 CodeGenFunction::StmtExprEvaluation eval(CGF);
John McCall7a626f62010-09-15 10:14:12 +0000416 CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
Chris Lattner49e3bfa2007-08-31 22:54:14 +0000417}
418
Chris Lattner4758b402007-08-21 04:25:47 +0000419void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +0000420 if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +0000421 VisitPointerToDataMemberBinaryOperator(E);
422 else
423 CGF.ErrorUnsupported(E, "aggregate binary expression");
424}
425
426void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
427 const BinaryOperator *E) {
428 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
429 EmitFinalDestCopy(E, LV);
Chris Lattner835635d2007-08-21 04:59:27 +0000430}
431
Chris Lattnercd9fb242007-08-21 04:43:17 +0000432void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Eli Friedmanf54c4e52008-02-11 01:09:17 +0000433 // For an assignment to work, the value on the right has
434 // to be compatible with the value on the left.
Eli Friedman2a695472009-05-28 23:04:00 +0000435 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
436 E->getRHS()->getType())
Eli Friedmanf54c4e52008-02-11 01:09:17 +0000437 && "Invalid assignment");
John McCalld0a30012010-12-06 06:10:02 +0000438
Fariborz Jahanian99514b92011-04-29 21:53:21 +0000439 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getLHS()))
Fariborz Jahanian52a8cca2011-04-29 22:11:28 +0000440 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Fariborz Jahanian99514b92011-04-29 21:53:21 +0000441 if (VD->hasAttr<BlocksAttr>() &&
442 E->getRHS()->HasSideEffects(CGF.getContext())) {
443 // When __block variable on LHS, the RHS must be evaluated first
444 // as it may change the 'forwarding' field via call to Block_copy.
445 LValue RHS = CGF.EmitLValue(E->getRHS());
446 LValue LHS = CGF.EmitLValue(E->getLHS());
John McCall8d6fc952011-08-25 20:40:09 +0000447 Dest = AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
John McCall46759f42011-08-26 07:31:35 +0000448 needsGC(E->getLHS()->getType()),
449 AggValueSlot::IsAliased);
Fariborz Jahanian99514b92011-04-29 21:53:21 +0000450 EmitFinalDestCopy(E, RHS, true);
451 return;
452 }
Fariborz Jahanian99514b92011-04-29 21:53:21 +0000453
Chris Lattner4758b402007-08-21 04:25:47 +0000454 LValue LHS = CGF.EmitLValue(E->getLHS());
Chris Lattner6278e6a2007-08-11 00:04:45 +0000455
John McCallc109a252011-11-07 03:59:57 +0000456 // Codegen the RHS so that it stores directly into the LHS.
457 AggValueSlot LHSSlot =
458 AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
459 needsGC(E->getLHS()->getType()),
460 AggValueSlot::IsAliased);
461 CGF.EmitAggExpr(E->getRHS(), LHSSlot, false);
462 EmitFinalDestCopy(E, LHS, true);
Chris Lattner6278e6a2007-08-11 00:04:45 +0000463}
464
John McCallc07a0c72011-02-17 10:25:35 +0000465void AggExprEmitter::
466VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Daniel Dunbara612e792008-11-13 01:38:36 +0000467 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
468 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
469 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Mike Stump11289f42009-09-09 15:08:12 +0000470
John McCallc07a0c72011-02-17 10:25:35 +0000471 // Bind the common expression if necessary.
472 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
473
John McCallce1de612011-01-26 04:00:11 +0000474 CodeGenFunction::ConditionalEvaluation eval(CGF);
Eli Friedmanb8841af2009-12-25 06:17:05 +0000475 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000476
John McCall5b26f652010-11-17 00:07:33 +0000477 // Save whether the destination's lifetime is externally managed.
John McCallcac93852011-08-26 08:02:37 +0000478 bool isExternallyDestructed = Dest.isExternallyDestructed();
Chris Lattner6278e6a2007-08-11 00:04:45 +0000479
John McCallce1de612011-01-26 04:00:11 +0000480 eval.begin(CGF);
481 CGF.EmitBlock(LHSBlock);
John McCallc07a0c72011-02-17 10:25:35 +0000482 Visit(E->getTrueExpr());
John McCallce1de612011-01-26 04:00:11 +0000483 eval.end(CGF);
Mike Stump11289f42009-09-09 15:08:12 +0000484
John McCallce1de612011-01-26 04:00:11 +0000485 assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
486 CGF.Builder.CreateBr(ContBlock);
Mike Stump11289f42009-09-09 15:08:12 +0000487
John McCall5b26f652010-11-17 00:07:33 +0000488 // If the result of an agg expression is unused, then the emission
489 // of the LHS might need to create a destination slot. That's fine
490 // with us, and we can safely emit the RHS into the same slot, but
John McCallcac93852011-08-26 08:02:37 +0000491 // we shouldn't claim that it's already being destructed.
492 Dest.setExternallyDestructed(isExternallyDestructed);
John McCall5b26f652010-11-17 00:07:33 +0000493
John McCallce1de612011-01-26 04:00:11 +0000494 eval.begin(CGF);
495 CGF.EmitBlock(RHSBlock);
John McCallc07a0c72011-02-17 10:25:35 +0000496 Visit(E->getFalseExpr());
John McCallce1de612011-01-26 04:00:11 +0000497 eval.end(CGF);
Mike Stump11289f42009-09-09 15:08:12 +0000498
Chris Lattner4758b402007-08-21 04:25:47 +0000499 CGF.EmitBlock(ContBlock);
Chris Lattner6278e6a2007-08-11 00:04:45 +0000500}
Chris Lattner835635d2007-08-21 04:59:27 +0000501
Anders Carlsson5b2095c2009-07-08 18:33:14 +0000502void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
503 Visit(CE->getChosenSubExpr(CGF.getContext()));
504}
505
Eli Friedman21911e82008-05-27 15:51:49 +0000506void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Daniel Dunbare9fcadd22009-02-11 22:25:55 +0000507 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlsson13abd7e2008-11-04 05:30:00 +0000508 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
509
Sebastian Redl020cddc2009-01-09 21:09:38 +0000510 if (!ArgPtr) {
Anders Carlsson13abd7e2008-11-04 05:30:00 +0000511 CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
Sebastian Redl020cddc2009-01-09 21:09:38 +0000512 return;
513 }
514
Daniel Dunbar2e442a02010-08-21 03:15:20 +0000515 EmitFinalDestCopy(VE, CGF.MakeAddrLValue(ArgPtr, VE->getType()));
Eli Friedman21911e82008-05-27 15:51:49 +0000516}
517
Anders Carlsson3be22e22009-05-30 23:23:33 +0000518void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
John McCall7a626f62010-09-15 10:14:12 +0000519 // Ensure that we have a slot, but if we already do, remember
John McCallcac93852011-08-26 08:02:37 +0000520 // whether it was externally destructed.
521 bool wasExternallyDestructed = Dest.isExternallyDestructed();
John McCall7a626f62010-09-15 10:14:12 +0000522 Dest = EnsureSlot(E->getType());
John McCallcac93852011-08-26 08:02:37 +0000523
524 // We're going to push a destructor if there isn't already one.
525 Dest.setExternallyDestructed();
Mike Stump11289f42009-09-09 15:08:12 +0000526
John McCall7a626f62010-09-15 10:14:12 +0000527 Visit(E->getSubExpr());
Anders Carlsson3be22e22009-05-30 23:23:33 +0000528
John McCallcac93852011-08-26 08:02:37 +0000529 // Push that destructor we promised.
530 if (!wasExternallyDestructed)
John McCall7a626f62010-09-15 10:14:12 +0000531 CGF.EmitCXXTemporary(E->getTemporary(), Dest.getAddr());
Anders Carlsson3be22e22009-05-30 23:23:33 +0000532}
533
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000534void
Anders Carlsson1619a5042009-05-03 17:47:16 +0000535AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
John McCall7a626f62010-09-15 10:14:12 +0000536 AggValueSlot Slot = EnsureSlot(E->getType());
537 CGF.EmitCXXConstructExpr(E, Slot);
Anders Carlssonc82b86d2009-05-19 04:48:36 +0000538}
539
John McCall5d413782010-12-06 08:20:24 +0000540void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
541 CGF.EmitExprWithCleanups(E, Dest);
Anders Carlssonb7f8f592009-04-17 00:06:03 +0000542}
543
Douglas Gregor747eb782010-07-08 06:14:04 +0000544void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
John McCall7a626f62010-09-15 10:14:12 +0000545 QualType T = E->getType();
546 AggValueSlot Slot = EnsureSlot(T);
John McCall1553b192011-06-16 04:16:24 +0000547 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
Anders Carlsson18ada982009-12-16 06:57:54 +0000548}
549
550void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
John McCall7a626f62010-09-15 10:14:12 +0000551 QualType T = E->getType();
552 AggValueSlot Slot = EnsureSlot(T);
John McCall1553b192011-06-16 04:16:24 +0000553 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
Nuno Lopesff3507b2009-10-18 15:18:11 +0000554}
555
Chris Lattner27a36312010-12-02 07:07:26 +0000556/// isSimpleZero - If emitting this value will obviously just cause a store of
557/// zero to memory, return true. This can return false if uncertain, so it just
558/// handles simple cases.
559static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000560 E = E->IgnoreParens();
561
Chris Lattner27a36312010-12-02 07:07:26 +0000562 // 0
563 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
564 return IL->getValue() == 0;
565 // +0.0
566 if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
567 return FL->getValue().isPosZero();
568 // int()
569 if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
570 CGF.getTypes().isZeroInitializable(E->getType()))
571 return true;
572 // (int*)0 - Null pointer expressions.
573 if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
574 return ICE->getCastKind() == CK_NullToPointer;
575 // '\0'
576 if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
577 return CL->getValue() == 0;
578
579 // Otherwise, hard case: conservatively return false.
580 return false;
581}
582
583
Anders Carlssonb2473502010-02-03 17:33:16 +0000584void
John McCall1553b192011-06-16 04:16:24 +0000585AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) {
586 QualType type = LV.getType();
Mike Stumpdf0fe272009-05-29 15:46:01 +0000587 // FIXME: Ignore result?
Chris Lattner579a05d2008-04-04 18:42:16 +0000588 // FIXME: Are initializers affected by volatile?
Chris Lattner27a36312010-12-02 07:07:26 +0000589 if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
590 // Storing "i32 0" to a zero'd memory location is a noop.
591 } else if (isa<ImplicitValueInitExpr>(E)) {
John McCall1553b192011-06-16 04:16:24 +0000592 EmitNullInitializationToLValue(LV);
593 } else if (type->isReferenceType()) {
Anders Carlsson04775f82010-06-26 16:35:32 +0000594 RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
John McCall55e1fbc2011-06-25 02:11:03 +0000595 CGF.EmitStoreThroughLValue(RV, LV);
John McCall1553b192011-06-16 04:16:24 +0000596 } else if (type->isAnyComplexType()) {
Douglas Gregor0202cb42009-01-29 17:44:32 +0000597 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
John McCall1553b192011-06-16 04:16:24 +0000598 } else if (CGF.hasAggregateLLVMType(type)) {
John McCall8d6fc952011-08-25 20:40:09 +0000599 CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV,
600 AggValueSlot::IsDestructed,
601 AggValueSlot::DoesNotNeedGCBarriers,
John McCalla5efa732011-08-25 23:04:34 +0000602 AggValueSlot::IsNotAliased,
John McCall1553b192011-06-16 04:16:24 +0000603 Dest.isZeroed()));
John McCall31168b02011-06-15 23:02:42 +0000604 } else if (LV.isSimple()) {
John McCall1553b192011-06-16 04:16:24 +0000605 CGF.EmitScalarInit(E, /*D=*/0, LV, /*Captured=*/false);
Eli Friedman6e313212008-05-12 15:06:05 +0000606 } else {
John McCall55e1fbc2011-06-25 02:11:03 +0000607 CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
Chris Lattner579a05d2008-04-04 18:42:16 +0000608 }
Chris Lattner579a05d2008-04-04 18:42:16 +0000609}
610
John McCall1553b192011-06-16 04:16:24 +0000611void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
612 QualType type = lv.getType();
613
Chris Lattner27a36312010-12-02 07:07:26 +0000614 // If the destination slot is already zeroed out before the aggregate is
615 // copied into it, we don't have to emit any zeros here.
John McCall1553b192011-06-16 04:16:24 +0000616 if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
Chris Lattner27a36312010-12-02 07:07:26 +0000617 return;
618
John McCall1553b192011-06-16 04:16:24 +0000619 if (!CGF.hasAggregateLLVMType(type)) {
Chris Lattner579a05d2008-04-04 18:42:16 +0000620 // For non-aggregates, we can store zero
John McCall1553b192011-06-16 04:16:24 +0000621 llvm::Value *null = llvm::Constant::getNullValue(CGF.ConvertType(type));
John McCall55e1fbc2011-06-25 02:11:03 +0000622 CGF.EmitStoreThroughLValue(RValue::get(null), lv);
Lauro Ramos Venancioe2162c62008-02-19 19:27:31 +0000623 } else {
Chris Lattner579a05d2008-04-04 18:42:16 +0000624 // There's a potential optimization opportunity in combining
625 // memsets; that would be easy for arrays, but relatively
626 // difficult for structures with the current code.
John McCall1553b192011-06-16 04:16:24 +0000627 CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
Chris Lattner579a05d2008-04-04 18:42:16 +0000628 }
629}
630
Chris Lattner579a05d2008-04-04 18:42:16 +0000631void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
Eli Friedmanf5d08c92008-12-02 01:17:45 +0000632#if 0
Eli Friedman6d11ec82009-12-04 01:30:56 +0000633 // FIXME: Assess perf here? Figure out what cases are worth optimizing here
634 // (Length of globals? Chunks of zeroed-out space?).
Eli Friedmanf5d08c92008-12-02 01:17:45 +0000635 //
Mike Stump18bb9282009-05-16 07:57:57 +0000636 // If we can, prefer a copy from a global; this is a lot less code for long
637 // globals, and it's easier for the current optimizers to analyze.
Eli Friedman6d11ec82009-12-04 01:30:56 +0000638 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
Eli Friedmanc59bb482008-11-30 02:11:09 +0000639 llvm::GlobalVariable* GV =
Eli Friedman6d11ec82009-12-04 01:30:56 +0000640 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
641 llvm::GlobalValue::InternalLinkage, C, "");
Daniel Dunbar2e442a02010-08-21 03:15:20 +0000642 EmitFinalDestCopy(E, CGF.MakeAddrLValue(GV, E->getType()));
Eli Friedmanc59bb482008-11-30 02:11:09 +0000643 return;
644 }
Eli Friedmanf5d08c92008-12-02 01:17:45 +0000645#endif
Chris Lattnerf53c0962010-09-06 00:11:41 +0000646 if (E->hadArrayRangeDesignator())
Douglas Gregorbf7207a2009-01-29 19:42:23 +0000647 CGF.ErrorUnsupported(E, "GNU array range designator extension");
Douglas Gregorbf7207a2009-01-29 19:42:23 +0000648
John McCall7a626f62010-09-15 10:14:12 +0000649 llvm::Value *DestPtr = Dest.getAddr();
650
Chris Lattner579a05d2008-04-04 18:42:16 +0000651 // Handle initialization of an array.
652 if (E->getType()->isArrayType()) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000653 llvm::PointerType *APType =
Chris Lattner579a05d2008-04-04 18:42:16 +0000654 cast<llvm::PointerType>(DestPtr->getType());
Chris Lattner2192fe52011-07-18 04:24:23 +0000655 llvm::ArrayType *AType =
Chris Lattner579a05d2008-04-04 18:42:16 +0000656 cast<llvm::ArrayType>(APType->getElementType());
Mike Stump11289f42009-09-09 15:08:12 +0000657
Chris Lattner579a05d2008-04-04 18:42:16 +0000658 uint64_t NumInitElements = E->getNumInits();
Eli Friedmanf23b6fa2008-05-19 17:51:16 +0000659
Chris Lattner0f398c42008-07-26 22:37:01 +0000660 if (E->getNumInits() > 0) {
661 QualType T1 = E->getType();
662 QualType T2 = E->getInit(0)->getType();
Eli Friedman2a695472009-05-28 23:04:00 +0000663 if (CGF.getContext().hasSameUnqualifiedType(T1, T2)) {
Chris Lattner0f398c42008-07-26 22:37:01 +0000664 EmitAggLoadOfLValue(E->getInit(0));
665 return;
666 }
Eli Friedmanf23b6fa2008-05-19 17:51:16 +0000667 }
668
Chris Lattner579a05d2008-04-04 18:42:16 +0000669 uint64_t NumArrayElements = AType->getNumElements();
John McCall82fe67b2011-07-09 01:37:26 +0000670 assert(NumInitElements <= NumArrayElements);
Mike Stump11289f42009-09-09 15:08:12 +0000671
John McCall82fe67b2011-07-09 01:37:26 +0000672 QualType elementType = E->getType().getCanonicalType();
673 elementType = CGF.getContext().getQualifiedType(
674 cast<ArrayType>(elementType)->getElementType(),
675 elementType.getQualifiers() + Dest.getQualifiers());
Argyrios Kyrtzidise07425a52011-04-28 18:53:58 +0000676
John McCall82fe67b2011-07-09 01:37:26 +0000677 // DestPtr is an array*. Construct an elementType* by drilling
678 // down a level.
679 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
680 llvm::Value *indices[] = { zero, zero };
681 llvm::Value *begin =
Jay Foad040dd822011-07-22 08:16:57 +0000682 Builder.CreateInBoundsGEP(DestPtr, indices, "arrayinit.begin");
Chris Lattner27a36312010-12-02 07:07:26 +0000683
John McCall82fe67b2011-07-09 01:37:26 +0000684 // Exception safety requires us to destroy all the
685 // already-constructed members if an initializer throws.
686 // For that, we'll need an EH cleanup.
687 QualType::DestructionKind dtorKind = elementType.isDestructedType();
688 llvm::AllocaInst *endOfInit = 0;
689 EHScopeStack::stable_iterator cleanup;
690 if (CGF.needsEHCleanup(dtorKind)) {
691 // In principle we could tell the cleanup where we are more
692 // directly, but the control flow can get so varied here that it
693 // would actually be quite complex. Therefore we go through an
694 // alloca.
695 endOfInit = CGF.CreateTempAlloca(begin->getType(),
696 "arrayinit.endOfInit");
697 Builder.CreateStore(begin, endOfInit);
John McCall178360e2011-07-11 08:38:19 +0000698 CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
699 CGF.getDestroyer(dtorKind));
John McCall82fe67b2011-07-09 01:37:26 +0000700 cleanup = CGF.EHStack.stable_begin();
701
702 // Otherwise, remember that we didn't need a cleanup.
703 } else {
704 dtorKind = QualType::DK_none;
Lauro Ramos Venancioe2162c62008-02-19 19:27:31 +0000705 }
John McCall82fe67b2011-07-09 01:37:26 +0000706
707 llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
708
709 // The 'current element to initialize'. The invariants on this
710 // variable are complicated. Essentially, after each iteration of
711 // the loop, it points to the last initialized element, except
712 // that it points to the beginning of the array before any
713 // elements have been initialized.
714 llvm::Value *element = begin;
715
716 // Emit the explicit initializers.
717 for (uint64_t i = 0; i != NumInitElements; ++i) {
718 // Advance to the next element.
John McCall178360e2011-07-11 08:38:19 +0000719 if (i > 0) {
John McCall82fe67b2011-07-09 01:37:26 +0000720 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element");
721
John McCall178360e2011-07-11 08:38:19 +0000722 // Tell the cleanup that it needs to destroy up to this
723 // element. TODO: some of these stores can be trivially
724 // observed to be unnecessary.
725 if (endOfInit) Builder.CreateStore(element, endOfInit);
726 }
727
John McCall82fe67b2011-07-09 01:37:26 +0000728 LValue elementLV = CGF.MakeAddrLValue(element, elementType);
729 EmitInitializationToLValue(E->getInit(i), elementLV);
John McCall82fe67b2011-07-09 01:37:26 +0000730 }
731
732 // Check whether there's a non-trivial array-fill expression.
733 // Note that this will be a CXXConstructExpr even if the element
734 // type is an array (or array of array, etc.) of class type.
735 Expr *filler = E->getArrayFiller();
736 bool hasTrivialFiller = true;
737 if (CXXConstructExpr *cons = dyn_cast_or_null<CXXConstructExpr>(filler)) {
738 assert(cons->getConstructor()->isDefaultConstructor());
739 hasTrivialFiller = cons->getConstructor()->isTrivial();
740 }
741
742 // Any remaining elements need to be zero-initialized, possibly
743 // using the filler expression. We can skip this if the we're
744 // emitting to zeroed memory.
745 if (NumInitElements != NumArrayElements &&
746 !(Dest.isZeroed() && hasTrivialFiller &&
747 CGF.getTypes().isZeroInitializable(elementType))) {
748
749 // Use an actual loop. This is basically
750 // do { *array++ = filler; } while (array != end);
751
752 // Advance to the start of the rest of the array.
John McCall178360e2011-07-11 08:38:19 +0000753 if (NumInitElements) {
John McCall82fe67b2011-07-09 01:37:26 +0000754 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start");
John McCall178360e2011-07-11 08:38:19 +0000755 if (endOfInit) Builder.CreateStore(element, endOfInit);
756 }
John McCall82fe67b2011-07-09 01:37:26 +0000757
758 // Compute the end of the array.
759 llvm::Value *end = Builder.CreateInBoundsGEP(begin,
760 llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
761 "arrayinit.end");
762
763 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
764 llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
765
766 // Jump into the body.
767 CGF.EmitBlock(bodyBB);
768 llvm::PHINode *currentElement =
769 Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
770 currentElement->addIncoming(element, entryBB);
771
772 // Emit the actual filler expression.
773 LValue elementLV = CGF.MakeAddrLValue(currentElement, elementType);
774 if (filler)
775 EmitInitializationToLValue(filler, elementLV);
776 else
777 EmitNullInitializationToLValue(elementLV);
778
John McCall82fe67b2011-07-09 01:37:26 +0000779 // Move on to the next element.
780 llvm::Value *nextElement =
781 Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
782
John McCall178360e2011-07-11 08:38:19 +0000783 // Tell the EH cleanup that we finished with the last element.
784 if (endOfInit) Builder.CreateStore(nextElement, endOfInit);
785
John McCall82fe67b2011-07-09 01:37:26 +0000786 // Leave the loop if we're done.
787 llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
788 "arrayinit.done");
789 llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
790 Builder.CreateCondBr(done, endBB, bodyBB);
791 currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
792
793 CGF.EmitBlock(endBB);
794 }
795
796 // Leave the partial-array cleanup if we entered one.
797 if (dtorKind) CGF.DeactivateCleanupBlock(cleanup);
798
Chris Lattner579a05d2008-04-04 18:42:16 +0000799 return;
800 }
Mike Stump11289f42009-09-09 15:08:12 +0000801
Chris Lattner579a05d2008-04-04 18:42:16 +0000802 assert(E->getType()->isRecordType() && "Only support structs/unions here!");
Mike Stump11289f42009-09-09 15:08:12 +0000803
Chris Lattner579a05d2008-04-04 18:42:16 +0000804 // Do struct initialization; this code just sets each individual member
805 // to the approprate value. This makes bitfield support automatic;
806 // the disadvantage is that the generated code is more difficult for
807 // the optimizer, especially with bitfields.
808 unsigned NumInitElements = E->getNumInits();
John McCall3b935d32011-07-11 19:35:02 +0000809 RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
Chris Lattner52bcf962010-09-06 00:13:11 +0000810
John McCall3b935d32011-07-11 19:35:02 +0000811 if (record->isUnion()) {
Douglas Gregor51695702009-01-29 16:53:55 +0000812 // Only initialize one field of a union. The field itself is
813 // specified by the initializer list.
814 if (!E->getInitializedFieldInUnion()) {
815 // Empty union; we have nothing to do.
Mike Stump11289f42009-09-09 15:08:12 +0000816
Douglas Gregor51695702009-01-29 16:53:55 +0000817#ifndef NDEBUG
818 // Make sure that it's really an empty and not a failure of
819 // semantic analysis.
John McCall3b935d32011-07-11 19:35:02 +0000820 for (RecordDecl::field_iterator Field = record->field_begin(),
821 FieldEnd = record->field_end();
Douglas Gregor51695702009-01-29 16:53:55 +0000822 Field != FieldEnd; ++Field)
823 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
824#endif
825 return;
826 }
827
828 // FIXME: volatility
829 FieldDecl *Field = E->getInitializedFieldInUnion();
Douglas Gregor51695702009-01-29 16:53:55 +0000830
Chris Lattner27a36312010-12-02 07:07:26 +0000831 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestPtr, Field, 0);
Douglas Gregor51695702009-01-29 16:53:55 +0000832 if (NumInitElements) {
833 // Store the initializer into the field
John McCall1553b192011-06-16 04:16:24 +0000834 EmitInitializationToLValue(E->getInit(0), FieldLoc);
Douglas Gregor51695702009-01-29 16:53:55 +0000835 } else {
Chris Lattner27a36312010-12-02 07:07:26 +0000836 // Default-initialize to null.
John McCall1553b192011-06-16 04:16:24 +0000837 EmitNullInitializationToLValue(FieldLoc);
Douglas Gregor51695702009-01-29 16:53:55 +0000838 }
839
840 return;
841 }
Mike Stump11289f42009-09-09 15:08:12 +0000842
John McCall3b935d32011-07-11 19:35:02 +0000843 // We'll need to enter cleanup scopes in case any of the member
844 // initializers throw an exception.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000845 SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
John McCall3b935d32011-07-11 19:35:02 +0000846
Chris Lattner579a05d2008-04-04 18:42:16 +0000847 // Here we iterate over the fields; this makes it simpler to both
848 // default-initialize fields and skip over unnamed fields.
John McCall3b935d32011-07-11 19:35:02 +0000849 unsigned curInitIndex = 0;
850 for (RecordDecl::field_iterator field = record->field_begin(),
851 fieldEnd = record->field_end();
852 field != fieldEnd; ++field) {
853 // We're done once we hit the flexible array member.
854 if (field->getType()->isIncompleteArrayType())
Douglas Gregor91f84212008-12-11 16:49:14 +0000855 break;
856
John McCall3b935d32011-07-11 19:35:02 +0000857 // Always skip anonymous bitfields.
858 if (field->isUnnamedBitfield())
Chris Lattner579a05d2008-04-04 18:42:16 +0000859 continue;
Douglas Gregor17bd0942009-01-28 23:36:17 +0000860
John McCall3b935d32011-07-11 19:35:02 +0000861 // We're done if we reach the end of the explicit initializers, we
862 // have a zeroed object, and the rest of the fields are
863 // zero-initializable.
864 if (curInitIndex == NumInitElements && Dest.isZeroed() &&
Chris Lattner27a36312010-12-02 07:07:26 +0000865 CGF.getTypes().isZeroInitializable(E->getType()))
866 break;
867
Eli Friedman327944b2008-06-13 23:01:12 +0000868 // FIXME: volatility
John McCall3b935d32011-07-11 19:35:02 +0000869 LValue LV = CGF.EmitLValueForFieldInitialization(DestPtr, *field, 0);
Fariborz Jahanian7c1baf42009-05-27 19:54:11 +0000870 // We never generate write-barries for initialized fields.
John McCall3b935d32011-07-11 19:35:02 +0000871 LV.setNonGC(true);
Chris Lattner27a36312010-12-02 07:07:26 +0000872
John McCall3b935d32011-07-11 19:35:02 +0000873 if (curInitIndex < NumInitElements) {
Chris Lattnere18aaf22010-03-08 21:08:07 +0000874 // Store the initializer into the field.
John McCall3b935d32011-07-11 19:35:02 +0000875 EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
Chris Lattner579a05d2008-04-04 18:42:16 +0000876 } else {
877 // We're out of initalizers; default-initialize to null
John McCall3b935d32011-07-11 19:35:02 +0000878 EmitNullInitializationToLValue(LV);
879 }
880
881 // Push a destructor if necessary.
882 // FIXME: if we have an array of structures, all explicitly
883 // initialized, we can end up pushing a linear number of cleanups.
884 bool pushedCleanup = false;
885 if (QualType::DestructionKind dtorKind
886 = field->getType().isDestructedType()) {
887 assert(LV.isSimple());
888 if (CGF.needsEHCleanup(dtorKind)) {
889 CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
890 CGF.getDestroyer(dtorKind), false);
891 cleanups.push_back(CGF.EHStack.stable_begin());
892 pushedCleanup = true;
893 }
Chris Lattner579a05d2008-04-04 18:42:16 +0000894 }
Chris Lattner27a36312010-12-02 07:07:26 +0000895
896 // If the GEP didn't get used because of a dead zero init or something
897 // else, clean it up for -O0 builds and general tidiness.
John McCall3b935d32011-07-11 19:35:02 +0000898 if (!pushedCleanup && LV.isSimple())
Chris Lattner27a36312010-12-02 07:07:26 +0000899 if (llvm::GetElementPtrInst *GEP =
John McCall3b935d32011-07-11 19:35:02 +0000900 dyn_cast<llvm::GetElementPtrInst>(LV.getAddress()))
Chris Lattner27a36312010-12-02 07:07:26 +0000901 if (GEP->use_empty())
902 GEP->eraseFromParent();
Lauro Ramos Venancioe2162c62008-02-19 19:27:31 +0000903 }
John McCall3b935d32011-07-11 19:35:02 +0000904
905 // Deactivate all the partial cleanups in reverse order, which
906 // generally means popping them.
907 for (unsigned i = cleanups.size(); i != 0; --i)
908 CGF.DeactivateCleanupBlock(cleanups[i-1]);
Devang Patel87174172007-10-26 17:44:44 +0000909}
910
Chris Lattner835635d2007-08-21 04:59:27 +0000911//===----------------------------------------------------------------------===//
912// Entry Points into this File
913//===----------------------------------------------------------------------===//
914
Chris Lattner27a36312010-12-02 07:07:26 +0000915/// GetNumNonZeroBytesInInit - Get an approximate count of the number of
916/// non-zero bytes that will be stored when outputting the initializer for the
917/// specified initializer expression.
Ken Dyckdf94cb72011-04-24 17:17:56 +0000918static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000919 E = E->IgnoreParens();
Chris Lattner27a36312010-12-02 07:07:26 +0000920
921 // 0 and 0.0 won't require any non-zero stores!
Ken Dyckdf94cb72011-04-24 17:17:56 +0000922 if (isSimpleZero(E, CGF)) return CharUnits::Zero();
Chris Lattner27a36312010-12-02 07:07:26 +0000923
924 // If this is an initlist expr, sum up the size of sizes of the (present)
925 // elements. If this is something weird, assume the whole thing is non-zero.
926 const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
927 if (ILE == 0 || !CGF.getTypes().isZeroInitializable(ILE->getType()))
Ken Dyckdf94cb72011-04-24 17:17:56 +0000928 return CGF.getContext().getTypeSizeInChars(E->getType());
Chris Lattner27a36312010-12-02 07:07:26 +0000929
Chris Lattnerc5cc2fb2010-12-02 18:29:00 +0000930 // InitListExprs for structs have to be handled carefully. If there are
931 // reference members, we need to consider the size of the reference, not the
932 // referencee. InitListExprs for unions and arrays can't have references.
Chris Lattner5cd84752010-12-02 22:52:04 +0000933 if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
934 if (!RT->isUnionType()) {
935 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
Ken Dyckdf94cb72011-04-24 17:17:56 +0000936 CharUnits NumNonZeroBytes = CharUnits::Zero();
Chris Lattner5cd84752010-12-02 22:52:04 +0000937
938 unsigned ILEElement = 0;
939 for (RecordDecl::field_iterator Field = SD->field_begin(),
940 FieldEnd = SD->field_end(); Field != FieldEnd; ++Field) {
941 // We're done once we hit the flexible array member or run out of
942 // InitListExpr elements.
943 if (Field->getType()->isIncompleteArrayType() ||
944 ILEElement == ILE->getNumInits())
945 break;
946 if (Field->isUnnamedBitfield())
947 continue;
Chris Lattnerc5cc2fb2010-12-02 18:29:00 +0000948
Chris Lattner5cd84752010-12-02 22:52:04 +0000949 const Expr *E = ILE->getInit(ILEElement++);
950
951 // Reference values are always non-null and have the width of a pointer.
952 if (Field->getType()->isReferenceType())
Ken Dyckdf94cb72011-04-24 17:17:56 +0000953 NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
Douglas Gregore8bbc122011-09-02 00:18:52 +0000954 CGF.getContext().getTargetInfo().getPointerWidth(0));
Chris Lattner5cd84752010-12-02 22:52:04 +0000955 else
956 NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
957 }
Chris Lattnerc5cc2fb2010-12-02 18:29:00 +0000958
Chris Lattner5cd84752010-12-02 22:52:04 +0000959 return NumNonZeroBytes;
Chris Lattnerc5cc2fb2010-12-02 18:29:00 +0000960 }
Chris Lattnerc5cc2fb2010-12-02 18:29:00 +0000961 }
962
963
Ken Dyckdf94cb72011-04-24 17:17:56 +0000964 CharUnits NumNonZeroBytes = CharUnits::Zero();
Chris Lattner27a36312010-12-02 07:07:26 +0000965 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
966 NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
967 return NumNonZeroBytes;
968}
969
970/// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
971/// zeros in it, emit a memset and avoid storing the individual zeros.
972///
973static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
974 CodeGenFunction &CGF) {
975 // If the slot is already known to be zeroed, nothing to do. Don't mess with
976 // volatile stores.
977 if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == 0) return;
Argyrios Kyrtzidis03535262011-04-28 22:57:55 +0000978
979 // C++ objects with a user-declared constructor don't need zero'ing.
980 if (CGF.getContext().getLangOptions().CPlusPlus)
981 if (const RecordType *RT = CGF.getContext()
982 .getBaseElementType(E->getType())->getAs<RecordType>()) {
983 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
984 if (RD->hasUserDeclaredConstructor())
985 return;
986 }
987
Chris Lattner27a36312010-12-02 07:07:26 +0000988 // If the type is 16-bytes or smaller, prefer individual stores over memset.
Ken Dyck239a3352011-04-24 17:25:32 +0000989 std::pair<CharUnits, CharUnits> TypeInfo =
990 CGF.getContext().getTypeInfoInChars(E->getType());
991 if (TypeInfo.first <= CharUnits::fromQuantity(16))
Chris Lattner27a36312010-12-02 07:07:26 +0000992 return;
993
994 // Check to see if over 3/4 of the initializer are known to be zero. If so,
995 // we prefer to emit memset + individual stores for the rest.
Ken Dyck239a3352011-04-24 17:25:32 +0000996 CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
997 if (NumNonZeroBytes*4 > TypeInfo.first)
Chris Lattner27a36312010-12-02 07:07:26 +0000998 return;
999
1000 // Okay, it seems like a good idea to use an initial memset, emit the call.
Ken Dyck239a3352011-04-24 17:25:32 +00001001 llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first.getQuantity());
1002 CharUnits Align = TypeInfo.second;
Chris Lattner27a36312010-12-02 07:07:26 +00001003
1004 llvm::Value *Loc = Slot.getAddr();
Chris Lattner2192fe52011-07-18 04:24:23 +00001005 llvm::Type *BP = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
Chris Lattner27a36312010-12-02 07:07:26 +00001006
1007 Loc = CGF.Builder.CreateBitCast(Loc, BP);
Ken Dyck239a3352011-04-24 17:25:32 +00001008 CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal,
1009 Align.getQuantity(), false);
Chris Lattner27a36312010-12-02 07:07:26 +00001010
1011 // Tell the AggExprEmitter that the slot is known zero.
1012 Slot.setZeroed();
1013}
1014
1015
1016
1017
Mike Stump25306ca2009-05-26 18:57:45 +00001018/// EmitAggExpr - Emit the computation of the specified expression of aggregate
1019/// type. The result is computed into DestPtr. Note that if DestPtr is null,
1020/// the value of the aggregate expression is not needed. If VolatileDest is
1021/// true, DestPtr cannot be 0.
John McCall7a626f62010-09-15 10:14:12 +00001022///
1023/// \param IsInitializer - true if this evaluation is initializing an
1024/// object whose lifetime is already being managed.
John McCall7a626f62010-09-15 10:14:12 +00001025void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot,
Fariborz Jahanianb60e70f2010-09-16 00:20:07 +00001026 bool IgnoreResult) {
Chris Lattner835635d2007-08-21 04:59:27 +00001027 assert(E && hasAggregateLLVMType(E->getType()) &&
1028 "Invalid aggregate expression to emit");
Chris Lattner27a36312010-12-02 07:07:26 +00001029 assert((Slot.getAddr() != 0 || Slot.isIgnored()) &&
1030 "slot has bits but no address");
Mike Stump11289f42009-09-09 15:08:12 +00001031
Chris Lattner27a36312010-12-02 07:07:26 +00001032 // Optimize the slot if possible.
1033 CheckAggExprForMemSetUse(Slot, E, *this);
1034
1035 AggExprEmitter(*this, Slot, IgnoreResult).Visit(const_cast<Expr*>(E));
Chris Lattner835635d2007-08-21 04:59:27 +00001036}
Daniel Dunbar0bc8e862008-09-09 20:49:46 +00001037
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00001038LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
1039 assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!");
Daniel Dunbara7566f12010-02-09 02:48:28 +00001040 llvm::Value *Temp = CreateMemTemp(E->getType());
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001041 LValue LV = MakeAddrLValue(Temp, E->getType());
John McCall8d6fc952011-08-25 20:40:09 +00001042 EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,
John McCall46759f42011-08-26 07:31:35 +00001043 AggValueSlot::DoesNotNeedGCBarriers,
1044 AggValueSlot::IsNotAliased));
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001045 return LV;
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00001046}
1047
Daniel Dunbar0bc8e862008-09-09 20:49:46 +00001048void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
Mike Stump5e9e61b2009-05-23 22:29:41 +00001049 llvm::Value *SrcPtr, QualType Ty,
1050 bool isVolatile) {
Daniel Dunbar0bc8e862008-09-09 20:49:46 +00001051 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
Mike Stump11289f42009-09-09 15:08:12 +00001052
Anders Carlsson16e94af2010-05-03 01:20:20 +00001053 if (getContext().getLangOptions().CPlusPlus) {
1054 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Douglas Gregorf22101a2010-05-20 15:39:01 +00001055 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
1056 assert((Record->hasTrivialCopyConstructor() ||
Douglas Gregor146b8e92011-09-06 16:26:56 +00001057 Record->hasTrivialCopyAssignment() ||
1058 Record->hasTrivialMoveConstructor() ||
1059 Record->hasTrivialMoveAssignment()) &&
Douglas Gregorf22101a2010-05-20 15:39:01 +00001060 "Trying to aggregate-copy a type without a trivial copy "
1061 "constructor or assignment operator");
Douglas Gregor265b8b82010-05-20 15:48:29 +00001062 // Ignore empty classes in C++.
Douglas Gregorf22101a2010-05-20 15:39:01 +00001063 if (Record->isEmpty())
Anders Carlsson16e94af2010-05-03 01:20:20 +00001064 return;
1065 }
1066 }
1067
Chris Lattnerca05dfe2009-02-28 18:31:01 +00001068 // Aggregate assignment turns into llvm.memcpy. This is almost valid per
Chris Lattner3ef668c2009-02-28 18:18:58 +00001069 // C99 6.5.16.1p3, which states "If the value being stored in an object is
1070 // read from another object that overlaps in anyway the storage of the first
1071 // object, then the overlap shall be exact and the two objects shall have
1072 // qualified or unqualified versions of a compatible type."
1073 //
Chris Lattnerca05dfe2009-02-28 18:31:01 +00001074 // memcpy is not defined if the source and destination pointers are exactly
Chris Lattner3ef668c2009-02-28 18:18:58 +00001075 // equal, but other compilers do this optimization, and almost every memcpy
1076 // implementation handles this case safely. If there is a libc that does not
1077 // safely handle this, we can add a target hook.
Mike Stump11289f42009-09-09 15:08:12 +00001078
Daniel Dunbar0bc8e862008-09-09 20:49:46 +00001079 // Get size and alignment info for this aggregate.
Ken Dyckbb2c2402011-04-24 17:37:26 +00001080 std::pair<CharUnits, CharUnits> TypeInfo =
1081 getContext().getTypeInfoInChars(Ty);
Mike Stump11289f42009-09-09 15:08:12 +00001082
Daniel Dunbar0bc8e862008-09-09 20:49:46 +00001083 // FIXME: Handle variable sized types.
Mike Stump11289f42009-09-09 15:08:12 +00001084
Mike Stump86736572009-05-23 04:13:59 +00001085 // FIXME: If we have a volatile struct, the optimizer can remove what might
1086 // appear to be `extra' memory ops:
1087 //
1088 // volatile struct { int i; } a, b;
1089 //
1090 // int main() {
1091 // a = b;
1092 // a = b;
1093 // }
1094 //
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001095 // we need to use a different call here. We use isVolatile to indicate when
Mike Stumpec3cbfe2009-05-26 22:03:21 +00001096 // either the source or the destination is volatile.
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001097
Chris Lattner2192fe52011-07-18 04:24:23 +00001098 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
1099 llvm::Type *DBP =
John McCallad7c5c12011-02-08 08:22:06 +00001100 llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace());
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001101 DestPtr = Builder.CreateBitCast(DestPtr, DBP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001102
Chris Lattner2192fe52011-07-18 04:24:23 +00001103 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
1104 llvm::Type *SBP =
John McCallad7c5c12011-02-08 08:22:06 +00001105 llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace());
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001106 SrcPtr = Builder.CreateBitCast(SrcPtr, SBP);
Mon P Wangcc2ab0c2010-04-04 03:10:52 +00001107
John McCall31168b02011-06-15 23:02:42 +00001108 // Don't do any of the memmove_collectable tests if GC isn't set.
Douglas Gregor79a91412011-09-13 17:21:33 +00001109 if (CGM.getLangOptions().getGC() == LangOptions::NonGC) {
John McCall31168b02011-06-15 23:02:42 +00001110 // fall through
1111 } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
Fariborz Jahanian021510e2010-06-15 22:44:06 +00001112 RecordDecl *Record = RecordTy->getDecl();
1113 if (Record->hasObjectMember()) {
Ken Dyckbb2c2402011-04-24 17:37:26 +00001114 CharUnits size = TypeInfo.first;
Chris Lattner2192fe52011-07-18 04:24:23 +00001115 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Ken Dyckbb2c2402011-04-24 17:37:26 +00001116 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00001117 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1118 SizeVal);
1119 return;
1120 }
John McCall31168b02011-06-15 23:02:42 +00001121 } else if (Ty->isArrayType()) {
Fariborz Jahanian021510e2010-06-15 22:44:06 +00001122 QualType BaseType = getContext().getBaseElementType(Ty);
1123 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
1124 if (RecordTy->getDecl()->hasObjectMember()) {
Ken Dyckbb2c2402011-04-24 17:37:26 +00001125 CharUnits size = TypeInfo.first;
Chris Lattner2192fe52011-07-18 04:24:23 +00001126 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Ken Dyckbb2c2402011-04-24 17:37:26 +00001127 llvm::Value *SizeVal =
1128 llvm::ConstantInt::get(SizeTy, size.getQuantity());
Fariborz Jahanian021510e2010-06-15 22:44:06 +00001129 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1130 SizeVal);
1131 return;
1132 }
1133 }
1134 }
1135
Benjamin Krameracc6b4e2010-12-30 00:13:21 +00001136 Builder.CreateMemCpy(DestPtr, SrcPtr,
Ken Dyckbb2c2402011-04-24 17:37:26 +00001137 llvm::ConstantInt::get(IntPtrTy,
1138 TypeInfo.first.getQuantity()),
1139 TypeInfo.second.getQuantity(), isVolatile);
Daniel Dunbar0bc8e862008-09-09 20:49:46 +00001140}