blob: d53cbc430f7eafc1ecf8949070387b22eccf46cb [file] [log] [blame]
Chris Lattner566b6ce2007-08-24 02:22:53 +00001//===--- CGExprAgg.cpp - Emit LLVM Code from Aggregate Expressions --------===//
Chris Lattneraf6f5282007-08-10 20:13:28 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-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 Lattneraf6f5282007-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 Lattner883f6a72007-08-11 00:04:45 +000015#include "CodeGenModule.h"
Fariborz Jahanian082b02e2009-07-08 01:18:33 +000016#include "CGObjCRuntime.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000017#include "clang/AST/ASTContext.h"
Anders Carlssonb14095a2009-04-17 00:06:03 +000018#include "clang/AST/DeclCXX.h"
Sebastian Redl32cf1f22012-02-17 08:42:25 +000019#include "clang/AST/DeclTemplate.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000020#include "clang/AST/StmtVisitor.h"
Chris Lattner883f6a72007-08-11 00:04:45 +000021#include "llvm/Constants.h"
22#include "llvm/Function.h"
Devang Patel636c3d02007-10-26 17:44:44 +000023#include "llvm/GlobalVariable.h"
Chris Lattnerf81557c2008-04-04 18:42:16 +000024#include "llvm/Intrinsics.h"
Chris Lattneraf6f5282007-08-10 20:13:28 +000025using namespace clang;
26using namespace CodeGen;
Chris Lattner883f6a72007-08-11 00:04:45 +000027
Chris Lattner9c033562007-08-21 04:25:47 +000028//===----------------------------------------------------------------------===//
29// Aggregate Expression Emitter
30//===----------------------------------------------------------------------===//
31
32namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000033class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
Chris Lattner9c033562007-08-21 04:25:47 +000034 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000035 CGBuilderTy &Builder;
John McCall558d2ab2010-09-15 10:14:12 +000036 AggValueSlot Dest;
Mike Stump49d1cd52009-05-26 22:03:21 +000037 bool IgnoreResult;
John McCallef072fd2010-05-22 01:48:05 +000038
John McCall410ffb22011-08-25 23:04:34 +000039 /// We want to use 'dest' as the return slot except under two
40 /// conditions:
41 /// - The destination slot requires garbage collection, so we
42 /// need to use the GC API.
43 /// - The destination slot is potentially aliased.
44 bool shouldUseDestForReturnSlot() const {
45 return !(Dest.requiresGCollection() || Dest.isPotentiallyAliased());
46 }
47
John McCallef072fd2010-05-22 01:48:05 +000048 ReturnValueSlot getReturnValueSlot() const {
John McCall410ffb22011-08-25 23:04:34 +000049 if (!shouldUseDestForReturnSlot())
50 return ReturnValueSlot();
John McCallfa037bd2010-05-22 22:13:32 +000051
John McCall558d2ab2010-09-15 10:14:12 +000052 return ReturnValueSlot(Dest.getAddr(), Dest.isVolatile());
53 }
54
55 AggValueSlot EnsureSlot(QualType T) {
56 if (!Dest.isIgnored()) return Dest;
57 return CGF.CreateAggTemp(T, "agg.tmp.ensured");
John McCallef072fd2010-05-22 01:48:05 +000058 }
John McCallfa037bd2010-05-22 22:13:32 +000059
Chris Lattner9c033562007-08-21 04:25:47 +000060public:
John McCall558d2ab2010-09-15 10:14:12 +000061 AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest,
Fariborz Jahanian474e2fe2010-09-16 00:20:07 +000062 bool ignore)
John McCall558d2ab2010-09-15 10:14:12 +000063 : CGF(cgf), Builder(CGF.Builder), Dest(Dest),
Fariborz Jahanian474e2fe2010-09-16 00:20:07 +000064 IgnoreResult(ignore) {
Chris Lattner9c033562007-08-21 04:25:47 +000065 }
66
Chris Lattneree755f92007-08-21 04:59:27 +000067 //===--------------------------------------------------------------------===//
68 // Utilities
69 //===--------------------------------------------------------------------===//
70
Chris Lattner9c033562007-08-21 04:25:47 +000071 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
72 /// represents a value lvalue, this method emits the address of the lvalue,
73 /// then loads the result into DestPtr.
74 void EmitAggLoadOfLValue(const Expr *E);
Eli Friedman922696f2008-05-19 17:51:16 +000075
Mike Stump4ac20dd2009-05-23 20:28:01 +000076 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
Mike Stump49d1cd52009-05-26 22:03:21 +000077 void EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore = false);
Eli Friedmanbd7d8282011-12-05 22:23:28 +000078 void EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore = false,
79 unsigned Alignment = 0);
Mike Stump4ac20dd2009-05-23 20:28:01 +000080
John McCall410ffb22011-08-25 23:04:34 +000081 void EmitMoveFromReturnSlot(const Expr *E, RValue Src);
John McCallfa037bd2010-05-22 22:13:32 +000082
Sebastian Redlaf130fd2012-02-19 12:28:02 +000083 void EmitStdInitializerList(llvm::Value *DestPtr, InitListExpr *InitList);
Sebastian Redl32cf1f22012-02-17 08:42:25 +000084 void EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
85 QualType elementType, InitListExpr *E);
86
John McCall7c2349b2011-08-25 20:40:09 +000087 AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
David Blaikie4e4d0842012-03-11 07:00:24 +000088 if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))
John McCall7c2349b2011-08-25 20:40:09 +000089 return AggValueSlot::NeedsGCBarriers;
90 return AggValueSlot::DoesNotNeedGCBarriers;
91 }
92
John McCallfa037bd2010-05-22 22:13:32 +000093 bool TypeRequiresGCollection(QualType T);
94
Chris Lattneree755f92007-08-21 04:59:27 +000095 //===--------------------------------------------------------------------===//
96 // Visitor Methods
97 //===--------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +000098
Chris Lattner9c033562007-08-21 04:25:47 +000099 void VisitStmt(Stmt *S) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000100 CGF.ErrorUnsupported(S, "aggregate expression");
Chris Lattner9c033562007-08-21 04:25:47 +0000101 }
102 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000103 void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
104 Visit(GE->getResultExpr());
105 }
Eli Friedman12444a22009-01-27 09:03:41 +0000106 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
John McCall91a57552011-07-15 05:09:51 +0000107 void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
108 return Visit(E->getReplacement());
109 }
Chris Lattner9c033562007-08-21 04:25:47 +0000110
111 // l-values.
John McCallf4b88a42012-03-10 09:33:50 +0000112 void VisitDeclRefExpr(DeclRefExpr *E) {
John McCalldd2ecee2012-03-10 03:05:10 +0000113 // For aggregates, we should always be able to emit the variable
114 // as an l-value unless it's a reference. This is due to the fact
115 // that we can't actually ever see a normal l2r conversion on an
116 // aggregate in C++, and in C there's no language standard
117 // actively preventing us from listing variables in the captures
118 // list of a block.
John McCallf4b88a42012-03-10 09:33:50 +0000119 if (E->getDecl()->getType()->isReferenceType()) {
John McCalldd2ecee2012-03-10 03:05:10 +0000120 if (CodeGenFunction::ConstantEmission result
John McCallf4b88a42012-03-10 09:33:50 +0000121 = CGF.tryEmitAsConstant(E)) {
122 EmitFinalDestCopy(E, result.getReferenceLValue(CGF, E));
John McCalldd2ecee2012-03-10 03:05:10 +0000123 return;
124 }
125 }
126
John McCallf4b88a42012-03-10 09:33:50 +0000127 EmitAggLoadOfLValue(E);
John McCalldd2ecee2012-03-10 03:05:10 +0000128 }
129
Seo Sanghyeon9b73b392007-12-14 02:04:12 +0000130 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
131 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
Daniel Dunbar5be028f2010-01-04 18:47:06 +0000132 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
Douglas Gregor751ec9b2011-06-17 04:59:12 +0000133 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Seo Sanghyeon9b73b392007-12-14 02:04:12 +0000134 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
135 EmitAggLoadOfLValue(E);
136 }
Chris Lattnerf0a990c2009-04-21 23:00:09 +0000137 void VisitPredefinedExpr(const PredefinedExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000138 EmitAggLoadOfLValue(E);
Chris Lattnerf0a990c2009-04-21 23:00:09 +0000139 }
Mike Stump1eb44332009-09-09 15:08:12 +0000140
Chris Lattner9c033562007-08-21 04:25:47 +0000141 // Operators.
Anders Carlsson4d8673b2009-08-07 23:22:37 +0000142 void VisitCastExpr(CastExpr *E);
Anders Carlsson148fe672007-10-31 22:04:46 +0000143 void VisitCallExpr(const CallExpr *E);
Chris Lattnerb2d963f2007-08-31 22:54:14 +0000144 void VisitStmtExpr(const StmtExpr *E);
Chris Lattner9c033562007-08-21 04:25:47 +0000145 void VisitBinaryOperator(const BinaryOperator *BO);
Fariborz Jahanian8bfd31f2009-10-22 22:57:31 +0000146 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
Chris Lattner03d6fb92007-08-21 04:43:17 +0000147 void VisitBinAssign(const BinaryOperator *E);
Eli Friedman07fa52a2008-05-20 07:56:31 +0000148 void VisitBinComma(const BinaryOperator *E);
Chris Lattner9c033562007-08-21 04:25:47 +0000149
Chris Lattner8fdf3282008-06-24 17:04:18 +0000150 void VisitObjCMessageExpr(ObjCMessageExpr *E);
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000151 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
152 EmitAggLoadOfLValue(E);
153 }
Mike Stump1eb44332009-09-09 15:08:12 +0000154
John McCall56ca35d2011-02-17 10:25:35 +0000155 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
Anders Carlssona294ca82009-07-08 18:33:14 +0000156 void VisitChooseExpr(const ChooseExpr *CE);
Devang Patel636c3d02007-10-26 17:44:44 +0000157 void VisitInitListExpr(InitListExpr *E);
Anders Carlsson30311fa2009-12-16 06:57:54 +0000158 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
Chris Lattner04421082008-04-08 04:40:51 +0000159 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
160 Visit(DAE->getExpr());
161 }
Anders Carlssonb58d0172009-05-30 23:23:33 +0000162 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
Anders Carlsson31ccf372009-05-03 17:47:16 +0000163 void VisitCXXConstructExpr(const CXXConstructExpr *E);
Eli Friedman4c5d8af2012-02-09 03:32:31 +0000164 void VisitLambdaExpr(LambdaExpr *E);
John McCall4765fa02010-12-06 08:20:24 +0000165 void VisitExprWithCleanups(ExprWithCleanups *E);
Douglas Gregored8abf12010-07-08 06:14:04 +0000166 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Mike Stump2710c412009-11-18 00:40:12 +0000167 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
Douglas Gregor03e80032011-06-21 17:03:29 +0000168 void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
John McCalle996ffd2011-02-16 08:02:54 +0000169 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
170
John McCall4b9c2d22011-11-06 09:01:30 +0000171 void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
172 if (E->isGLValue()) {
173 LValue LV = CGF.EmitPseudoObjectLValue(E);
174 return EmitFinalDestCopy(E, LV);
175 }
176
177 CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
178 }
179
Eli Friedmanb1851242008-05-27 15:51:49 +0000180 void VisitVAArgExpr(VAArgExpr *E);
Chris Lattnerf81557c2008-04-04 18:42:16 +0000181
Chad Rosier649b4a12012-03-29 17:37:10 +0000182 void EmitInitializationToLValue(Expr *E, LValue Address);
John McCalla07398e2011-06-16 04:16:24 +0000183 void EmitNullInitializationToLValue(LValue Address);
Chris Lattner9c033562007-08-21 04:25:47 +0000184 // case Expr::ChooseExprClass:
Mike Stump39406b12009-12-09 19:24:08 +0000185 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
Eli Friedman276b0612011-10-11 02:20:01 +0000186 void VisitAtomicExpr(AtomicExpr *E) {
187 CGF.EmitAtomicExpr(E, EnsureSlot(E->getType()).getAddr());
188 }
Chris Lattner9c033562007-08-21 04:25:47 +0000189};
190} // end anonymous namespace.
191
Chris Lattneree755f92007-08-21 04:59:27 +0000192//===----------------------------------------------------------------------===//
193// Utilities
194//===----------------------------------------------------------------------===//
Chris Lattner9c033562007-08-21 04:25:47 +0000195
Chris Lattner883f6a72007-08-11 00:04:45 +0000196/// EmitAggLoadOfLValue - Given an expression with aggregate type that
197/// represents a value lvalue, this method emits the address of the lvalue,
198/// then loads the result into DestPtr.
Chris Lattner9c033562007-08-21 04:25:47 +0000199void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
200 LValue LV = CGF.EmitLValue(E);
Mike Stump4ac20dd2009-05-23 20:28:01 +0000201 EmitFinalDestCopy(E, LV);
202}
203
John McCallfa037bd2010-05-22 22:13:32 +0000204/// \brief True if the given aggregate type requires special GC API calls.
205bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
206 // Only record types have members that might require garbage collection.
207 const RecordType *RecordTy = T->getAs<RecordType>();
208 if (!RecordTy) return false;
209
210 // Don't mess with non-trivial C++ types.
211 RecordDecl *Record = RecordTy->getDecl();
212 if (isa<CXXRecordDecl>(Record) &&
213 (!cast<CXXRecordDecl>(Record)->hasTrivialCopyConstructor() ||
214 !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
215 return false;
216
217 // Check whether the type has an object member.
218 return Record->hasObjectMember();
219}
220
John McCall410ffb22011-08-25 23:04:34 +0000221/// \brief Perform the final move to DestPtr if for some reason
222/// getReturnValueSlot() didn't use it directly.
John McCallfa037bd2010-05-22 22:13:32 +0000223///
224/// The idea is that you do something like this:
225/// RValue Result = EmitSomething(..., getReturnValueSlot());
John McCall410ffb22011-08-25 23:04:34 +0000226/// EmitMoveFromReturnSlot(E, Result);
227///
228/// If nothing interferes, this will cause the result to be emitted
229/// directly into the return value slot. Otherwise, a final move
230/// will be performed.
231void AggExprEmitter::EmitMoveFromReturnSlot(const Expr *E, RValue Src) {
232 if (shouldUseDestForReturnSlot()) {
233 // Logically, Dest.getAddr() should equal Src.getAggregateAddr().
234 // The possibility of undef rvalues complicates that a lot,
235 // though, so we can't really assert.
236 return;
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000237 }
John McCall410ffb22011-08-25 23:04:34 +0000238
239 // Otherwise, do a final copy,
240 assert(Dest.getAddr() != Src.getAggregateAddr());
Chad Rosier26397ed2012-04-17 01:14:29 +0000241 std::pair<CharUnits, CharUnits> TypeInfo =
242 CGF.getContext().getTypeInfoInChars(E->getType());
243 CharUnits Alignment = std::min(TypeInfo.second, Dest.getAlignment());
244 EmitFinalDestCopy(E, Src, /*Ignore*/ true, Alignment.getQuantity());
John McCallfa037bd2010-05-22 22:13:32 +0000245}
246
Mike Stump4ac20dd2009-05-23 20:28:01 +0000247/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
Eli Friedmanbd7d8282011-12-05 22:23:28 +0000248void AggExprEmitter::EmitFinalDestCopy(const Expr *E, RValue Src, bool Ignore,
249 unsigned Alignment) {
Mike Stump4ac20dd2009-05-23 20:28:01 +0000250 assert(Src.isAggregate() && "value must be aggregate value!");
251
John McCall558d2ab2010-09-15 10:14:12 +0000252 // If Dest is ignored, then we're evaluating an aggregate expression
John McCalla8f28da2010-08-25 02:50:31 +0000253 // in a context (like an expression statement) that doesn't care
254 // about the result. C says that an lvalue-to-rvalue conversion is
255 // performed in these cases; C++ says that it is not. In either
256 // case, we don't actually need to do anything unless the value is
257 // volatile.
John McCall558d2ab2010-09-15 10:14:12 +0000258 if (Dest.isIgnored()) {
John McCalla8f28da2010-08-25 02:50:31 +0000259 if (!Src.isVolatileQualified() ||
David Blaikie4e4d0842012-03-11 07:00:24 +0000260 CGF.CGM.getLangOpts().CPlusPlus ||
John McCalla8f28da2010-08-25 02:50:31 +0000261 (IgnoreResult && Ignore))
Mike Stump9ccb1032009-05-23 22:01:27 +0000262 return;
Fariborz Jahanian8a970052010-10-22 22:05:03 +0000263
Mike Stump49d1cd52009-05-26 22:03:21 +0000264 // If the source is volatile, we must read from it; to do that, we need
265 // some place to put it.
John McCall558d2ab2010-09-15 10:14:12 +0000266 Dest = CGF.CreateAggTemp(E->getType(), "agg.tmp");
Mike Stump9ccb1032009-05-23 22:01:27 +0000267 }
Chris Lattner883f6a72007-08-11 00:04:45 +0000268
John McCalld1a5f132010-09-16 03:13:23 +0000269 if (Dest.requiresGCollection()) {
Ken Dyck479b61c2011-04-24 17:08:00 +0000270 CharUnits size = CGF.getContext().getTypeSizeInChars(E->getType());
Chris Lattner2acc6e32011-07-18 04:24:23 +0000271 llvm::Type *SizeTy = CGF.ConvertType(CGF.getContext().getSizeType());
Ken Dyck479b61c2011-04-24 17:08:00 +0000272 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
Fariborz Jahanian08c32132009-08-31 19:33:16 +0000273 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
John McCall558d2ab2010-09-15 10:14:12 +0000274 Dest.getAddr(),
275 Src.getAggregateAddr(),
276 SizeVal);
Fariborz Jahanian08c32132009-08-31 19:33:16 +0000277 return;
278 }
Mike Stump4ac20dd2009-05-23 20:28:01 +0000279 // If the result of the assignment is used, copy the LHS there also.
280 // FIXME: Pass VolatileDest as well. I think we also need to merge volatile
281 // from the source as well, as we can't eliminate it if either operand
282 // is volatile, unless copy has volatile for both source and destination..
John McCall558d2ab2010-09-15 10:14:12 +0000283 CGF.EmitAggregateCopy(Dest.getAddr(), Src.getAggregateAddr(), E->getType(),
Eli Friedmanbd7d8282011-12-05 22:23:28 +0000284 Dest.isVolatile()|Src.isVolatileQualified(),
Chad Rosier649b4a12012-03-29 17:37:10 +0000285 Alignment);
Mike Stump4ac20dd2009-05-23 20:28:01 +0000286}
287
288/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
Mike Stump49d1cd52009-05-26 22:03:21 +0000289void AggExprEmitter::EmitFinalDestCopy(const Expr *E, LValue Src, bool Ignore) {
Mike Stump4ac20dd2009-05-23 20:28:01 +0000290 assert(Src.isSimple() && "Can't have aggregate bitfield, vector, etc");
291
Eli Friedmanbd7d8282011-12-05 22:23:28 +0000292 CharUnits Alignment = std::min(Src.getAlignment(), Dest.getAlignment());
293 EmitFinalDestCopy(E, Src.asAggregateRValue(), Ignore, Alignment.getQuantity());
Chris Lattner883f6a72007-08-11 00:04:45 +0000294}
295
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000296static QualType GetStdInitializerListElementType(QualType T) {
297 // Just assume that this is really std::initializer_list.
298 ClassTemplateSpecializationDecl *specialization =
299 cast<ClassTemplateSpecializationDecl>(T->castAs<RecordType>()->getDecl());
300 return specialization->getTemplateArgs()[0].getAsType();
301}
302
303/// \brief Prepare cleanup for the temporary array.
304static void EmitStdInitializerListCleanup(CodeGenFunction &CGF,
305 QualType arrayType,
306 llvm::Value *addr,
307 const InitListExpr *initList) {
308 QualType::DestructionKind dtorKind = arrayType.isDestructedType();
309 if (!dtorKind)
310 return; // Type doesn't need destroying.
311 if (dtorKind != QualType::DK_cxx_destructor) {
312 CGF.ErrorUnsupported(initList, "ObjC ARC type in initializer_list");
313 return;
314 }
315
316 CodeGenFunction::Destroyer *destroyer = CGF.getDestroyer(dtorKind);
317 CGF.pushDestroy(NormalAndEHCleanup, addr, arrayType, destroyer,
318 /*EHCleanup=*/true);
319}
320
321/// \brief Emit the initializer for a std::initializer_list initialized with a
322/// real initializer list.
Sebastian Redlaf130fd2012-02-19 12:28:02 +0000323void AggExprEmitter::EmitStdInitializerList(llvm::Value *destPtr,
324 InitListExpr *initList) {
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000325 // We emit an array containing the elements, then have the init list point
326 // at the array.
327 ASTContext &ctx = CGF.getContext();
328 unsigned numInits = initList->getNumInits();
329 QualType element = GetStdInitializerListElementType(initList->getType());
330 llvm::APInt size(ctx.getTypeSize(ctx.getSizeType()), numInits);
331 QualType array = ctx.getConstantArrayType(element, size, ArrayType::Normal,0);
332 llvm::Type *LTy = CGF.ConvertTypeForMem(array);
333 llvm::AllocaInst *alloc = CGF.CreateTempAlloca(LTy);
334 alloc->setAlignment(ctx.getTypeAlignInChars(array).getQuantity());
335 alloc->setName(".initlist.");
336
337 EmitArrayInit(alloc, cast<llvm::ArrayType>(LTy), element, initList);
338
339 // FIXME: The diagnostics are somewhat out of place here.
340 RecordDecl *record = initList->getType()->castAs<RecordType>()->getDecl();
341 RecordDecl::field_iterator field = record->field_begin();
342 if (field == record->field_end()) {
343 CGF.ErrorUnsupported(initList, "weird std::initializer_list");
Sebastian Redlbabcf9d2012-02-25 20:51:13 +0000344 return;
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000345 }
346
347 QualType elementPtr = ctx.getPointerType(element.withConst());
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000348
349 // Start pointer.
350 if (!ctx.hasSameType(field->getType(), elementPtr)) {
351 CGF.ErrorUnsupported(initList, "weird std::initializer_list");
Sebastian Redlbabcf9d2012-02-25 20:51:13 +0000352 return;
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000353 }
Eli Friedman377ecc72012-04-16 03:54:45 +0000354 LValue DestLV = CGF.MakeNaturalAlignAddrLValue(destPtr, initList->getType());
David Blaikie262bc182012-04-30 02:36:29 +0000355 LValue start = CGF.EmitLValueForFieldInitialization(DestLV, &*field);
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000356 llvm::Value *arrayStart = Builder.CreateStructGEP(alloc, 0, "arraystart");
357 CGF.EmitStoreThroughLValue(RValue::get(arrayStart), start);
358 ++field;
359
360 if (field == record->field_end()) {
361 CGF.ErrorUnsupported(initList, "weird std::initializer_list");
Sebastian Redlbabcf9d2012-02-25 20:51:13 +0000362 return;
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000363 }
David Blaikie262bc182012-04-30 02:36:29 +0000364 LValue endOrLength = CGF.EmitLValueForFieldInitialization(DestLV, &*field);
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000365 if (ctx.hasSameType(field->getType(), elementPtr)) {
366 // End pointer.
367 llvm::Value *arrayEnd = Builder.CreateStructGEP(alloc,numInits, "arrayend");
368 CGF.EmitStoreThroughLValue(RValue::get(arrayEnd), endOrLength);
369 } else if(ctx.hasSameType(field->getType(), ctx.getSizeType())) {
370 // Length.
371 CGF.EmitStoreThroughLValue(RValue::get(Builder.getInt(size)), endOrLength);
372 } else {
373 CGF.ErrorUnsupported(initList, "weird std::initializer_list");
Sebastian Redlbabcf9d2012-02-25 20:51:13 +0000374 return;
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000375 }
376
377 if (!Dest.isExternallyDestructed())
378 EmitStdInitializerListCleanup(CGF, array, alloc, initList);
379}
380
381/// \brief Emit initialization of an array from an initializer list.
382void AggExprEmitter::EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
383 QualType elementType, InitListExpr *E) {
384 uint64_t NumInitElements = E->getNumInits();
385
386 uint64_t NumArrayElements = AType->getNumElements();
387 assert(NumInitElements <= NumArrayElements);
388
389 // DestPtr is an array*. Construct an elementType* by drilling
390 // down a level.
391 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
392 llvm::Value *indices[] = { zero, zero };
393 llvm::Value *begin =
394 Builder.CreateInBoundsGEP(DestPtr, indices, "arrayinit.begin");
395
396 // Exception safety requires us to destroy all the
397 // already-constructed members if an initializer throws.
398 // For that, we'll need an EH cleanup.
399 QualType::DestructionKind dtorKind = elementType.isDestructedType();
400 llvm::AllocaInst *endOfInit = 0;
401 EHScopeStack::stable_iterator cleanup;
402 llvm::Instruction *cleanupDominator = 0;
403 if (CGF.needsEHCleanup(dtorKind)) {
404 // In principle we could tell the cleanup where we are more
405 // directly, but the control flow can get so varied here that it
406 // would actually be quite complex. Therefore we go through an
407 // alloca.
408 endOfInit = CGF.CreateTempAlloca(begin->getType(),
409 "arrayinit.endOfInit");
410 cleanupDominator = Builder.CreateStore(begin, endOfInit);
411 CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
412 CGF.getDestroyer(dtorKind));
413 cleanup = CGF.EHStack.stable_begin();
414
415 // Otherwise, remember that we didn't need a cleanup.
416 } else {
417 dtorKind = QualType::DK_none;
418 }
419
420 llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
421
422 // The 'current element to initialize'. The invariants on this
423 // variable are complicated. Essentially, after each iteration of
424 // the loop, it points to the last initialized element, except
425 // that it points to the beginning of the array before any
426 // elements have been initialized.
427 llvm::Value *element = begin;
428
429 // Emit the explicit initializers.
430 for (uint64_t i = 0; i != NumInitElements; ++i) {
431 // Advance to the next element.
432 if (i > 0) {
433 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element");
434
435 // Tell the cleanup that it needs to destroy up to this
436 // element. TODO: some of these stores can be trivially
437 // observed to be unnecessary.
438 if (endOfInit) Builder.CreateStore(element, endOfInit);
439 }
440
Sebastian Redlaf130fd2012-02-19 12:28:02 +0000441 // If these are nested std::initializer_list inits, do them directly,
442 // because they are conceptually the same "location".
443 InitListExpr *initList = dyn_cast<InitListExpr>(E->getInit(i));
444 if (initList && initList->initializesStdInitializerList()) {
445 EmitStdInitializerList(element, initList);
446 } else {
447 LValue elementLV = CGF.MakeAddrLValue(element, elementType);
Chad Rosier649b4a12012-03-29 17:37:10 +0000448 EmitInitializationToLValue(E->getInit(i), elementLV);
Sebastian Redlaf130fd2012-02-19 12:28:02 +0000449 }
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000450 }
451
452 // Check whether there's a non-trivial array-fill expression.
453 // Note that this will be a CXXConstructExpr even if the element
454 // type is an array (or array of array, etc.) of class type.
455 Expr *filler = E->getArrayFiller();
456 bool hasTrivialFiller = true;
457 if (CXXConstructExpr *cons = dyn_cast_or_null<CXXConstructExpr>(filler)) {
458 assert(cons->getConstructor()->isDefaultConstructor());
459 hasTrivialFiller = cons->getConstructor()->isTrivial();
460 }
461
462 // Any remaining elements need to be zero-initialized, possibly
463 // using the filler expression. We can skip this if the we're
464 // emitting to zeroed memory.
465 if (NumInitElements != NumArrayElements &&
466 !(Dest.isZeroed() && hasTrivialFiller &&
467 CGF.getTypes().isZeroInitializable(elementType))) {
468
469 // Use an actual loop. This is basically
470 // do { *array++ = filler; } while (array != end);
471
472 // Advance to the start of the rest of the array.
473 if (NumInitElements) {
474 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start");
475 if (endOfInit) Builder.CreateStore(element, endOfInit);
476 }
477
478 // Compute the end of the array.
479 llvm::Value *end = Builder.CreateInBoundsGEP(begin,
480 llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
481 "arrayinit.end");
482
483 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
484 llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
485
486 // Jump into the body.
487 CGF.EmitBlock(bodyBB);
488 llvm::PHINode *currentElement =
489 Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
490 currentElement->addIncoming(element, entryBB);
491
492 // Emit the actual filler expression.
493 LValue elementLV = CGF.MakeAddrLValue(currentElement, elementType);
494 if (filler)
Chad Rosier649b4a12012-03-29 17:37:10 +0000495 EmitInitializationToLValue(filler, elementLV);
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000496 else
497 EmitNullInitializationToLValue(elementLV);
498
499 // Move on to the next element.
500 llvm::Value *nextElement =
501 Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
502
503 // Tell the EH cleanup that we finished with the last element.
504 if (endOfInit) Builder.CreateStore(nextElement, endOfInit);
505
506 // Leave the loop if we're done.
507 llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
508 "arrayinit.done");
509 llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
510 Builder.CreateCondBr(done, endBB, bodyBB);
511 currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
512
513 CGF.EmitBlock(endBB);
514 }
515
516 // Leave the partial-array cleanup if we entered one.
517 if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator);
518}
519
Chris Lattneree755f92007-08-21 04:59:27 +0000520//===----------------------------------------------------------------------===//
521// Visitor Methods
522//===----------------------------------------------------------------------===//
523
Douglas Gregor03e80032011-06-21 17:03:29 +0000524void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
525 Visit(E->GetTemporaryExpr());
526}
527
John McCalle996ffd2011-02-16 08:02:54 +0000528void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
John McCall56ca35d2011-02-17 10:25:35 +0000529 EmitFinalDestCopy(e, CGF.getOpaqueLValueMapping(e));
John McCalle996ffd2011-02-16 08:02:54 +0000530}
531
Douglas Gregor751ec9b2011-06-17 04:59:12 +0000532void
533AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
Douglas Gregor673e98b2011-06-17 16:37:20 +0000534 if (E->getType().isPODType(CGF.getContext())) {
535 // For a POD type, just emit a load of the lvalue + a copy, because our
536 // compound literal might alias the destination.
537 // FIXME: This is a band-aid; the real problem appears to be in our handling
538 // of assignments, where we store directly into the LHS without checking
539 // whether anything in the RHS aliases.
540 EmitAggLoadOfLValue(E);
541 return;
542 }
543
Douglas Gregor751ec9b2011-06-17 04:59:12 +0000544 AggValueSlot Slot = EnsureSlot(E->getType());
545 CGF.EmitAggExpr(E->getInitializer(), Slot);
546}
547
548
Anders Carlsson4d8673b2009-08-07 23:22:37 +0000549void AggExprEmitter::VisitCastExpr(CastExpr *E) {
Anders Carlsson30168422009-09-29 01:23:39 +0000550 switch (E->getCastKind()) {
Anders Carlsson575b3742011-04-11 02:03:26 +0000551 case CK_Dynamic: {
Douglas Gregor69cfeb12010-05-14 21:31:02 +0000552 assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
553 LValue LV = CGF.EmitCheckedLValue(E->getSubExpr());
554 // FIXME: Do we also need to handle property references here?
555 if (LV.isSimple())
556 CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
557 else
558 CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
559
John McCall558d2ab2010-09-15 10:14:12 +0000560 if (!Dest.isIgnored())
561 CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
Douglas Gregor69cfeb12010-05-14 21:31:02 +0000562 break;
563 }
564
John McCall2de56d12010-08-25 11:45:40 +0000565 case CK_ToUnion: {
John McCall65912712011-04-12 22:02:02 +0000566 if (Dest.isIgnored()) break;
567
Anders Carlsson4d8673b2009-08-07 23:22:37 +0000568 // GCC union extension
Daniel Dunbar79c39282010-08-21 03:15:20 +0000569 QualType Ty = E->getSubExpr()->getType();
570 QualType PtrTy = CGF.getContext().getPointerType(Ty);
John McCall558d2ab2010-09-15 10:14:12 +0000571 llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
Eli Friedman34ebf4d2009-06-03 20:45:06 +0000572 CGF.ConvertType(PtrTy));
John McCalla07398e2011-06-16 04:16:24 +0000573 EmitInitializationToLValue(E->getSubExpr(),
Chad Rosier649b4a12012-03-29 17:37:10 +0000574 CGF.MakeAddrLValue(CastPtr, Ty));
Anders Carlsson30168422009-09-29 01:23:39 +0000575 break;
Nuno Lopes7e916272009-01-15 20:14:33 +0000576 }
Mike Stump1eb44332009-09-09 15:08:12 +0000577
John McCall2de56d12010-08-25 11:45:40 +0000578 case CK_DerivedToBase:
579 case CK_BaseToDerived:
580 case CK_UncheckedDerivedToBase: {
David Blaikieb219cfc2011-09-23 05:06:16 +0000581 llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000582 "should have been unpacked before we got here");
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000583 }
584
John McCallf6a16482010-12-04 03:47:34 +0000585 case CK_LValueToRValue: // hope for downstream optimization
John McCall2de56d12010-08-25 11:45:40 +0000586 case CK_NoOp:
David Chisnall7a7ee302012-01-16 17:27:18 +0000587 case CK_AtomicToNonAtomic:
588 case CK_NonAtomicToAtomic:
John McCall2de56d12010-08-25 11:45:40 +0000589 case CK_UserDefinedConversion:
590 case CK_ConstructorConversion:
Anders Carlsson30168422009-09-29 01:23:39 +0000591 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
592 E->getType()) &&
593 "Implicit cast types must be compatible");
594 Visit(E->getSubExpr());
595 break;
John McCall0ae287a2010-12-01 04:43:34 +0000596
John McCall2de56d12010-08-25 11:45:40 +0000597 case CK_LValueBitCast:
John McCall0ae287a2010-12-01 04:43:34 +0000598 llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
John McCall1de4d4e2011-04-07 08:22:57 +0000599
John McCall0ae287a2010-12-01 04:43:34 +0000600 case CK_Dependent:
601 case CK_BitCast:
602 case CK_ArrayToPointerDecay:
603 case CK_FunctionToPointerDecay:
604 case CK_NullToPointer:
605 case CK_NullToMemberPointer:
606 case CK_BaseToDerivedMemberPointer:
607 case CK_DerivedToBaseMemberPointer:
608 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +0000609 case CK_ReinterpretMemberPointer:
John McCall0ae287a2010-12-01 04:43:34 +0000610 case CK_IntegralToPointer:
611 case CK_PointerToIntegral:
612 case CK_PointerToBoolean:
613 case CK_ToVoid:
614 case CK_VectorSplat:
615 case CK_IntegralCast:
616 case CK_IntegralToBoolean:
617 case CK_IntegralToFloating:
618 case CK_FloatingToIntegral:
619 case CK_FloatingToBoolean:
620 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +0000621 case CK_CPointerToObjCPointerCast:
622 case CK_BlockPointerToObjCPointerCast:
John McCall0ae287a2010-12-01 04:43:34 +0000623 case CK_AnyPointerToBlockPointerCast:
624 case CK_ObjCObjectLValueCast:
625 case CK_FloatingRealToComplex:
626 case CK_FloatingComplexToReal:
627 case CK_FloatingComplexToBoolean:
628 case CK_FloatingComplexCast:
629 case CK_FloatingComplexToIntegralComplex:
630 case CK_IntegralRealToComplex:
631 case CK_IntegralComplexToReal:
632 case CK_IntegralComplexToBoolean:
633 case CK_IntegralComplexCast:
634 case CK_IntegralComplexToFloatingComplex:
John McCall33e56f32011-09-10 06:18:15 +0000635 case CK_ARCProduceObject:
636 case CK_ARCConsumeObject:
637 case CK_ARCReclaimReturnedObject:
638 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +0000639 case CK_CopyAndAutoreleaseBlockObject:
John McCall0ae287a2010-12-01 04:43:34 +0000640 llvm_unreachable("cast kind invalid for aggregate types");
Anders Carlsson30168422009-09-29 01:23:39 +0000641 }
Anders Carlssone4707ff2008-01-14 06:28:57 +0000642}
643
Chris Lattner96196622008-07-26 22:37:01 +0000644void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
Anders Carlssone70e8f72009-05-27 16:45:02 +0000645 if (E->getCallReturnType()->isReferenceType()) {
646 EmitAggLoadOfLValue(E);
647 return;
648 }
Mike Stump1eb44332009-09-09 15:08:12 +0000649
John McCallfa037bd2010-05-22 22:13:32 +0000650 RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
John McCall410ffb22011-08-25 23:04:34 +0000651 EmitMoveFromReturnSlot(E, RV);
Anders Carlsson148fe672007-10-31 22:04:46 +0000652}
Chris Lattner96196622008-07-26 22:37:01 +0000653
654void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCallfa037bd2010-05-22 22:13:32 +0000655 RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
John McCall410ffb22011-08-25 23:04:34 +0000656 EmitMoveFromReturnSlot(E, RV);
Chris Lattner8fdf3282008-06-24 17:04:18 +0000657}
Anders Carlsson148fe672007-10-31 22:04:46 +0000658
Chris Lattner96196622008-07-26 22:37:01 +0000659void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCall2a416372010-12-05 02:00:02 +0000660 CGF.EmitIgnoredExpr(E->getLHS());
John McCall558d2ab2010-09-15 10:14:12 +0000661 Visit(E->getRHS());
Eli Friedman07fa52a2008-05-20 07:56:31 +0000662}
663
Chris Lattnerb2d963f2007-08-31 22:54:14 +0000664void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCall150b4622011-01-26 04:00:11 +0000665 CodeGenFunction::StmtExprEvaluation eval(CGF);
John McCall558d2ab2010-09-15 10:14:12 +0000666 CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
Chris Lattnerb2d963f2007-08-31 22:54:14 +0000667}
668
Chris Lattner9c033562007-08-21 04:25:47 +0000669void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +0000670 if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
Fariborz Jahanian8bfd31f2009-10-22 22:57:31 +0000671 VisitPointerToDataMemberBinaryOperator(E);
672 else
673 CGF.ErrorUnsupported(E, "aggregate binary expression");
674}
675
676void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
677 const BinaryOperator *E) {
678 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
679 EmitFinalDestCopy(E, LV);
Chris Lattneree755f92007-08-21 04:59:27 +0000680}
681
Chris Lattner03d6fb92007-08-21 04:43:17 +0000682void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Eli Friedmanff6e2b72008-02-11 01:09:17 +0000683 // For an assignment to work, the value on the right has
684 // to be compatible with the value on the left.
Eli Friedman2dce5f82009-05-28 23:04:00 +0000685 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
686 E->getRHS()->getType())
Eli Friedmanff6e2b72008-02-11 01:09:17 +0000687 && "Invalid assignment");
John McCallcd940a12010-12-06 06:10:02 +0000688
Chad Rosier649b4a12012-03-29 17:37:10 +0000689 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getLHS()))
Fariborz Jahanian73a6f8e2011-04-29 22:11:28 +0000690 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Fariborz Jahanian2c7168c2011-04-29 21:53:21 +0000691 if (VD->hasAttr<BlocksAttr>() &&
692 E->getRHS()->HasSideEffects(CGF.getContext())) {
693 // When __block variable on LHS, the RHS must be evaluated first
694 // as it may change the 'forwarding' field via call to Block_copy.
695 LValue RHS = CGF.EmitLValue(E->getRHS());
696 LValue LHS = CGF.EmitLValue(E->getLHS());
John McCall7c2349b2011-08-25 20:40:09 +0000697 Dest = AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
John McCall44184392011-08-26 07:31:35 +0000698 needsGC(E->getLHS()->getType()),
Chad Rosier649b4a12012-03-29 17:37:10 +0000699 AggValueSlot::IsAliased);
Fariborz Jahanian2c7168c2011-04-29 21:53:21 +0000700 EmitFinalDestCopy(E, RHS, true);
701 return;
702 }
Chad Rosier649b4a12012-03-29 17:37:10 +0000703
Chris Lattner9c033562007-08-21 04:25:47 +0000704 LValue LHS = CGF.EmitLValue(E->getLHS());
Chris Lattner883f6a72007-08-11 00:04:45 +0000705
John McCalldb458062011-11-07 03:59:57 +0000706 // Codegen the RHS so that it stores directly into the LHS.
707 AggValueSlot LHSSlot =
708 AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
709 needsGC(E->getLHS()->getType()),
Chad Rosier649b4a12012-03-29 17:37:10 +0000710 AggValueSlot::IsAliased);
John McCalldb458062011-11-07 03:59:57 +0000711 CGF.EmitAggExpr(E->getRHS(), LHSSlot, false);
712 EmitFinalDestCopy(E, LHS, true);
Chris Lattner883f6a72007-08-11 00:04:45 +0000713}
714
John McCall56ca35d2011-02-17 10:25:35 +0000715void AggExprEmitter::
716VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000717 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
718 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
719 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Mike Stump1eb44332009-09-09 15:08:12 +0000720
John McCall56ca35d2011-02-17 10:25:35 +0000721 // Bind the common expression if necessary.
Eli Friedmand97927d2012-01-06 20:42:20 +0000722 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
John McCall56ca35d2011-02-17 10:25:35 +0000723
John McCall150b4622011-01-26 04:00:11 +0000724 CodeGenFunction::ConditionalEvaluation eval(CGF);
Eli Friedman8e274bd2009-12-25 06:17:05 +0000725 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000726
John McCall74fb0ed2010-11-17 00:07:33 +0000727 // Save whether the destination's lifetime is externally managed.
John McCallfd71fb82011-08-26 08:02:37 +0000728 bool isExternallyDestructed = Dest.isExternallyDestructed();
Chris Lattner883f6a72007-08-11 00:04:45 +0000729
John McCall150b4622011-01-26 04:00:11 +0000730 eval.begin(CGF);
731 CGF.EmitBlock(LHSBlock);
John McCall56ca35d2011-02-17 10:25:35 +0000732 Visit(E->getTrueExpr());
John McCall150b4622011-01-26 04:00:11 +0000733 eval.end(CGF);
Mike Stump1eb44332009-09-09 15:08:12 +0000734
John McCall150b4622011-01-26 04:00:11 +0000735 assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
736 CGF.Builder.CreateBr(ContBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000737
John McCall74fb0ed2010-11-17 00:07:33 +0000738 // If the result of an agg expression is unused, then the emission
739 // of the LHS might need to create a destination slot. That's fine
740 // with us, and we can safely emit the RHS into the same slot, but
John McCallfd71fb82011-08-26 08:02:37 +0000741 // we shouldn't claim that it's already being destructed.
742 Dest.setExternallyDestructed(isExternallyDestructed);
John McCall74fb0ed2010-11-17 00:07:33 +0000743
John McCall150b4622011-01-26 04:00:11 +0000744 eval.begin(CGF);
745 CGF.EmitBlock(RHSBlock);
John McCall56ca35d2011-02-17 10:25:35 +0000746 Visit(E->getFalseExpr());
John McCall150b4622011-01-26 04:00:11 +0000747 eval.end(CGF);
Mike Stump1eb44332009-09-09 15:08:12 +0000748
Chris Lattner9c033562007-08-21 04:25:47 +0000749 CGF.EmitBlock(ContBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000750}
Chris Lattneree755f92007-08-21 04:59:27 +0000751
Anders Carlssona294ca82009-07-08 18:33:14 +0000752void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
753 Visit(CE->getChosenSubExpr(CGF.getContext()));
754}
755
Eli Friedmanb1851242008-05-27 15:51:49 +0000756void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Daniel Dunbar07855702009-02-11 22:25:55 +0000757 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000758 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
759
Sebastian Redl0262f022009-01-09 21:09:38 +0000760 if (!ArgPtr) {
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000761 CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
Sebastian Redl0262f022009-01-09 21:09:38 +0000762 return;
763 }
764
Daniel Dunbar79c39282010-08-21 03:15:20 +0000765 EmitFinalDestCopy(VE, CGF.MakeAddrLValue(ArgPtr, VE->getType()));
Eli Friedmanb1851242008-05-27 15:51:49 +0000766}
767
Anders Carlssonb58d0172009-05-30 23:23:33 +0000768void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
John McCall558d2ab2010-09-15 10:14:12 +0000769 // Ensure that we have a slot, but if we already do, remember
John McCallfd71fb82011-08-26 08:02:37 +0000770 // whether it was externally destructed.
771 bool wasExternallyDestructed = Dest.isExternallyDestructed();
John McCall558d2ab2010-09-15 10:14:12 +0000772 Dest = EnsureSlot(E->getType());
John McCallfd71fb82011-08-26 08:02:37 +0000773
774 // We're going to push a destructor if there isn't already one.
775 Dest.setExternallyDestructed();
Mike Stump1eb44332009-09-09 15:08:12 +0000776
John McCall558d2ab2010-09-15 10:14:12 +0000777 Visit(E->getSubExpr());
Anders Carlssonb58d0172009-05-30 23:23:33 +0000778
John McCallfd71fb82011-08-26 08:02:37 +0000779 // Push that destructor we promised.
780 if (!wasExternallyDestructed)
Peter Collingbourne86811602011-11-27 22:09:22 +0000781 CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddr());
Anders Carlssonb58d0172009-05-30 23:23:33 +0000782}
783
Anders Carlssonb14095a2009-04-17 00:06:03 +0000784void
Anders Carlsson31ccf372009-05-03 17:47:16 +0000785AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
John McCall558d2ab2010-09-15 10:14:12 +0000786 AggValueSlot Slot = EnsureSlot(E->getType());
787 CGF.EmitCXXConstructExpr(E, Slot);
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000788}
789
Eli Friedman4c5d8af2012-02-09 03:32:31 +0000790void
791AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
792 AggValueSlot Slot = EnsureSlot(E->getType());
793 CGF.EmitLambdaExpr(E, Slot);
794}
795
John McCall4765fa02010-12-06 08:20:24 +0000796void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
John McCall1a343eb2011-11-10 08:15:53 +0000797 CGF.enterFullExpression(E);
798 CodeGenFunction::RunCleanupsScope cleanups(CGF);
799 Visit(E->getSubExpr());
Anders Carlssonb14095a2009-04-17 00:06:03 +0000800}
801
Douglas Gregored8abf12010-07-08 06:14:04 +0000802void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
John McCall558d2ab2010-09-15 10:14:12 +0000803 QualType T = E->getType();
804 AggValueSlot Slot = EnsureSlot(T);
John McCalla07398e2011-06-16 04:16:24 +0000805 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
Anders Carlsson30311fa2009-12-16 06:57:54 +0000806}
807
808void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
John McCall558d2ab2010-09-15 10:14:12 +0000809 QualType T = E->getType();
810 AggValueSlot Slot = EnsureSlot(T);
John McCalla07398e2011-06-16 04:16:24 +0000811 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
Nuno Lopes329763b2009-10-18 15:18:11 +0000812}
813
Chris Lattner1b726772010-12-02 07:07:26 +0000814/// isSimpleZero - If emitting this value will obviously just cause a store of
815/// zero to memory, return true. This can return false if uncertain, so it just
816/// handles simple cases.
817static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
Peter Collingbournef111d932011-04-15 00:35:48 +0000818 E = E->IgnoreParens();
819
Chris Lattner1b726772010-12-02 07:07:26 +0000820 // 0
821 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
822 return IL->getValue() == 0;
823 // +0.0
824 if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
825 return FL->getValue().isPosZero();
826 // int()
827 if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
828 CGF.getTypes().isZeroInitializable(E->getType()))
829 return true;
830 // (int*)0 - Null pointer expressions.
831 if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
832 return ICE->getCastKind() == CK_NullToPointer;
833 // '\0'
834 if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
835 return CL->getValue() == 0;
836
837 // Otherwise, hard case: conservatively return false.
838 return false;
839}
840
841
Anders Carlsson78e83f82010-02-03 17:33:16 +0000842void
Chad Rosier649b4a12012-03-29 17:37:10 +0000843AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) {
John McCalla07398e2011-06-16 04:16:24 +0000844 QualType type = LV.getType();
Mike Stump7f79f9b2009-05-29 15:46:01 +0000845 // FIXME: Ignore result?
Chris Lattnerf81557c2008-04-04 18:42:16 +0000846 // FIXME: Are initializers affected by volatile?
Chris Lattner1b726772010-12-02 07:07:26 +0000847 if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
848 // Storing "i32 0" to a zero'd memory location is a noop.
849 } else if (isa<ImplicitValueInitExpr>(E)) {
John McCalla07398e2011-06-16 04:16:24 +0000850 EmitNullInitializationToLValue(LV);
851 } else if (type->isReferenceType()) {
Anders Carlsson32f36ba2010-06-26 16:35:32 +0000852 RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
John McCall545d9962011-06-25 02:11:03 +0000853 CGF.EmitStoreThroughLValue(RV, LV);
John McCalla07398e2011-06-16 04:16:24 +0000854 } else if (type->isAnyComplexType()) {
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000855 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
John McCalla07398e2011-06-16 04:16:24 +0000856 } else if (CGF.hasAggregateLLVMType(type)) {
John McCall7c2349b2011-08-25 20:40:09 +0000857 CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV,
858 AggValueSlot::IsDestructed,
859 AggValueSlot::DoesNotNeedGCBarriers,
John McCall410ffb22011-08-25 23:04:34 +0000860 AggValueSlot::IsNotAliased,
John McCalla07398e2011-06-16 04:16:24 +0000861 Dest.isZeroed()));
John McCallf85e1932011-06-15 23:02:42 +0000862 } else if (LV.isSimple()) {
John McCalla07398e2011-06-16 04:16:24 +0000863 CGF.EmitScalarInit(E, /*D=*/0, LV, /*Captured=*/false);
Eli Friedmanc8ba9612008-05-12 15:06:05 +0000864 } else {
John McCall545d9962011-06-25 02:11:03 +0000865 CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
Chris Lattnerf81557c2008-04-04 18:42:16 +0000866 }
Chris Lattnerf81557c2008-04-04 18:42:16 +0000867}
868
John McCalla07398e2011-06-16 04:16:24 +0000869void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
870 QualType type = lv.getType();
871
Chris Lattner1b726772010-12-02 07:07:26 +0000872 // If the destination slot is already zeroed out before the aggregate is
873 // copied into it, we don't have to emit any zeros here.
John McCalla07398e2011-06-16 04:16:24 +0000874 if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
Chris Lattner1b726772010-12-02 07:07:26 +0000875 return;
876
John McCalla07398e2011-06-16 04:16:24 +0000877 if (!CGF.hasAggregateLLVMType(type)) {
Eli Friedmanb1e3f322012-02-22 05:38:59 +0000878 // For non-aggregates, we can store zero.
John McCalla07398e2011-06-16 04:16:24 +0000879 llvm::Value *null = llvm::Constant::getNullValue(CGF.ConvertType(type));
Eli Friedmanb1e3f322012-02-22 05:38:59 +0000880 // Note that the following is not equivalent to
881 // EmitStoreThroughBitfieldLValue for ARC types.
Eli Friedman5a13d4d2012-02-24 23:53:49 +0000882 if (lv.isBitField()) {
Eli Friedmanb1e3f322012-02-22 05:38:59 +0000883 CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
Eli Friedman5a13d4d2012-02-24 23:53:49 +0000884 } else {
885 assert(lv.isSimple());
886 CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
887 }
Lauro Ramos Venancio145cd892008-02-19 19:27:31 +0000888 } else {
Chris Lattnerf81557c2008-04-04 18:42:16 +0000889 // There's a potential optimization opportunity in combining
890 // memsets; that would be easy for arrays, but relatively
891 // difficult for structures with the current code.
John McCalla07398e2011-06-16 04:16:24 +0000892 CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
Chris Lattnerf81557c2008-04-04 18:42:16 +0000893 }
894}
895
Chris Lattnerf81557c2008-04-04 18:42:16 +0000896void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
Eli Friedmana385b3c2008-12-02 01:17:45 +0000897#if 0
Eli Friedman13a5be12009-12-04 01:30:56 +0000898 // FIXME: Assess perf here? Figure out what cases are worth optimizing here
899 // (Length of globals? Chunks of zeroed-out space?).
Eli Friedmana385b3c2008-12-02 01:17:45 +0000900 //
Mike Stumpf5408fe2009-05-16 07:57:57 +0000901 // If we can, prefer a copy from a global; this is a lot less code for long
902 // globals, and it's easier for the current optimizers to analyze.
Eli Friedman13a5be12009-12-04 01:30:56 +0000903 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
Eli Friedman994ffef2008-11-30 02:11:09 +0000904 llvm::GlobalVariable* GV =
Eli Friedman13a5be12009-12-04 01:30:56 +0000905 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
906 llvm::GlobalValue::InternalLinkage, C, "");
Daniel Dunbar79c39282010-08-21 03:15:20 +0000907 EmitFinalDestCopy(E, CGF.MakeAddrLValue(GV, E->getType()));
Eli Friedman994ffef2008-11-30 02:11:09 +0000908 return;
909 }
Eli Friedmana385b3c2008-12-02 01:17:45 +0000910#endif
Chris Lattnerd0db03a2010-09-06 00:11:41 +0000911 if (E->hadArrayRangeDesignator())
Douglas Gregora9c87802009-01-29 19:42:23 +0000912 CGF.ErrorUnsupported(E, "GNU array range designator extension");
Douglas Gregora9c87802009-01-29 19:42:23 +0000913
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000914 if (E->initializesStdInitializerList()) {
Sebastian Redlaf130fd2012-02-19 12:28:02 +0000915 EmitStdInitializerList(Dest.getAddr(), E);
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000916 return;
917 }
918
Eli Friedman377ecc72012-04-16 03:54:45 +0000919 AggValueSlot Dest = EnsureSlot(E->getType());
920 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddr(), E->getType(),
921 Dest.getAlignment());
John McCall558d2ab2010-09-15 10:14:12 +0000922
Chris Lattnerf81557c2008-04-04 18:42:16 +0000923 // Handle initialization of an array.
924 if (E->getType()->isArrayType()) {
Richard Smithfe587202012-04-15 02:50:59 +0000925 if (E->isStringLiteralInit())
926 return Visit(E->getInit(0));
Eli Friedman922696f2008-05-19 17:51:16 +0000927
Eli Friedman5c89c392012-02-23 02:25:10 +0000928 QualType elementType =
929 CGF.getContext().getAsArrayType(E->getType())->getElementType();
Argyrios Kyrtzidis3b4d4902011-04-28 18:53:58 +0000930
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000931 llvm::PointerType *APType =
Eli Friedman377ecc72012-04-16 03:54:45 +0000932 cast<llvm::PointerType>(Dest.getAddr()->getType());
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000933 llvm::ArrayType *AType =
934 cast<llvm::ArrayType>(APType->getElementType());
Chris Lattner1b726772010-12-02 07:07:26 +0000935
Eli Friedman377ecc72012-04-16 03:54:45 +0000936 EmitArrayInit(Dest.getAddr(), AType, elementType, E);
Chris Lattnerf81557c2008-04-04 18:42:16 +0000937 return;
938 }
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Chris Lattnerf81557c2008-04-04 18:42:16 +0000940 assert(E->getType()->isRecordType() && "Only support structs/unions here!");
Mike Stump1eb44332009-09-09 15:08:12 +0000941
Chris Lattnerf81557c2008-04-04 18:42:16 +0000942 // Do struct initialization; this code just sets each individual member
943 // to the approprate value. This makes bitfield support automatic;
944 // the disadvantage is that the generated code is more difficult for
945 // the optimizer, especially with bitfields.
946 unsigned NumInitElements = E->getNumInits();
John McCall2b30dcf2011-07-11 19:35:02 +0000947 RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
Chris Lattnerbd7de382010-09-06 00:13:11 +0000948
John McCall2b30dcf2011-07-11 19:35:02 +0000949 if (record->isUnion()) {
Douglas Gregor0bb76892009-01-29 16:53:55 +0000950 // Only initialize one field of a union. The field itself is
951 // specified by the initializer list.
952 if (!E->getInitializedFieldInUnion()) {
953 // Empty union; we have nothing to do.
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Douglas Gregor0bb76892009-01-29 16:53:55 +0000955#ifndef NDEBUG
956 // Make sure that it's really an empty and not a failure of
957 // semantic analysis.
John McCall2b30dcf2011-07-11 19:35:02 +0000958 for (RecordDecl::field_iterator Field = record->field_begin(),
959 FieldEnd = record->field_end();
Douglas Gregor0bb76892009-01-29 16:53:55 +0000960 Field != FieldEnd; ++Field)
961 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
962#endif
963 return;
964 }
965
966 // FIXME: volatility
967 FieldDecl *Field = E->getInitializedFieldInUnion();
Douglas Gregor0bb76892009-01-29 16:53:55 +0000968
Eli Friedman377ecc72012-04-16 03:54:45 +0000969 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +0000970 if (NumInitElements) {
971 // Store the initializer into the field
Chad Rosier649b4a12012-03-29 17:37:10 +0000972 EmitInitializationToLValue(E->getInit(0), FieldLoc);
Douglas Gregor0bb76892009-01-29 16:53:55 +0000973 } else {
Chris Lattner1b726772010-12-02 07:07:26 +0000974 // Default-initialize to null.
John McCalla07398e2011-06-16 04:16:24 +0000975 EmitNullInitializationToLValue(FieldLoc);
Douglas Gregor0bb76892009-01-29 16:53:55 +0000976 }
977
978 return;
979 }
Mike Stump1eb44332009-09-09 15:08:12 +0000980
John McCall2b30dcf2011-07-11 19:35:02 +0000981 // We'll need to enter cleanup scopes in case any of the member
982 // initializers throw an exception.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000983 SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
John McCall6f103ba2011-11-10 10:43:54 +0000984 llvm::Instruction *cleanupDominator = 0;
John McCall2b30dcf2011-07-11 19:35:02 +0000985
Chris Lattnerf81557c2008-04-04 18:42:16 +0000986 // Here we iterate over the fields; this makes it simpler to both
987 // default-initialize fields and skip over unnamed fields.
John McCall2b30dcf2011-07-11 19:35:02 +0000988 unsigned curInitIndex = 0;
989 for (RecordDecl::field_iterator field = record->field_begin(),
990 fieldEnd = record->field_end();
991 field != fieldEnd; ++field) {
992 // We're done once we hit the flexible array member.
993 if (field->getType()->isIncompleteArrayType())
Douglas Gregor44b43212008-12-11 16:49:14 +0000994 break;
995
John McCall2b30dcf2011-07-11 19:35:02 +0000996 // Always skip anonymous bitfields.
997 if (field->isUnnamedBitfield())
Chris Lattnerf81557c2008-04-04 18:42:16 +0000998 continue;
Douglas Gregor34e79462009-01-28 23:36:17 +0000999
John McCall2b30dcf2011-07-11 19:35:02 +00001000 // We're done if we reach the end of the explicit initializers, we
1001 // have a zeroed object, and the rest of the fields are
1002 // zero-initializable.
1003 if (curInitIndex == NumInitElements && Dest.isZeroed() &&
Chris Lattner1b726772010-12-02 07:07:26 +00001004 CGF.getTypes().isZeroInitializable(E->getType()))
1005 break;
1006
Eli Friedman377ecc72012-04-16 03:54:45 +00001007
David Blaikie262bc182012-04-30 02:36:29 +00001008 LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, &*field);
Fariborz Jahanian14674ff2009-05-27 19:54:11 +00001009 // We never generate write-barries for initialized fields.
John McCall2b30dcf2011-07-11 19:35:02 +00001010 LV.setNonGC(true);
Chris Lattner1b726772010-12-02 07:07:26 +00001011
John McCall2b30dcf2011-07-11 19:35:02 +00001012 if (curInitIndex < NumInitElements) {
Chris Lattnerb35baae2010-03-08 21:08:07 +00001013 // Store the initializer into the field.
Chad Rosier649b4a12012-03-29 17:37:10 +00001014 EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
Chris Lattnerf81557c2008-04-04 18:42:16 +00001015 } else {
1016 // We're out of initalizers; default-initialize to null
John McCall2b30dcf2011-07-11 19:35:02 +00001017 EmitNullInitializationToLValue(LV);
1018 }
1019
1020 // Push a destructor if necessary.
1021 // FIXME: if we have an array of structures, all explicitly
1022 // initialized, we can end up pushing a linear number of cleanups.
1023 bool pushedCleanup = false;
1024 if (QualType::DestructionKind dtorKind
1025 = field->getType().isDestructedType()) {
1026 assert(LV.isSimple());
1027 if (CGF.needsEHCleanup(dtorKind)) {
John McCall6f103ba2011-11-10 10:43:54 +00001028 if (!cleanupDominator)
1029 cleanupDominator = CGF.Builder.CreateUnreachable(); // placeholder
1030
John McCall2b30dcf2011-07-11 19:35:02 +00001031 CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
1032 CGF.getDestroyer(dtorKind), false);
1033 cleanups.push_back(CGF.EHStack.stable_begin());
1034 pushedCleanup = true;
1035 }
Chris Lattnerf81557c2008-04-04 18:42:16 +00001036 }
Chris Lattner1b726772010-12-02 07:07:26 +00001037
1038 // If the GEP didn't get used because of a dead zero init or something
1039 // else, clean it up for -O0 builds and general tidiness.
John McCall2b30dcf2011-07-11 19:35:02 +00001040 if (!pushedCleanup && LV.isSimple())
Chris Lattner1b726772010-12-02 07:07:26 +00001041 if (llvm::GetElementPtrInst *GEP =
John McCall2b30dcf2011-07-11 19:35:02 +00001042 dyn_cast<llvm::GetElementPtrInst>(LV.getAddress()))
Chris Lattner1b726772010-12-02 07:07:26 +00001043 if (GEP->use_empty())
1044 GEP->eraseFromParent();
Lauro Ramos Venancio145cd892008-02-19 19:27:31 +00001045 }
John McCall2b30dcf2011-07-11 19:35:02 +00001046
1047 // Deactivate all the partial cleanups in reverse order, which
1048 // generally means popping them.
1049 for (unsigned i = cleanups.size(); i != 0; --i)
John McCall6f103ba2011-11-10 10:43:54 +00001050 CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
1051
1052 // Destroy the placeholder if we made one.
1053 if (cleanupDominator)
1054 cleanupDominator->eraseFromParent();
Devang Patel636c3d02007-10-26 17:44:44 +00001055}
1056
Chris Lattneree755f92007-08-21 04:59:27 +00001057//===----------------------------------------------------------------------===//
1058// Entry Points into this File
1059//===----------------------------------------------------------------------===//
1060
Chris Lattner1b726772010-12-02 07:07:26 +00001061/// GetNumNonZeroBytesInInit - Get an approximate count of the number of
1062/// non-zero bytes that will be stored when outputting the initializer for the
1063/// specified initializer expression.
Ken Dyck02c45332011-04-24 17:17:56 +00001064static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
Peter Collingbournef111d932011-04-15 00:35:48 +00001065 E = E->IgnoreParens();
Chris Lattner1b726772010-12-02 07:07:26 +00001066
1067 // 0 and 0.0 won't require any non-zero stores!
Ken Dyck02c45332011-04-24 17:17:56 +00001068 if (isSimpleZero(E, CGF)) return CharUnits::Zero();
Chris Lattner1b726772010-12-02 07:07:26 +00001069
1070 // If this is an initlist expr, sum up the size of sizes of the (present)
1071 // elements. If this is something weird, assume the whole thing is non-zero.
1072 const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
1073 if (ILE == 0 || !CGF.getTypes().isZeroInitializable(ILE->getType()))
Ken Dyck02c45332011-04-24 17:17:56 +00001074 return CGF.getContext().getTypeSizeInChars(E->getType());
Chris Lattner1b726772010-12-02 07:07:26 +00001075
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001076 // InitListExprs for structs have to be handled carefully. If there are
1077 // reference members, we need to consider the size of the reference, not the
1078 // referencee. InitListExprs for unions and arrays can't have references.
Chris Lattner8c00ad12010-12-02 22:52:04 +00001079 if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
1080 if (!RT->isUnionType()) {
1081 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
Ken Dyck02c45332011-04-24 17:17:56 +00001082 CharUnits NumNonZeroBytes = CharUnits::Zero();
Chris Lattner8c00ad12010-12-02 22:52:04 +00001083
1084 unsigned ILEElement = 0;
1085 for (RecordDecl::field_iterator Field = SD->field_begin(),
1086 FieldEnd = SD->field_end(); Field != FieldEnd; ++Field) {
1087 // We're done once we hit the flexible array member or run out of
1088 // InitListExpr elements.
1089 if (Field->getType()->isIncompleteArrayType() ||
1090 ILEElement == ILE->getNumInits())
1091 break;
1092 if (Field->isUnnamedBitfield())
1093 continue;
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001094
Chris Lattner8c00ad12010-12-02 22:52:04 +00001095 const Expr *E = ILE->getInit(ILEElement++);
1096
1097 // Reference values are always non-null and have the width of a pointer.
1098 if (Field->getType()->isReferenceType())
Ken Dyck02c45332011-04-24 17:17:56 +00001099 NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001100 CGF.getContext().getTargetInfo().getPointerWidth(0));
Chris Lattner8c00ad12010-12-02 22:52:04 +00001101 else
1102 NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
1103 }
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001104
Chris Lattner8c00ad12010-12-02 22:52:04 +00001105 return NumNonZeroBytes;
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001106 }
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001107 }
1108
1109
Ken Dyck02c45332011-04-24 17:17:56 +00001110 CharUnits NumNonZeroBytes = CharUnits::Zero();
Chris Lattner1b726772010-12-02 07:07:26 +00001111 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1112 NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
1113 return NumNonZeroBytes;
1114}
1115
1116/// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
1117/// zeros in it, emit a memset and avoid storing the individual zeros.
1118///
1119static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
1120 CodeGenFunction &CGF) {
1121 // If the slot is already known to be zeroed, nothing to do. Don't mess with
1122 // volatile stores.
1123 if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == 0) return;
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +00001124
1125 // C++ objects with a user-declared constructor don't need zero'ing.
David Blaikie4e4d0842012-03-11 07:00:24 +00001126 if (CGF.getContext().getLangOpts().CPlusPlus)
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +00001127 if (const RecordType *RT = CGF.getContext()
1128 .getBaseElementType(E->getType())->getAs<RecordType>()) {
1129 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1130 if (RD->hasUserDeclaredConstructor())
1131 return;
1132 }
1133
Chris Lattner1b726772010-12-02 07:07:26 +00001134 // If the type is 16-bytes or smaller, prefer individual stores over memset.
Ken Dyck5ff1a352011-04-24 17:25:32 +00001135 std::pair<CharUnits, CharUnits> TypeInfo =
1136 CGF.getContext().getTypeInfoInChars(E->getType());
1137 if (TypeInfo.first <= CharUnits::fromQuantity(16))
Chris Lattner1b726772010-12-02 07:07:26 +00001138 return;
1139
1140 // Check to see if over 3/4 of the initializer are known to be zero. If so,
1141 // we prefer to emit memset + individual stores for the rest.
Ken Dyck5ff1a352011-04-24 17:25:32 +00001142 CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
1143 if (NumNonZeroBytes*4 > TypeInfo.first)
Chris Lattner1b726772010-12-02 07:07:26 +00001144 return;
1145
1146 // Okay, it seems like a good idea to use an initial memset, emit the call.
Ken Dyck5ff1a352011-04-24 17:25:32 +00001147 llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first.getQuantity());
1148 CharUnits Align = TypeInfo.second;
Chris Lattner1b726772010-12-02 07:07:26 +00001149
1150 llvm::Value *Loc = Slot.getAddr();
Chris Lattner1b726772010-12-02 07:07:26 +00001151
Chris Lattner8b418682012-02-07 00:39:47 +00001152 Loc = CGF.Builder.CreateBitCast(Loc, CGF.Int8PtrTy);
Ken Dyck5ff1a352011-04-24 17:25:32 +00001153 CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal,
1154 Align.getQuantity(), false);
Chris Lattner1b726772010-12-02 07:07:26 +00001155
1156 // Tell the AggExprEmitter that the slot is known zero.
1157 Slot.setZeroed();
1158}
1159
1160
1161
1162
Mike Stumpe1129a92009-05-26 18:57:45 +00001163/// EmitAggExpr - Emit the computation of the specified expression of aggregate
1164/// type. The result is computed into DestPtr. Note that if DestPtr is null,
1165/// the value of the aggregate expression is not needed. If VolatileDest is
1166/// true, DestPtr cannot be 0.
John McCall558d2ab2010-09-15 10:14:12 +00001167///
1168/// \param IsInitializer - true if this evaluation is initializing an
1169/// object whose lifetime is already being managed.
John McCall558d2ab2010-09-15 10:14:12 +00001170void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot,
Fariborz Jahanian474e2fe2010-09-16 00:20:07 +00001171 bool IgnoreResult) {
Chris Lattneree755f92007-08-21 04:59:27 +00001172 assert(E && hasAggregateLLVMType(E->getType()) &&
1173 "Invalid aggregate expression to emit");
Chris Lattner1b726772010-12-02 07:07:26 +00001174 assert((Slot.getAddr() != 0 || Slot.isIgnored()) &&
1175 "slot has bits but no address");
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Chris Lattner1b726772010-12-02 07:07:26 +00001177 // Optimize the slot if possible.
1178 CheckAggExprForMemSetUse(Slot, E, *this);
1179
1180 AggExprEmitter(*this, Slot, IgnoreResult).Visit(const_cast<Expr*>(E));
Chris Lattneree755f92007-08-21 04:59:27 +00001181}
Daniel Dunbar7482d122008-09-09 20:49:46 +00001182
Daniel Dunbar18aba0d2010-02-05 19:38:31 +00001183LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
1184 assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!");
Daniel Dunbar195337d2010-02-09 02:48:28 +00001185 llvm::Value *Temp = CreateMemTemp(E->getType());
Daniel Dunbar79c39282010-08-21 03:15:20 +00001186 LValue LV = MakeAddrLValue(Temp, E->getType());
John McCall7c2349b2011-08-25 20:40:09 +00001187 EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,
John McCall44184392011-08-26 07:31:35 +00001188 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001189 AggValueSlot::IsNotAliased));
Daniel Dunbar79c39282010-08-21 03:15:20 +00001190 return LV;
Daniel Dunbar18aba0d2010-02-05 19:38:31 +00001191}
1192
Chad Rosier649b4a12012-03-29 17:37:10 +00001193void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
1194 llvm::Value *SrcPtr, QualType Ty,
1195 bool isVolatile, unsigned Alignment) {
1196 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
Mike Stump1eb44332009-09-09 15:08:12 +00001197
David Blaikie4e4d0842012-03-11 07:00:24 +00001198 if (getContext().getLangOpts().CPlusPlus) {
Chad Rosier649b4a12012-03-29 17:37:10 +00001199 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1200 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
1201 assert((Record->hasTrivialCopyConstructor() ||
1202 Record->hasTrivialCopyAssignment() ||
1203 Record->hasTrivialMoveConstructor() ||
1204 Record->hasTrivialMoveAssignment()) &&
Douglas Gregore9979482010-05-20 15:39:01 +00001205 "Trying to aggregate-copy a type without a trivial copy "
1206 "constructor or assignment operator");
Chad Rosier649b4a12012-03-29 17:37:10 +00001207 // Ignore empty classes in C++.
1208 if (Record->isEmpty())
Anders Carlsson0d7c5832010-05-03 01:20:20 +00001209 return;
1210 }
1211 }
1212
Chris Lattner83c96292009-02-28 18:31:01 +00001213 // Aggregate assignment turns into llvm.memcpy. This is almost valid per
Chris Lattnerca4fc2c2009-02-28 18:18:58 +00001214 // C99 6.5.16.1p3, which states "If the value being stored in an object is
1215 // read from another object that overlaps in anyway the storage of the first
1216 // object, then the overlap shall be exact and the two objects shall have
1217 // qualified or unqualified versions of a compatible type."
1218 //
Chris Lattner83c96292009-02-28 18:31:01 +00001219 // memcpy is not defined if the source and destination pointers are exactly
Chris Lattnerca4fc2c2009-02-28 18:18:58 +00001220 // equal, but other compilers do this optimization, and almost every memcpy
1221 // implementation handles this case safely. If there is a libc that does not
1222 // safely handle this, we can add a target hook.
Chad Rosier649b4a12012-03-29 17:37:10 +00001223
1224 // Get size and alignment info for this aggregate.
1225 std::pair<CharUnits, CharUnits> TypeInfo =
1226 getContext().getTypeInfoInChars(Ty);
1227
1228 if (!Alignment)
1229 Alignment = TypeInfo.second.getQuantity();
1230
1231 // FIXME: Handle variable sized types.
1232
1233 // FIXME: If we have a volatile struct, the optimizer can remove what might
1234 // appear to be `extra' memory ops:
1235 //
1236 // volatile struct { int i; } a, b;
1237 //
1238 // int main() {
1239 // a = b;
1240 // a = b;
1241 // }
1242 //
1243 // we need to use a different call here. We use isVolatile to indicate when
1244 // either the source or the destination is volatile.
1245
1246 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
1247 llvm::Type *DBP =
1248 llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace());
1249 DestPtr = Builder.CreateBitCast(DestPtr, DBP);
1250
1251 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
1252 llvm::Type *SBP =
1253 llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace());
1254 SrcPtr = Builder.CreateBitCast(SrcPtr, SBP);
1255
1256 // Don't do any of the memmove_collectable tests if GC isn't set.
1257 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
1258 // fall through
1259 } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1260 RecordDecl *Record = RecordTy->getDecl();
1261 if (Record->hasObjectMember()) {
1262 CharUnits size = TypeInfo.first;
1263 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1264 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
1265 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1266 SizeVal);
1267 return;
1268 }
1269 } else if (Ty->isArrayType()) {
1270 QualType BaseType = getContext().getBaseElementType(Ty);
1271 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
1272 if (RecordTy->getDecl()->hasObjectMember()) {
1273 CharUnits size = TypeInfo.first;
1274 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1275 llvm::Value *SizeVal =
1276 llvm::ConstantInt::get(SizeTy, size.getQuantity());
1277 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1278 SizeVal);
1279 return;
1280 }
1281 }
1282 }
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00001283
Chad Rosier649b4a12012-03-29 17:37:10 +00001284 Builder.CreateMemCpy(DestPtr, SrcPtr,
1285 llvm::ConstantInt::get(IntPtrTy,
1286 TypeInfo.first.getQuantity()),
1287 Alignment, isVolatile);
Daniel Dunbar7482d122008-09-09 20:49:46 +00001288}
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001289
Sebastian Redl972edf02012-02-19 16:03:09 +00001290void CodeGenFunction::MaybeEmitStdInitializerListCleanup(llvm::Value *loc,
1291 const Expr *init) {
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001292 const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(init);
Sebastian Redl972edf02012-02-19 16:03:09 +00001293 if (cleanups)
1294 init = cleanups->getSubExpr();
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001295
1296 if (isa<InitListExpr>(init) &&
1297 cast<InitListExpr>(init)->initializesStdInitializerList()) {
1298 // We initialized this std::initializer_list with an initializer list.
1299 // A backing array was created. Push a cleanup for it.
Sebastian Redl972edf02012-02-19 16:03:09 +00001300 EmitStdInitializerListCleanup(loc, cast<InitListExpr>(init));
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001301 }
1302}
1303
Sebastian Redlaf130fd2012-02-19 12:28:02 +00001304static void EmitRecursiveStdInitializerListCleanup(CodeGenFunction &CGF,
1305 llvm::Value *arrayStart,
1306 const InitListExpr *init) {
1307 // Check if there are any recursive cleanups to do, i.e. if we have
1308 // std::initializer_list<std::initializer_list<obj>> list = {{obj()}};
1309 // then we need to destroy the inner array as well.
1310 for (unsigned i = 0, e = init->getNumInits(); i != e; ++i) {
1311 const InitListExpr *subInit = dyn_cast<InitListExpr>(init->getInit(i));
1312 if (!subInit || !subInit->initializesStdInitializerList())
1313 continue;
1314
1315 // This one needs to be destroyed. Get the address of the std::init_list.
1316 llvm::Value *offset = llvm::ConstantInt::get(CGF.SizeTy, i);
1317 llvm::Value *loc = CGF.Builder.CreateInBoundsGEP(arrayStart, offset,
1318 "std.initlist");
1319 CGF.EmitStdInitializerListCleanup(loc, subInit);
1320 }
1321}
1322
1323void CodeGenFunction::EmitStdInitializerListCleanup(llvm::Value *loc,
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001324 const InitListExpr *init) {
1325 ASTContext &ctx = getContext();
1326 QualType element = GetStdInitializerListElementType(init->getType());
1327 unsigned numInits = init->getNumInits();
1328 llvm::APInt size(ctx.getTypeSize(ctx.getSizeType()), numInits);
1329 QualType array =ctx.getConstantArrayType(element, size, ArrayType::Normal, 0);
1330 QualType arrayPtr = ctx.getPointerType(array);
1331 llvm::Type *arrayPtrType = ConvertType(arrayPtr);
1332
1333 // lvalue is the location of a std::initializer_list, which as its first
1334 // element has a pointer to the array we want to destroy.
Sebastian Redlaf130fd2012-02-19 12:28:02 +00001335 llvm::Value *startPointer = Builder.CreateStructGEP(loc, 0, "startPointer");
1336 llvm::Value *startAddress = Builder.CreateLoad(startPointer, "startAddress");
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001337
Sebastian Redlaf130fd2012-02-19 12:28:02 +00001338 ::EmitRecursiveStdInitializerListCleanup(*this, startAddress, init);
1339
1340 llvm::Value *arrayAddress =
1341 Builder.CreateBitCast(startAddress, arrayPtrType, "arrayAddress");
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001342 ::EmitStdInitializerListCleanup(*this, array, arrayAddress, init);
1343}