blob: 48b21d2f851d0c13b7dc73b14245d0d87a02e757 [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;
John McCallef072fd2010-05-22 01:48:05 +000037
John McCall410ffb22011-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 McCallef072fd2010-05-22 01:48:05 +000047 ReturnValueSlot getReturnValueSlot() const {
John McCall410ffb22011-08-25 23:04:34 +000048 if (!shouldUseDestForReturnSlot())
49 return ReturnValueSlot();
John McCallfa037bd2010-05-22 22:13:32 +000050
John McCall558d2ab2010-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 McCallef072fd2010-05-22 01:48:05 +000057 }
John McCalle0c11682012-07-02 23:58:38 +000058 void EnsureDest(QualType T) {
59 if (!Dest.isIgnored()) return;
60 Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured");
61 }
John McCallfa037bd2010-05-22 22:13:32 +000062
Chris Lattner9c033562007-08-21 04:25:47 +000063public:
John McCalle0c11682012-07-02 23:58:38 +000064 AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest)
65 : CGF(cgf), Builder(CGF.Builder), Dest(Dest) {
Chris Lattner9c033562007-08-21 04:25:47 +000066 }
67
Chris Lattneree755f92007-08-21 04:59:27 +000068 //===--------------------------------------------------------------------===//
69 // Utilities
70 //===--------------------------------------------------------------------===//
71
Chris Lattner9c033562007-08-21 04:25:47 +000072 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
73 /// represents a value lvalue, this method emits the address of the lvalue,
74 /// then loads the result into DestPtr.
75 void EmitAggLoadOfLValue(const Expr *E);
Eli Friedman922696f2008-05-19 17:51:16 +000076
Mike Stump4ac20dd2009-05-23 20:28:01 +000077 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
John McCalle0c11682012-07-02 23:58:38 +000078 void EmitFinalDestCopy(QualType type, const LValue &src);
79 void EmitFinalDestCopy(QualType type, RValue src,
80 CharUnits srcAlignment = CharUnits::Zero());
81 void EmitCopy(QualType type, const AggValueSlot &dest,
82 const AggValueSlot &src);
Mike Stump4ac20dd2009-05-23 20:28:01 +000083
John McCall410ffb22011-08-25 23:04:34 +000084 void EmitMoveFromReturnSlot(const Expr *E, RValue Src);
John McCallfa037bd2010-05-22 22:13:32 +000085
Sebastian Redlaf130fd2012-02-19 12:28:02 +000086 void EmitStdInitializerList(llvm::Value *DestPtr, InitListExpr *InitList);
Sebastian Redl32cf1f22012-02-17 08:42:25 +000087 void EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
88 QualType elementType, InitListExpr *E);
89
John McCall7c2349b2011-08-25 20:40:09 +000090 AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
David Blaikie4e4d0842012-03-11 07:00:24 +000091 if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))
John McCall7c2349b2011-08-25 20:40:09 +000092 return AggValueSlot::NeedsGCBarriers;
93 return AggValueSlot::DoesNotNeedGCBarriers;
94 }
95
John McCallfa037bd2010-05-22 22:13:32 +000096 bool TypeRequiresGCollection(QualType T);
97
Chris Lattneree755f92007-08-21 04:59:27 +000098 //===--------------------------------------------------------------------===//
99 // Visitor Methods
100 //===--------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000101
Chris Lattner9c033562007-08-21 04:25:47 +0000102 void VisitStmt(Stmt *S) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000103 CGF.ErrorUnsupported(S, "aggregate expression");
Chris Lattner9c033562007-08-21 04:25:47 +0000104 }
105 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000106 void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
107 Visit(GE->getResultExpr());
108 }
Eli Friedman12444a22009-01-27 09:03:41 +0000109 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
John McCall91a57552011-07-15 05:09:51 +0000110 void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
111 return Visit(E->getReplacement());
112 }
Chris Lattner9c033562007-08-21 04:25:47 +0000113
114 // l-values.
John McCallf4b88a42012-03-10 09:33:50 +0000115 void VisitDeclRefExpr(DeclRefExpr *E) {
John McCalldd2ecee2012-03-10 03:05:10 +0000116 // For aggregates, we should always be able to emit the variable
117 // as an l-value unless it's a reference. This is due to the fact
118 // that we can't actually ever see a normal l2r conversion on an
119 // aggregate in C++, and in C there's no language standard
120 // actively preventing us from listing variables in the captures
121 // list of a block.
John McCallf4b88a42012-03-10 09:33:50 +0000122 if (E->getDecl()->getType()->isReferenceType()) {
John McCalldd2ecee2012-03-10 03:05:10 +0000123 if (CodeGenFunction::ConstantEmission result
John McCallf4b88a42012-03-10 09:33:50 +0000124 = CGF.tryEmitAsConstant(E)) {
John McCalle0c11682012-07-02 23:58:38 +0000125 EmitFinalDestCopy(E->getType(), result.getReferenceLValue(CGF, E));
John McCalldd2ecee2012-03-10 03:05:10 +0000126 return;
127 }
128 }
129
John McCallf4b88a42012-03-10 09:33:50 +0000130 EmitAggLoadOfLValue(E);
John McCalldd2ecee2012-03-10 03:05:10 +0000131 }
132
Seo Sanghyeon9b73b392007-12-14 02:04:12 +0000133 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
134 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
Daniel Dunbar5be028f2010-01-04 18:47:06 +0000135 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
Douglas Gregor751ec9b2011-06-17 04:59:12 +0000136 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Seo Sanghyeon9b73b392007-12-14 02:04:12 +0000137 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
138 EmitAggLoadOfLValue(E);
139 }
Chris Lattnerf0a990c2009-04-21 23:00:09 +0000140 void VisitPredefinedExpr(const PredefinedExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000141 EmitAggLoadOfLValue(E);
Chris Lattnerf0a990c2009-04-21 23:00:09 +0000142 }
Mike Stump1eb44332009-09-09 15:08:12 +0000143
Chris Lattner9c033562007-08-21 04:25:47 +0000144 // Operators.
Anders Carlsson4d8673b2009-08-07 23:22:37 +0000145 void VisitCastExpr(CastExpr *E);
Anders Carlsson148fe672007-10-31 22:04:46 +0000146 void VisitCallExpr(const CallExpr *E);
Chris Lattnerb2d963f2007-08-31 22:54:14 +0000147 void VisitStmtExpr(const StmtExpr *E);
Chris Lattner9c033562007-08-21 04:25:47 +0000148 void VisitBinaryOperator(const BinaryOperator *BO);
Fariborz Jahanian8bfd31f2009-10-22 22:57:31 +0000149 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
Chris Lattner03d6fb92007-08-21 04:43:17 +0000150 void VisitBinAssign(const BinaryOperator *E);
Eli Friedman07fa52a2008-05-20 07:56:31 +0000151 void VisitBinComma(const BinaryOperator *E);
Chris Lattner9c033562007-08-21 04:25:47 +0000152
Chris Lattner8fdf3282008-06-24 17:04:18 +0000153 void VisitObjCMessageExpr(ObjCMessageExpr *E);
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000154 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
155 EmitAggLoadOfLValue(E);
156 }
Mike Stump1eb44332009-09-09 15:08:12 +0000157
John McCall56ca35d2011-02-17 10:25:35 +0000158 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
Anders Carlssona294ca82009-07-08 18:33:14 +0000159 void VisitChooseExpr(const ChooseExpr *CE);
Devang Patel636c3d02007-10-26 17:44:44 +0000160 void VisitInitListExpr(InitListExpr *E);
Anders Carlsson30311fa2009-12-16 06:57:54 +0000161 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
Chris Lattner04421082008-04-08 04:40:51 +0000162 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
163 Visit(DAE->getExpr());
164 }
Anders Carlssonb58d0172009-05-30 23:23:33 +0000165 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
Anders Carlsson31ccf372009-05-03 17:47:16 +0000166 void VisitCXXConstructExpr(const CXXConstructExpr *E);
Eli Friedman4c5d8af2012-02-09 03:32:31 +0000167 void VisitLambdaExpr(LambdaExpr *E);
John McCall4765fa02010-12-06 08:20:24 +0000168 void VisitExprWithCleanups(ExprWithCleanups *E);
Douglas Gregored8abf12010-07-08 06:14:04 +0000169 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Mike Stump2710c412009-11-18 00:40:12 +0000170 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
Douglas Gregor03e80032011-06-21 17:03:29 +0000171 void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
John McCalle996ffd2011-02-16 08:02:54 +0000172 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
173
John McCall4b9c2d22011-11-06 09:01:30 +0000174 void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
175 if (E->isGLValue()) {
176 LValue LV = CGF.EmitPseudoObjectLValue(E);
John McCalle0c11682012-07-02 23:58:38 +0000177 return EmitFinalDestCopy(E->getType(), LV);
John McCall4b9c2d22011-11-06 09:01:30 +0000178 }
179
180 CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
181 }
182
Eli Friedmanb1851242008-05-27 15:51:49 +0000183 void VisitVAArgExpr(VAArgExpr *E);
Chris Lattnerf81557c2008-04-04 18:42:16 +0000184
Chad Rosier649b4a12012-03-29 17:37:10 +0000185 void EmitInitializationToLValue(Expr *E, LValue Address);
John McCalla07398e2011-06-16 04:16:24 +0000186 void EmitNullInitializationToLValue(LValue Address);
Chris Lattner9c033562007-08-21 04:25:47 +0000187 // case Expr::ChooseExprClass:
Mike Stump39406b12009-12-09 19:24:08 +0000188 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
Eli Friedman276b0612011-10-11 02:20:01 +0000189 void VisitAtomicExpr(AtomicExpr *E) {
190 CGF.EmitAtomicExpr(E, EnsureSlot(E->getType()).getAddr());
191 }
Chris Lattner9c033562007-08-21 04:25:47 +0000192};
193} // end anonymous namespace.
194
Chris Lattneree755f92007-08-21 04:59:27 +0000195//===----------------------------------------------------------------------===//
196// Utilities
197//===----------------------------------------------------------------------===//
Chris Lattner9c033562007-08-21 04:25:47 +0000198
Chris Lattner883f6a72007-08-11 00:04:45 +0000199/// EmitAggLoadOfLValue - Given an expression with aggregate type that
200/// represents a value lvalue, this method emits the address of the lvalue,
201/// then loads the result into DestPtr.
Chris Lattner9c033562007-08-21 04:25:47 +0000202void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
203 LValue LV = CGF.EmitLValue(E);
John McCalle0c11682012-07-02 23:58:38 +0000204 EmitFinalDestCopy(E->getType(), LV);
Mike Stump4ac20dd2009-05-23 20:28:01 +0000205}
206
John McCallfa037bd2010-05-22 22:13:32 +0000207/// \brief True if the given aggregate type requires special GC API calls.
208bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
209 // Only record types have members that might require garbage collection.
210 const RecordType *RecordTy = T->getAs<RecordType>();
211 if (!RecordTy) return false;
212
213 // Don't mess with non-trivial C++ types.
214 RecordDecl *Record = RecordTy->getDecl();
215 if (isa<CXXRecordDecl>(Record) &&
216 (!cast<CXXRecordDecl>(Record)->hasTrivialCopyConstructor() ||
217 !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
218 return false;
219
220 // Check whether the type has an object member.
221 return Record->hasObjectMember();
222}
223
John McCall410ffb22011-08-25 23:04:34 +0000224/// \brief Perform the final move to DestPtr if for some reason
225/// getReturnValueSlot() didn't use it directly.
John McCallfa037bd2010-05-22 22:13:32 +0000226///
227/// The idea is that you do something like this:
228/// RValue Result = EmitSomething(..., getReturnValueSlot());
John McCall410ffb22011-08-25 23:04:34 +0000229/// EmitMoveFromReturnSlot(E, Result);
230///
231/// If nothing interferes, this will cause the result to be emitted
232/// directly into the return value slot. Otherwise, a final move
233/// will be performed.
John McCalle0c11682012-07-02 23:58:38 +0000234void AggExprEmitter::EmitMoveFromReturnSlot(const Expr *E, RValue src) {
John McCall410ffb22011-08-25 23:04:34 +0000235 if (shouldUseDestForReturnSlot()) {
236 // Logically, Dest.getAddr() should equal Src.getAggregateAddr().
237 // The possibility of undef rvalues complicates that a lot,
238 // though, so we can't really assert.
239 return;
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000240 }
John McCall410ffb22011-08-25 23:04:34 +0000241
John McCalle0c11682012-07-02 23:58:38 +0000242 // Otherwise, copy from there to the destination.
243 assert(Dest.getAddr() != src.getAggregateAddr());
244 std::pair<CharUnits, CharUnits> typeInfo =
Chad Rosier26397ed2012-04-17 01:14:29 +0000245 CGF.getContext().getTypeInfoInChars(E->getType());
John McCalle0c11682012-07-02 23:58:38 +0000246 EmitFinalDestCopy(E->getType(), src, typeInfo.second);
John McCallfa037bd2010-05-22 22:13:32 +0000247}
248
Mike Stump4ac20dd2009-05-23 20:28:01 +0000249/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
John McCalle0c11682012-07-02 23:58:38 +0000250void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src,
251 CharUnits srcAlign) {
252 assert(src.isAggregate() && "value must be aggregate value!");
253 LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddr(), type, srcAlign);
254 EmitFinalDestCopy(type, srcLV);
255}
Mike Stump4ac20dd2009-05-23 20:28:01 +0000256
John McCalle0c11682012-07-02 23:58:38 +0000257/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
258void AggExprEmitter::EmitFinalDestCopy(QualType type, const LValue &src) {
John McCall558d2ab2010-09-15 10:14:12 +0000259 // If Dest is ignored, then we're evaluating an aggregate expression
John McCalle0c11682012-07-02 23:58:38 +0000260 // in a context that doesn't care about the result. Note that loads
261 // from volatile l-values force the existence of a non-ignored
262 // destination.
263 if (Dest.isIgnored())
264 return;
Fariborz Jahanian8a970052010-10-22 22:05:03 +0000265
John McCalle0c11682012-07-02 23:58:38 +0000266 AggValueSlot srcAgg =
267 AggValueSlot::forLValue(src, AggValueSlot::IsDestructed,
268 needsGC(type), AggValueSlot::IsAliased);
269 EmitCopy(type, Dest, srcAgg);
270}
Chris Lattner883f6a72007-08-11 00:04:45 +0000271
John McCalle0c11682012-07-02 23:58:38 +0000272/// Perform a copy from the source into the destination.
273///
274/// \param type - the type of the aggregate being copied; qualifiers are
275/// ignored
276void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,
277 const AggValueSlot &src) {
278 if (dest.requiresGCollection()) {
279 CharUnits sz = CGF.getContext().getTypeSizeInChars(type);
280 llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());
Fariborz Jahanian08c32132009-08-31 19:33:16 +0000281 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
John McCalle0c11682012-07-02 23:58:38 +0000282 dest.getAddr(),
283 src.getAddr(),
284 size);
Fariborz Jahanian08c32132009-08-31 19:33:16 +0000285 return;
286 }
John McCalle0c11682012-07-02 23:58:38 +0000287
Mike Stump4ac20dd2009-05-23 20:28:01 +0000288 // If the result of the assignment is used, copy the LHS there also.
John McCalle0c11682012-07-02 23:58:38 +0000289 // It's volatile if either side is. Use the minimum alignment of
290 // the two sides.
291 CGF.EmitAggregateCopy(dest.getAddr(), src.getAddr(), type,
292 dest.isVolatile() || src.isVolatile(),
293 std::min(dest.getAlignment(), src.getAlignment()));
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 Blaikie581deb32012-06-06 20:45:41 +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 Blaikie581deb32012-06-06 20:45:41 +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 McCalle0c11682012-07-02 23:58:38 +0000529 EmitFinalDestCopy(e->getType(), 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: {
Richard Smith2c9f87c2012-08-24 00:54:33 +0000552 // FIXME: Can this actually happen? We have no test coverage for it.
Douglas Gregor69cfeb12010-05-14 21:31:02 +0000553 assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
Richard Smith2c9f87c2012-08-24 00:54:33 +0000554 LValue LV = CGF.EmitCheckedLValue(E->getSubExpr(),
Richard Smith7ac9ef12012-09-08 02:08:36 +0000555 CodeGenFunction::TCK_Load);
Douglas Gregor69cfeb12010-05-14 21:31:02 +0000556 // FIXME: Do we also need to handle property references here?
557 if (LV.isSimple())
558 CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
559 else
560 CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
561
John McCall558d2ab2010-09-15 10:14:12 +0000562 if (!Dest.isIgnored())
563 CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
Douglas Gregor69cfeb12010-05-14 21:31:02 +0000564 break;
565 }
566
John McCall2de56d12010-08-25 11:45:40 +0000567 case CK_ToUnion: {
John McCall65912712011-04-12 22:02:02 +0000568 if (Dest.isIgnored()) break;
569
Anders Carlsson4d8673b2009-08-07 23:22:37 +0000570 // GCC union extension
Daniel Dunbar79c39282010-08-21 03:15:20 +0000571 QualType Ty = E->getSubExpr()->getType();
572 QualType PtrTy = CGF.getContext().getPointerType(Ty);
John McCall558d2ab2010-09-15 10:14:12 +0000573 llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
Eli Friedman34ebf4d2009-06-03 20:45:06 +0000574 CGF.ConvertType(PtrTy));
John McCalla07398e2011-06-16 04:16:24 +0000575 EmitInitializationToLValue(E->getSubExpr(),
Chad Rosier649b4a12012-03-29 17:37:10 +0000576 CGF.MakeAddrLValue(CastPtr, Ty));
Anders Carlsson30168422009-09-29 01:23:39 +0000577 break;
Nuno Lopes7e916272009-01-15 20:14:33 +0000578 }
Mike Stump1eb44332009-09-09 15:08:12 +0000579
John McCall2de56d12010-08-25 11:45:40 +0000580 case CK_DerivedToBase:
581 case CK_BaseToDerived:
582 case CK_UncheckedDerivedToBase: {
David Blaikieb219cfc2011-09-23 05:06:16 +0000583 llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000584 "should have been unpacked before we got here");
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000585 }
586
John McCalle0c11682012-07-02 23:58:38 +0000587 case CK_LValueToRValue:
588 // If we're loading from a volatile type, force the destination
589 // into existence.
590 if (E->getSubExpr()->getType().isVolatileQualified()) {
591 EnsureDest(E->getType());
592 return Visit(E->getSubExpr());
593 }
594 // fallthrough
595
John McCall2de56d12010-08-25 11:45:40 +0000596 case CK_NoOp:
David Chisnall7a7ee302012-01-16 17:27:18 +0000597 case CK_AtomicToNonAtomic:
598 case CK_NonAtomicToAtomic:
John McCall2de56d12010-08-25 11:45:40 +0000599 case CK_UserDefinedConversion:
600 case CK_ConstructorConversion:
Anders Carlsson30168422009-09-29 01:23:39 +0000601 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
602 E->getType()) &&
603 "Implicit cast types must be compatible");
604 Visit(E->getSubExpr());
605 break;
John McCall0ae287a2010-12-01 04:43:34 +0000606
John McCall2de56d12010-08-25 11:45:40 +0000607 case CK_LValueBitCast:
John McCall0ae287a2010-12-01 04:43:34 +0000608 llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
John McCall1de4d4e2011-04-07 08:22:57 +0000609
John McCall0ae287a2010-12-01 04:43:34 +0000610 case CK_Dependent:
611 case CK_BitCast:
612 case CK_ArrayToPointerDecay:
613 case CK_FunctionToPointerDecay:
614 case CK_NullToPointer:
615 case CK_NullToMemberPointer:
616 case CK_BaseToDerivedMemberPointer:
617 case CK_DerivedToBaseMemberPointer:
618 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +0000619 case CK_ReinterpretMemberPointer:
John McCall0ae287a2010-12-01 04:43:34 +0000620 case CK_IntegralToPointer:
621 case CK_PointerToIntegral:
622 case CK_PointerToBoolean:
623 case CK_ToVoid:
624 case CK_VectorSplat:
625 case CK_IntegralCast:
626 case CK_IntegralToBoolean:
627 case CK_IntegralToFloating:
628 case CK_FloatingToIntegral:
629 case CK_FloatingToBoolean:
630 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +0000631 case CK_CPointerToObjCPointerCast:
632 case CK_BlockPointerToObjCPointerCast:
John McCall0ae287a2010-12-01 04:43:34 +0000633 case CK_AnyPointerToBlockPointerCast:
634 case CK_ObjCObjectLValueCast:
635 case CK_FloatingRealToComplex:
636 case CK_FloatingComplexToReal:
637 case CK_FloatingComplexToBoolean:
638 case CK_FloatingComplexCast:
639 case CK_FloatingComplexToIntegralComplex:
640 case CK_IntegralRealToComplex:
641 case CK_IntegralComplexToReal:
642 case CK_IntegralComplexToBoolean:
643 case CK_IntegralComplexCast:
644 case CK_IntegralComplexToFloatingComplex:
John McCall33e56f32011-09-10 06:18:15 +0000645 case CK_ARCProduceObject:
646 case CK_ARCConsumeObject:
647 case CK_ARCReclaimReturnedObject:
648 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +0000649 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000650 case CK_BuiltinFnToFnPtr:
John McCall0ae287a2010-12-01 04:43:34 +0000651 llvm_unreachable("cast kind invalid for aggregate types");
Anders Carlsson30168422009-09-29 01:23:39 +0000652 }
Anders Carlssone4707ff2008-01-14 06:28:57 +0000653}
654
Chris Lattner96196622008-07-26 22:37:01 +0000655void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
Anders Carlssone70e8f72009-05-27 16:45:02 +0000656 if (E->getCallReturnType()->isReferenceType()) {
657 EmitAggLoadOfLValue(E);
658 return;
659 }
Mike Stump1eb44332009-09-09 15:08:12 +0000660
John McCallfa037bd2010-05-22 22:13:32 +0000661 RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
John McCall410ffb22011-08-25 23:04:34 +0000662 EmitMoveFromReturnSlot(E, RV);
Anders Carlsson148fe672007-10-31 22:04:46 +0000663}
Chris Lattner96196622008-07-26 22:37:01 +0000664
665void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCallfa037bd2010-05-22 22:13:32 +0000666 RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
John McCall410ffb22011-08-25 23:04:34 +0000667 EmitMoveFromReturnSlot(E, RV);
Chris Lattner8fdf3282008-06-24 17:04:18 +0000668}
Anders Carlsson148fe672007-10-31 22:04:46 +0000669
Chris Lattner96196622008-07-26 22:37:01 +0000670void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCall2a416372010-12-05 02:00:02 +0000671 CGF.EmitIgnoredExpr(E->getLHS());
John McCall558d2ab2010-09-15 10:14:12 +0000672 Visit(E->getRHS());
Eli Friedman07fa52a2008-05-20 07:56:31 +0000673}
674
Chris Lattnerb2d963f2007-08-31 22:54:14 +0000675void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCall150b4622011-01-26 04:00:11 +0000676 CodeGenFunction::StmtExprEvaluation eval(CGF);
John McCall558d2ab2010-09-15 10:14:12 +0000677 CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
Chris Lattnerb2d963f2007-08-31 22:54:14 +0000678}
679
Chris Lattner9c033562007-08-21 04:25:47 +0000680void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +0000681 if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
Fariborz Jahanian8bfd31f2009-10-22 22:57:31 +0000682 VisitPointerToDataMemberBinaryOperator(E);
683 else
684 CGF.ErrorUnsupported(E, "aggregate binary expression");
685}
686
687void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
688 const BinaryOperator *E) {
689 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
John McCalle0c11682012-07-02 23:58:38 +0000690 EmitFinalDestCopy(E->getType(), LV);
691}
692
693/// Is the value of the given expression possibly a reference to or
694/// into a __block variable?
695static bool isBlockVarRef(const Expr *E) {
696 // Make sure we look through parens.
697 E = E->IgnoreParens();
698
699 // Check for a direct reference to a __block variable.
700 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
701 const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
702 return (var && var->hasAttr<BlocksAttr>());
703 }
704
705 // More complicated stuff.
706
707 // Binary operators.
708 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {
709 // For an assignment or pointer-to-member operation, just care
710 // about the LHS.
711 if (op->isAssignmentOp() || op->isPtrMemOp())
712 return isBlockVarRef(op->getLHS());
713
714 // For a comma, just care about the RHS.
715 if (op->getOpcode() == BO_Comma)
716 return isBlockVarRef(op->getRHS());
717
718 // FIXME: pointer arithmetic?
719 return false;
720
721 // Check both sides of a conditional operator.
722 } else if (const AbstractConditionalOperator *op
723 = dyn_cast<AbstractConditionalOperator>(E)) {
724 return isBlockVarRef(op->getTrueExpr())
725 || isBlockVarRef(op->getFalseExpr());
726
727 // OVEs are required to support BinaryConditionalOperators.
728 } else if (const OpaqueValueExpr *op
729 = dyn_cast<OpaqueValueExpr>(E)) {
730 if (const Expr *src = op->getSourceExpr())
731 return isBlockVarRef(src);
732
733 // Casts are necessary to get things like (*(int*)&var) = foo().
734 // We don't really care about the kind of cast here, except
735 // we don't want to look through l2r casts, because it's okay
736 // to get the *value* in a __block variable.
737 } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {
738 if (cast->getCastKind() == CK_LValueToRValue)
739 return false;
740 return isBlockVarRef(cast->getSubExpr());
741
742 // Handle unary operators. Again, just aggressively look through
743 // it, ignoring the operation.
744 } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {
745 return isBlockVarRef(uop->getSubExpr());
746
747 // Look into the base of a field access.
748 } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
749 return isBlockVarRef(mem->getBase());
750
751 // Look into the base of a subscript.
752 } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {
753 return isBlockVarRef(sub->getBase());
754 }
755
756 return false;
Chris Lattneree755f92007-08-21 04:59:27 +0000757}
758
Chris Lattner03d6fb92007-08-21 04:43:17 +0000759void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Eli Friedmanff6e2b72008-02-11 01:09:17 +0000760 // For an assignment to work, the value on the right has
761 // to be compatible with the value on the left.
Eli Friedman2dce5f82009-05-28 23:04:00 +0000762 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
763 E->getRHS()->getType())
Eli Friedmanff6e2b72008-02-11 01:09:17 +0000764 && "Invalid assignment");
John McCallcd940a12010-12-06 06:10:02 +0000765
John McCalle0c11682012-07-02 23:58:38 +0000766 // If the LHS might be a __block variable, and the RHS can
767 // potentially cause a block copy, we need to evaluate the RHS first
768 // so that the assignment goes the right place.
769 // This is pretty semantically fragile.
770 if (isBlockVarRef(E->getLHS()) &&
771 E->getRHS()->HasSideEffects(CGF.getContext())) {
772 // Ensure that we have a destination, and evaluate the RHS into that.
773 EnsureDest(E->getRHS()->getType());
774 Visit(E->getRHS());
775
776 // Now emit the LHS and copy into it.
777 LValue LHS = CGF.EmitLValue(E->getLHS());
778
779 EmitCopy(E->getLHS()->getType(),
780 AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
781 needsGC(E->getLHS()->getType()),
782 AggValueSlot::IsAliased),
783 Dest);
784 return;
785 }
Chad Rosier649b4a12012-03-29 17:37:10 +0000786
Chris Lattner9c033562007-08-21 04:25:47 +0000787 LValue LHS = CGF.EmitLValue(E->getLHS());
Chris Lattner883f6a72007-08-11 00:04:45 +0000788
John McCalldb458062011-11-07 03:59:57 +0000789 // Codegen the RHS so that it stores directly into the LHS.
790 AggValueSlot LHSSlot =
791 AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
792 needsGC(E->getLHS()->getType()),
Chad Rosier649b4a12012-03-29 17:37:10 +0000793 AggValueSlot::IsAliased);
John McCalle0c11682012-07-02 23:58:38 +0000794 CGF.EmitAggExpr(E->getRHS(), LHSSlot);
795
796 // Copy into the destination if the assignment isn't ignored.
797 EmitFinalDestCopy(E->getType(), LHS);
Chris Lattner883f6a72007-08-11 00:04:45 +0000798}
799
John McCall56ca35d2011-02-17 10:25:35 +0000800void AggExprEmitter::
801VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000802 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
803 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
804 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Mike Stump1eb44332009-09-09 15:08:12 +0000805
John McCall56ca35d2011-02-17 10:25:35 +0000806 // Bind the common expression if necessary.
Eli Friedmand97927d2012-01-06 20:42:20 +0000807 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
John McCall56ca35d2011-02-17 10:25:35 +0000808
John McCall150b4622011-01-26 04:00:11 +0000809 CodeGenFunction::ConditionalEvaluation eval(CGF);
Eli Friedman8e274bd2009-12-25 06:17:05 +0000810 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000811
John McCall74fb0ed2010-11-17 00:07:33 +0000812 // Save whether the destination's lifetime is externally managed.
John McCallfd71fb82011-08-26 08:02:37 +0000813 bool isExternallyDestructed = Dest.isExternallyDestructed();
Chris Lattner883f6a72007-08-11 00:04:45 +0000814
John McCall150b4622011-01-26 04:00:11 +0000815 eval.begin(CGF);
816 CGF.EmitBlock(LHSBlock);
John McCall56ca35d2011-02-17 10:25:35 +0000817 Visit(E->getTrueExpr());
John McCall150b4622011-01-26 04:00:11 +0000818 eval.end(CGF);
Mike Stump1eb44332009-09-09 15:08:12 +0000819
John McCall150b4622011-01-26 04:00:11 +0000820 assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
821 CGF.Builder.CreateBr(ContBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000822
John McCall74fb0ed2010-11-17 00:07:33 +0000823 // If the result of an agg expression is unused, then the emission
824 // of the LHS might need to create a destination slot. That's fine
825 // with us, and we can safely emit the RHS into the same slot, but
John McCallfd71fb82011-08-26 08:02:37 +0000826 // we shouldn't claim that it's already being destructed.
827 Dest.setExternallyDestructed(isExternallyDestructed);
John McCall74fb0ed2010-11-17 00:07:33 +0000828
John McCall150b4622011-01-26 04:00:11 +0000829 eval.begin(CGF);
830 CGF.EmitBlock(RHSBlock);
John McCall56ca35d2011-02-17 10:25:35 +0000831 Visit(E->getFalseExpr());
John McCall150b4622011-01-26 04:00:11 +0000832 eval.end(CGF);
Mike Stump1eb44332009-09-09 15:08:12 +0000833
Chris Lattner9c033562007-08-21 04:25:47 +0000834 CGF.EmitBlock(ContBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000835}
Chris Lattneree755f92007-08-21 04:59:27 +0000836
Anders Carlssona294ca82009-07-08 18:33:14 +0000837void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
838 Visit(CE->getChosenSubExpr(CGF.getContext()));
839}
840
Eli Friedmanb1851242008-05-27 15:51:49 +0000841void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Daniel Dunbar07855702009-02-11 22:25:55 +0000842 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000843 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
844
Sebastian Redl0262f022009-01-09 21:09:38 +0000845 if (!ArgPtr) {
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000846 CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
Sebastian Redl0262f022009-01-09 21:09:38 +0000847 return;
848 }
849
John McCalle0c11682012-07-02 23:58:38 +0000850 EmitFinalDestCopy(VE->getType(), CGF.MakeAddrLValue(ArgPtr, VE->getType()));
Eli Friedmanb1851242008-05-27 15:51:49 +0000851}
852
Anders Carlssonb58d0172009-05-30 23:23:33 +0000853void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
John McCall558d2ab2010-09-15 10:14:12 +0000854 // Ensure that we have a slot, but if we already do, remember
John McCallfd71fb82011-08-26 08:02:37 +0000855 // whether it was externally destructed.
856 bool wasExternallyDestructed = Dest.isExternallyDestructed();
John McCalle0c11682012-07-02 23:58:38 +0000857 EnsureDest(E->getType());
John McCallfd71fb82011-08-26 08:02:37 +0000858
859 // We're going to push a destructor if there isn't already one.
860 Dest.setExternallyDestructed();
Mike Stump1eb44332009-09-09 15:08:12 +0000861
John McCall558d2ab2010-09-15 10:14:12 +0000862 Visit(E->getSubExpr());
Anders Carlssonb58d0172009-05-30 23:23:33 +0000863
John McCallfd71fb82011-08-26 08:02:37 +0000864 // Push that destructor we promised.
865 if (!wasExternallyDestructed)
Peter Collingbourne86811602011-11-27 22:09:22 +0000866 CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddr());
Anders Carlssonb58d0172009-05-30 23:23:33 +0000867}
868
Anders Carlssonb14095a2009-04-17 00:06:03 +0000869void
Anders Carlsson31ccf372009-05-03 17:47:16 +0000870AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
John McCall558d2ab2010-09-15 10:14:12 +0000871 AggValueSlot Slot = EnsureSlot(E->getType());
872 CGF.EmitCXXConstructExpr(E, Slot);
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000873}
874
Eli Friedman4c5d8af2012-02-09 03:32:31 +0000875void
876AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
877 AggValueSlot Slot = EnsureSlot(E->getType());
878 CGF.EmitLambdaExpr(E, Slot);
879}
880
John McCall4765fa02010-12-06 08:20:24 +0000881void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
John McCall1a343eb2011-11-10 08:15:53 +0000882 CGF.enterFullExpression(E);
883 CodeGenFunction::RunCleanupsScope cleanups(CGF);
884 Visit(E->getSubExpr());
Anders Carlssonb14095a2009-04-17 00:06:03 +0000885}
886
Douglas Gregored8abf12010-07-08 06:14:04 +0000887void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
John McCall558d2ab2010-09-15 10:14:12 +0000888 QualType T = E->getType();
889 AggValueSlot Slot = EnsureSlot(T);
John McCalla07398e2011-06-16 04:16:24 +0000890 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
Anders Carlsson30311fa2009-12-16 06:57:54 +0000891}
892
893void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
John McCall558d2ab2010-09-15 10:14:12 +0000894 QualType T = E->getType();
895 AggValueSlot Slot = EnsureSlot(T);
John McCalla07398e2011-06-16 04:16:24 +0000896 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
Nuno Lopes329763b2009-10-18 15:18:11 +0000897}
898
Chris Lattner1b726772010-12-02 07:07:26 +0000899/// isSimpleZero - If emitting this value will obviously just cause a store of
900/// zero to memory, return true. This can return false if uncertain, so it just
901/// handles simple cases.
902static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
Peter Collingbournef111d932011-04-15 00:35:48 +0000903 E = E->IgnoreParens();
904
Chris Lattner1b726772010-12-02 07:07:26 +0000905 // 0
906 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
907 return IL->getValue() == 0;
908 // +0.0
909 if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
910 return FL->getValue().isPosZero();
911 // int()
912 if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
913 CGF.getTypes().isZeroInitializable(E->getType()))
914 return true;
915 // (int*)0 - Null pointer expressions.
916 if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
917 return ICE->getCastKind() == CK_NullToPointer;
918 // '\0'
919 if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
920 return CL->getValue() == 0;
921
922 // Otherwise, hard case: conservatively return false.
923 return false;
924}
925
926
Anders Carlsson78e83f82010-02-03 17:33:16 +0000927void
Chad Rosier649b4a12012-03-29 17:37:10 +0000928AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) {
John McCalla07398e2011-06-16 04:16:24 +0000929 QualType type = LV.getType();
Mike Stump7f79f9b2009-05-29 15:46:01 +0000930 // FIXME: Ignore result?
Chris Lattnerf81557c2008-04-04 18:42:16 +0000931 // FIXME: Are initializers affected by volatile?
Chris Lattner1b726772010-12-02 07:07:26 +0000932 if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
933 // Storing "i32 0" to a zero'd memory location is a noop.
934 } else if (isa<ImplicitValueInitExpr>(E)) {
John McCalla07398e2011-06-16 04:16:24 +0000935 EmitNullInitializationToLValue(LV);
936 } else if (type->isReferenceType()) {
Anders Carlsson32f36ba2010-06-26 16:35:32 +0000937 RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
John McCall545d9962011-06-25 02:11:03 +0000938 CGF.EmitStoreThroughLValue(RV, LV);
John McCalla07398e2011-06-16 04:16:24 +0000939 } else if (type->isAnyComplexType()) {
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000940 CGF.EmitComplexExprIntoAddr(E, LV.getAddress(), false);
John McCalla07398e2011-06-16 04:16:24 +0000941 } else if (CGF.hasAggregateLLVMType(type)) {
John McCall7c2349b2011-08-25 20:40:09 +0000942 CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV,
943 AggValueSlot::IsDestructed,
944 AggValueSlot::DoesNotNeedGCBarriers,
John McCall410ffb22011-08-25 23:04:34 +0000945 AggValueSlot::IsNotAliased,
John McCalla07398e2011-06-16 04:16:24 +0000946 Dest.isZeroed()));
John McCallf85e1932011-06-15 23:02:42 +0000947 } else if (LV.isSimple()) {
John McCalla07398e2011-06-16 04:16:24 +0000948 CGF.EmitScalarInit(E, /*D=*/0, LV, /*Captured=*/false);
Eli Friedmanc8ba9612008-05-12 15:06:05 +0000949 } else {
John McCall545d9962011-06-25 02:11:03 +0000950 CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
Chris Lattnerf81557c2008-04-04 18:42:16 +0000951 }
Chris Lattnerf81557c2008-04-04 18:42:16 +0000952}
953
John McCalla07398e2011-06-16 04:16:24 +0000954void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
955 QualType type = lv.getType();
956
Chris Lattner1b726772010-12-02 07:07:26 +0000957 // If the destination slot is already zeroed out before the aggregate is
958 // copied into it, we don't have to emit any zeros here.
John McCalla07398e2011-06-16 04:16:24 +0000959 if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
Chris Lattner1b726772010-12-02 07:07:26 +0000960 return;
961
John McCalla07398e2011-06-16 04:16:24 +0000962 if (!CGF.hasAggregateLLVMType(type)) {
Eli Friedmanb1e3f322012-02-22 05:38:59 +0000963 // For non-aggregates, we can store zero.
John McCalla07398e2011-06-16 04:16:24 +0000964 llvm::Value *null = llvm::Constant::getNullValue(CGF.ConvertType(type));
Eli Friedmanb1e3f322012-02-22 05:38:59 +0000965 // Note that the following is not equivalent to
966 // EmitStoreThroughBitfieldLValue for ARC types.
Eli Friedman5a13d4d2012-02-24 23:53:49 +0000967 if (lv.isBitField()) {
Eli Friedmanb1e3f322012-02-22 05:38:59 +0000968 CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
Eli Friedman5a13d4d2012-02-24 23:53:49 +0000969 } else {
970 assert(lv.isSimple());
971 CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
972 }
Lauro Ramos Venancio145cd892008-02-19 19:27:31 +0000973 } else {
Chris Lattnerf81557c2008-04-04 18:42:16 +0000974 // There's a potential optimization opportunity in combining
975 // memsets; that would be easy for arrays, but relatively
976 // difficult for structures with the current code.
John McCalla07398e2011-06-16 04:16:24 +0000977 CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
Chris Lattnerf81557c2008-04-04 18:42:16 +0000978 }
979}
980
Chris Lattnerf81557c2008-04-04 18:42:16 +0000981void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
Eli Friedmana385b3c2008-12-02 01:17:45 +0000982#if 0
Eli Friedman13a5be12009-12-04 01:30:56 +0000983 // FIXME: Assess perf here? Figure out what cases are worth optimizing here
984 // (Length of globals? Chunks of zeroed-out space?).
Eli Friedmana385b3c2008-12-02 01:17:45 +0000985 //
Mike Stumpf5408fe2009-05-16 07:57:57 +0000986 // If we can, prefer a copy from a global; this is a lot less code for long
987 // globals, and it's easier for the current optimizers to analyze.
Eli Friedman13a5be12009-12-04 01:30:56 +0000988 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
Eli Friedman994ffef2008-11-30 02:11:09 +0000989 llvm::GlobalVariable* GV =
Eli Friedman13a5be12009-12-04 01:30:56 +0000990 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
991 llvm::GlobalValue::InternalLinkage, C, "");
John McCalle0c11682012-07-02 23:58:38 +0000992 EmitFinalDestCopy(E->getType(), CGF.MakeAddrLValue(GV, E->getType()));
Eli Friedman994ffef2008-11-30 02:11:09 +0000993 return;
994 }
Eli Friedmana385b3c2008-12-02 01:17:45 +0000995#endif
Chris Lattnerd0db03a2010-09-06 00:11:41 +0000996 if (E->hadArrayRangeDesignator())
Douglas Gregora9c87802009-01-29 19:42:23 +0000997 CGF.ErrorUnsupported(E, "GNU array range designator extension");
Douglas Gregora9c87802009-01-29 19:42:23 +0000998
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000999 if (E->initializesStdInitializerList()) {
Sebastian Redlaf130fd2012-02-19 12:28:02 +00001000 EmitStdInitializerList(Dest.getAddr(), E);
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001001 return;
1002 }
1003
Eli Friedman377ecc72012-04-16 03:54:45 +00001004 AggValueSlot Dest = EnsureSlot(E->getType());
1005 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddr(), E->getType(),
1006 Dest.getAlignment());
John McCall558d2ab2010-09-15 10:14:12 +00001007
Chris Lattnerf81557c2008-04-04 18:42:16 +00001008 // Handle initialization of an array.
1009 if (E->getType()->isArrayType()) {
Richard Smithfe587202012-04-15 02:50:59 +00001010 if (E->isStringLiteralInit())
1011 return Visit(E->getInit(0));
Eli Friedman922696f2008-05-19 17:51:16 +00001012
Eli Friedman5c89c392012-02-23 02:25:10 +00001013 QualType elementType =
1014 CGF.getContext().getAsArrayType(E->getType())->getElementType();
Argyrios Kyrtzidis3b4d4902011-04-28 18:53:58 +00001015
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001016 llvm::PointerType *APType =
Eli Friedman377ecc72012-04-16 03:54:45 +00001017 cast<llvm::PointerType>(Dest.getAddr()->getType());
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001018 llvm::ArrayType *AType =
1019 cast<llvm::ArrayType>(APType->getElementType());
Chris Lattner1b726772010-12-02 07:07:26 +00001020
Eli Friedman377ecc72012-04-16 03:54:45 +00001021 EmitArrayInit(Dest.getAddr(), AType, elementType, E);
Chris Lattnerf81557c2008-04-04 18:42:16 +00001022 return;
1023 }
Mike Stump1eb44332009-09-09 15:08:12 +00001024
Chris Lattnerf81557c2008-04-04 18:42:16 +00001025 assert(E->getType()->isRecordType() && "Only support structs/unions here!");
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Chris Lattnerf81557c2008-04-04 18:42:16 +00001027 // Do struct initialization; this code just sets each individual member
1028 // to the approprate value. This makes bitfield support automatic;
1029 // the disadvantage is that the generated code is more difficult for
1030 // the optimizer, especially with bitfields.
1031 unsigned NumInitElements = E->getNumInits();
John McCall2b30dcf2011-07-11 19:35:02 +00001032 RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
Chris Lattnerbd7de382010-09-06 00:13:11 +00001033
John McCall2b30dcf2011-07-11 19:35:02 +00001034 if (record->isUnion()) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001035 // Only initialize one field of a union. The field itself is
1036 // specified by the initializer list.
1037 if (!E->getInitializedFieldInUnion()) {
1038 // Empty union; we have nothing to do.
Mike Stump1eb44332009-09-09 15:08:12 +00001039
Douglas Gregor0bb76892009-01-29 16:53:55 +00001040#ifndef NDEBUG
1041 // Make sure that it's really an empty and not a failure of
1042 // semantic analysis.
John McCall2b30dcf2011-07-11 19:35:02 +00001043 for (RecordDecl::field_iterator Field = record->field_begin(),
1044 FieldEnd = record->field_end();
Douglas Gregor0bb76892009-01-29 16:53:55 +00001045 Field != FieldEnd; ++Field)
1046 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
1047#endif
1048 return;
1049 }
1050
1051 // FIXME: volatility
1052 FieldDecl *Field = E->getInitializedFieldInUnion();
Douglas Gregor0bb76892009-01-29 16:53:55 +00001053
Eli Friedman377ecc72012-04-16 03:54:45 +00001054 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001055 if (NumInitElements) {
1056 // Store the initializer into the field
Chad Rosier649b4a12012-03-29 17:37:10 +00001057 EmitInitializationToLValue(E->getInit(0), FieldLoc);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001058 } else {
Chris Lattner1b726772010-12-02 07:07:26 +00001059 // Default-initialize to null.
John McCalla07398e2011-06-16 04:16:24 +00001060 EmitNullInitializationToLValue(FieldLoc);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001061 }
1062
1063 return;
1064 }
Mike Stump1eb44332009-09-09 15:08:12 +00001065
John McCall2b30dcf2011-07-11 19:35:02 +00001066 // We'll need to enter cleanup scopes in case any of the member
1067 // initializers throw an exception.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001068 SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
John McCall6f103ba2011-11-10 10:43:54 +00001069 llvm::Instruction *cleanupDominator = 0;
John McCall2b30dcf2011-07-11 19:35:02 +00001070
Chris Lattnerf81557c2008-04-04 18:42:16 +00001071 // Here we iterate over the fields; this makes it simpler to both
1072 // default-initialize fields and skip over unnamed fields.
John McCall2b30dcf2011-07-11 19:35:02 +00001073 unsigned curInitIndex = 0;
1074 for (RecordDecl::field_iterator field = record->field_begin(),
1075 fieldEnd = record->field_end();
1076 field != fieldEnd; ++field) {
1077 // We're done once we hit the flexible array member.
1078 if (field->getType()->isIncompleteArrayType())
Douglas Gregor44b43212008-12-11 16:49:14 +00001079 break;
1080
John McCall2b30dcf2011-07-11 19:35:02 +00001081 // Always skip anonymous bitfields.
1082 if (field->isUnnamedBitfield())
Chris Lattnerf81557c2008-04-04 18:42:16 +00001083 continue;
Douglas Gregor34e79462009-01-28 23:36:17 +00001084
John McCall2b30dcf2011-07-11 19:35:02 +00001085 // We're done if we reach the end of the explicit initializers, we
1086 // have a zeroed object, and the rest of the fields are
1087 // zero-initializable.
1088 if (curInitIndex == NumInitElements && Dest.isZeroed() &&
Chris Lattner1b726772010-12-02 07:07:26 +00001089 CGF.getTypes().isZeroInitializable(E->getType()))
1090 break;
1091
Eli Friedman377ecc72012-04-16 03:54:45 +00001092
David Blaikie581deb32012-06-06 20:45:41 +00001093 LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, *field);
Fariborz Jahanian14674ff2009-05-27 19:54:11 +00001094 // We never generate write-barries for initialized fields.
John McCall2b30dcf2011-07-11 19:35:02 +00001095 LV.setNonGC(true);
Chris Lattner1b726772010-12-02 07:07:26 +00001096
John McCall2b30dcf2011-07-11 19:35:02 +00001097 if (curInitIndex < NumInitElements) {
Chris Lattnerb35baae2010-03-08 21:08:07 +00001098 // Store the initializer into the field.
Chad Rosier649b4a12012-03-29 17:37:10 +00001099 EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
Chris Lattnerf81557c2008-04-04 18:42:16 +00001100 } else {
1101 // We're out of initalizers; default-initialize to null
John McCall2b30dcf2011-07-11 19:35:02 +00001102 EmitNullInitializationToLValue(LV);
1103 }
1104
1105 // Push a destructor if necessary.
1106 // FIXME: if we have an array of structures, all explicitly
1107 // initialized, we can end up pushing a linear number of cleanups.
1108 bool pushedCleanup = false;
1109 if (QualType::DestructionKind dtorKind
1110 = field->getType().isDestructedType()) {
1111 assert(LV.isSimple());
1112 if (CGF.needsEHCleanup(dtorKind)) {
John McCall6f103ba2011-11-10 10:43:54 +00001113 if (!cleanupDominator)
1114 cleanupDominator = CGF.Builder.CreateUnreachable(); // placeholder
1115
John McCall2b30dcf2011-07-11 19:35:02 +00001116 CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
1117 CGF.getDestroyer(dtorKind), false);
1118 cleanups.push_back(CGF.EHStack.stable_begin());
1119 pushedCleanup = true;
1120 }
Chris Lattnerf81557c2008-04-04 18:42:16 +00001121 }
Chris Lattner1b726772010-12-02 07:07:26 +00001122
1123 // If the GEP didn't get used because of a dead zero init or something
1124 // else, clean it up for -O0 builds and general tidiness.
John McCall2b30dcf2011-07-11 19:35:02 +00001125 if (!pushedCleanup && LV.isSimple())
Chris Lattner1b726772010-12-02 07:07:26 +00001126 if (llvm::GetElementPtrInst *GEP =
John McCall2b30dcf2011-07-11 19:35:02 +00001127 dyn_cast<llvm::GetElementPtrInst>(LV.getAddress()))
Chris Lattner1b726772010-12-02 07:07:26 +00001128 if (GEP->use_empty())
1129 GEP->eraseFromParent();
Lauro Ramos Venancio145cd892008-02-19 19:27:31 +00001130 }
John McCall2b30dcf2011-07-11 19:35:02 +00001131
1132 // Deactivate all the partial cleanups in reverse order, which
1133 // generally means popping them.
1134 for (unsigned i = cleanups.size(); i != 0; --i)
John McCall6f103ba2011-11-10 10:43:54 +00001135 CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
1136
1137 // Destroy the placeholder if we made one.
1138 if (cleanupDominator)
1139 cleanupDominator->eraseFromParent();
Devang Patel636c3d02007-10-26 17:44:44 +00001140}
1141
Chris Lattneree755f92007-08-21 04:59:27 +00001142//===----------------------------------------------------------------------===//
1143// Entry Points into this File
1144//===----------------------------------------------------------------------===//
1145
Chris Lattner1b726772010-12-02 07:07:26 +00001146/// GetNumNonZeroBytesInInit - Get an approximate count of the number of
1147/// non-zero bytes that will be stored when outputting the initializer for the
1148/// specified initializer expression.
Ken Dyck02c45332011-04-24 17:17:56 +00001149static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
Peter Collingbournef111d932011-04-15 00:35:48 +00001150 E = E->IgnoreParens();
Chris Lattner1b726772010-12-02 07:07:26 +00001151
1152 // 0 and 0.0 won't require any non-zero stores!
Ken Dyck02c45332011-04-24 17:17:56 +00001153 if (isSimpleZero(E, CGF)) return CharUnits::Zero();
Chris Lattner1b726772010-12-02 07:07:26 +00001154
1155 // If this is an initlist expr, sum up the size of sizes of the (present)
1156 // elements. If this is something weird, assume the whole thing is non-zero.
1157 const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
1158 if (ILE == 0 || !CGF.getTypes().isZeroInitializable(ILE->getType()))
Ken Dyck02c45332011-04-24 17:17:56 +00001159 return CGF.getContext().getTypeSizeInChars(E->getType());
Chris Lattner1b726772010-12-02 07:07:26 +00001160
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001161 // InitListExprs for structs have to be handled carefully. If there are
1162 // reference members, we need to consider the size of the reference, not the
1163 // referencee. InitListExprs for unions and arrays can't have references.
Chris Lattner8c00ad12010-12-02 22:52:04 +00001164 if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
1165 if (!RT->isUnionType()) {
1166 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
Ken Dyck02c45332011-04-24 17:17:56 +00001167 CharUnits NumNonZeroBytes = CharUnits::Zero();
Chris Lattner8c00ad12010-12-02 22:52:04 +00001168
1169 unsigned ILEElement = 0;
1170 for (RecordDecl::field_iterator Field = SD->field_begin(),
1171 FieldEnd = SD->field_end(); Field != FieldEnd; ++Field) {
1172 // We're done once we hit the flexible array member or run out of
1173 // InitListExpr elements.
1174 if (Field->getType()->isIncompleteArrayType() ||
1175 ILEElement == ILE->getNumInits())
1176 break;
1177 if (Field->isUnnamedBitfield())
1178 continue;
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001179
Chris Lattner8c00ad12010-12-02 22:52:04 +00001180 const Expr *E = ILE->getInit(ILEElement++);
1181
1182 // Reference values are always non-null and have the width of a pointer.
1183 if (Field->getType()->isReferenceType())
Ken Dyck02c45332011-04-24 17:17:56 +00001184 NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001185 CGF.getContext().getTargetInfo().getPointerWidth(0));
Chris Lattner8c00ad12010-12-02 22:52:04 +00001186 else
1187 NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
1188 }
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001189
Chris Lattner8c00ad12010-12-02 22:52:04 +00001190 return NumNonZeroBytes;
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001191 }
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001192 }
1193
1194
Ken Dyck02c45332011-04-24 17:17:56 +00001195 CharUnits NumNonZeroBytes = CharUnits::Zero();
Chris Lattner1b726772010-12-02 07:07:26 +00001196 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1197 NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
1198 return NumNonZeroBytes;
1199}
1200
1201/// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
1202/// zeros in it, emit a memset and avoid storing the individual zeros.
1203///
1204static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
1205 CodeGenFunction &CGF) {
1206 // If the slot is already known to be zeroed, nothing to do. Don't mess with
1207 // volatile stores.
1208 if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == 0) return;
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +00001209
1210 // C++ objects with a user-declared constructor don't need zero'ing.
David Blaikie4e4d0842012-03-11 07:00:24 +00001211 if (CGF.getContext().getLangOpts().CPlusPlus)
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +00001212 if (const RecordType *RT = CGF.getContext()
1213 .getBaseElementType(E->getType())->getAs<RecordType>()) {
1214 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1215 if (RD->hasUserDeclaredConstructor())
1216 return;
1217 }
1218
Chris Lattner1b726772010-12-02 07:07:26 +00001219 // If the type is 16-bytes or smaller, prefer individual stores over memset.
Ken Dyck5ff1a352011-04-24 17:25:32 +00001220 std::pair<CharUnits, CharUnits> TypeInfo =
1221 CGF.getContext().getTypeInfoInChars(E->getType());
1222 if (TypeInfo.first <= CharUnits::fromQuantity(16))
Chris Lattner1b726772010-12-02 07:07:26 +00001223 return;
1224
1225 // Check to see if over 3/4 of the initializer are known to be zero. If so,
1226 // we prefer to emit memset + individual stores for the rest.
Ken Dyck5ff1a352011-04-24 17:25:32 +00001227 CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
1228 if (NumNonZeroBytes*4 > TypeInfo.first)
Chris Lattner1b726772010-12-02 07:07:26 +00001229 return;
1230
1231 // Okay, it seems like a good idea to use an initial memset, emit the call.
Ken Dyck5ff1a352011-04-24 17:25:32 +00001232 llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first.getQuantity());
1233 CharUnits Align = TypeInfo.second;
Chris Lattner1b726772010-12-02 07:07:26 +00001234
1235 llvm::Value *Loc = Slot.getAddr();
Chris Lattner1b726772010-12-02 07:07:26 +00001236
Chris Lattner8b418682012-02-07 00:39:47 +00001237 Loc = CGF.Builder.CreateBitCast(Loc, CGF.Int8PtrTy);
Ken Dyck5ff1a352011-04-24 17:25:32 +00001238 CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal,
1239 Align.getQuantity(), false);
Chris Lattner1b726772010-12-02 07:07:26 +00001240
1241 // Tell the AggExprEmitter that the slot is known zero.
1242 Slot.setZeroed();
1243}
1244
1245
1246
1247
Mike Stumpe1129a92009-05-26 18:57:45 +00001248/// EmitAggExpr - Emit the computation of the specified expression of aggregate
1249/// type. The result is computed into DestPtr. Note that if DestPtr is null,
1250/// the value of the aggregate expression is not needed. If VolatileDest is
1251/// true, DestPtr cannot be 0.
John McCalle0c11682012-07-02 23:58:38 +00001252void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) {
Chris Lattneree755f92007-08-21 04:59:27 +00001253 assert(E && hasAggregateLLVMType(E->getType()) &&
1254 "Invalid aggregate expression to emit");
Chris Lattner1b726772010-12-02 07:07:26 +00001255 assert((Slot.getAddr() != 0 || Slot.isIgnored()) &&
1256 "slot has bits but no address");
Mike Stump1eb44332009-09-09 15:08:12 +00001257
Chris Lattner1b726772010-12-02 07:07:26 +00001258 // Optimize the slot if possible.
1259 CheckAggExprForMemSetUse(Slot, E, *this);
1260
John McCalle0c11682012-07-02 23:58:38 +00001261 AggExprEmitter(*this, Slot).Visit(const_cast<Expr*>(E));
Chris Lattneree755f92007-08-21 04:59:27 +00001262}
Daniel Dunbar7482d122008-09-09 20:49:46 +00001263
Daniel Dunbar18aba0d2010-02-05 19:38:31 +00001264LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
1265 assert(hasAggregateLLVMType(E->getType()) && "Invalid argument!");
Daniel Dunbar195337d2010-02-09 02:48:28 +00001266 llvm::Value *Temp = CreateMemTemp(E->getType());
Daniel Dunbar79c39282010-08-21 03:15:20 +00001267 LValue LV = MakeAddrLValue(Temp, E->getType());
John McCall7c2349b2011-08-25 20:40:09 +00001268 EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,
John McCall44184392011-08-26 07:31:35 +00001269 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001270 AggValueSlot::IsNotAliased));
Daniel Dunbar79c39282010-08-21 03:15:20 +00001271 return LV;
Daniel Dunbar18aba0d2010-02-05 19:38:31 +00001272}
1273
Chad Rosier649b4a12012-03-29 17:37:10 +00001274void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
1275 llvm::Value *SrcPtr, QualType Ty,
John McCalle0c11682012-07-02 23:58:38 +00001276 bool isVolatile,
1277 CharUnits alignment) {
Chad Rosier649b4a12012-03-29 17:37:10 +00001278 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
Mike Stump1eb44332009-09-09 15:08:12 +00001279
David Blaikie4e4d0842012-03-11 07:00:24 +00001280 if (getContext().getLangOpts().CPlusPlus) {
Chad Rosier649b4a12012-03-29 17:37:10 +00001281 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1282 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
1283 assert((Record->hasTrivialCopyConstructor() ||
1284 Record->hasTrivialCopyAssignment() ||
1285 Record->hasTrivialMoveConstructor() ||
1286 Record->hasTrivialMoveAssignment()) &&
Douglas Gregore9979482010-05-20 15:39:01 +00001287 "Trying to aggregate-copy a type without a trivial copy "
1288 "constructor or assignment operator");
Chad Rosier649b4a12012-03-29 17:37:10 +00001289 // Ignore empty classes in C++.
1290 if (Record->isEmpty())
Anders Carlsson0d7c5832010-05-03 01:20:20 +00001291 return;
1292 }
1293 }
1294
Chris Lattner83c96292009-02-28 18:31:01 +00001295 // Aggregate assignment turns into llvm.memcpy. This is almost valid per
Chris Lattnerca4fc2c2009-02-28 18:18:58 +00001296 // C99 6.5.16.1p3, which states "If the value being stored in an object is
1297 // read from another object that overlaps in anyway the storage of the first
1298 // object, then the overlap shall be exact and the two objects shall have
1299 // qualified or unqualified versions of a compatible type."
1300 //
Chris Lattner83c96292009-02-28 18:31:01 +00001301 // memcpy is not defined if the source and destination pointers are exactly
Chris Lattnerca4fc2c2009-02-28 18:18:58 +00001302 // equal, but other compilers do this optimization, and almost every memcpy
1303 // implementation handles this case safely. If there is a libc that does not
1304 // safely handle this, we can add a target hook.
Chad Rosier649b4a12012-03-29 17:37:10 +00001305
John McCall929bbfb2012-08-21 04:10:00 +00001306 // Get data size and alignment info for this aggregate.
Chad Rosier649b4a12012-03-29 17:37:10 +00001307 std::pair<CharUnits, CharUnits> TypeInfo =
John McCall929bbfb2012-08-21 04:10:00 +00001308 getContext().getTypeInfoDataSizeInChars(Ty);
Chad Rosier649b4a12012-03-29 17:37:10 +00001309
John McCalle0c11682012-07-02 23:58:38 +00001310 if (alignment.isZero())
1311 alignment = TypeInfo.second;
Chad Rosier649b4a12012-03-29 17:37:10 +00001312
1313 // FIXME: Handle variable sized types.
1314
1315 // FIXME: If we have a volatile struct, the optimizer can remove what might
1316 // appear to be `extra' memory ops:
1317 //
1318 // volatile struct { int i; } a, b;
1319 //
1320 // int main() {
1321 // a = b;
1322 // a = b;
1323 // }
1324 //
1325 // we need to use a different call here. We use isVolatile to indicate when
1326 // either the source or the destination is volatile.
1327
1328 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
1329 llvm::Type *DBP =
1330 llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace());
1331 DestPtr = Builder.CreateBitCast(DestPtr, DBP);
1332
1333 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
1334 llvm::Type *SBP =
1335 llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace());
1336 SrcPtr = Builder.CreateBitCast(SrcPtr, SBP);
1337
1338 // Don't do any of the memmove_collectable tests if GC isn't set.
1339 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
1340 // fall through
1341 } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1342 RecordDecl *Record = RecordTy->getDecl();
1343 if (Record->hasObjectMember()) {
1344 CharUnits size = TypeInfo.first;
1345 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1346 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
1347 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1348 SizeVal);
1349 return;
1350 }
1351 } else if (Ty->isArrayType()) {
1352 QualType BaseType = getContext().getBaseElementType(Ty);
1353 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
1354 if (RecordTy->getDecl()->hasObjectMember()) {
1355 CharUnits size = TypeInfo.first;
1356 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1357 llvm::Value *SizeVal =
1358 llvm::ConstantInt::get(SizeTy, size.getQuantity());
1359 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1360 SizeVal);
1361 return;
1362 }
1363 }
1364 }
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00001365
Chad Rosier649b4a12012-03-29 17:37:10 +00001366 Builder.CreateMemCpy(DestPtr, SrcPtr,
1367 llvm::ConstantInt::get(IntPtrTy,
1368 TypeInfo.first.getQuantity()),
John McCalle0c11682012-07-02 23:58:38 +00001369 alignment.getQuantity(), isVolatile);
Daniel Dunbar7482d122008-09-09 20:49:46 +00001370}
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001371
Sebastian Redl972edf02012-02-19 16:03:09 +00001372void CodeGenFunction::MaybeEmitStdInitializerListCleanup(llvm::Value *loc,
1373 const Expr *init) {
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001374 const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(init);
Sebastian Redl972edf02012-02-19 16:03:09 +00001375 if (cleanups)
1376 init = cleanups->getSubExpr();
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001377
1378 if (isa<InitListExpr>(init) &&
1379 cast<InitListExpr>(init)->initializesStdInitializerList()) {
1380 // We initialized this std::initializer_list with an initializer list.
1381 // A backing array was created. Push a cleanup for it.
Sebastian Redl972edf02012-02-19 16:03:09 +00001382 EmitStdInitializerListCleanup(loc, cast<InitListExpr>(init));
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001383 }
1384}
1385
Sebastian Redlaf130fd2012-02-19 12:28:02 +00001386static void EmitRecursiveStdInitializerListCleanup(CodeGenFunction &CGF,
1387 llvm::Value *arrayStart,
1388 const InitListExpr *init) {
1389 // Check if there are any recursive cleanups to do, i.e. if we have
1390 // std::initializer_list<std::initializer_list<obj>> list = {{obj()}};
1391 // then we need to destroy the inner array as well.
1392 for (unsigned i = 0, e = init->getNumInits(); i != e; ++i) {
1393 const InitListExpr *subInit = dyn_cast<InitListExpr>(init->getInit(i));
1394 if (!subInit || !subInit->initializesStdInitializerList())
1395 continue;
1396
1397 // This one needs to be destroyed. Get the address of the std::init_list.
1398 llvm::Value *offset = llvm::ConstantInt::get(CGF.SizeTy, i);
1399 llvm::Value *loc = CGF.Builder.CreateInBoundsGEP(arrayStart, offset,
1400 "std.initlist");
1401 CGF.EmitStdInitializerListCleanup(loc, subInit);
1402 }
1403}
1404
1405void CodeGenFunction::EmitStdInitializerListCleanup(llvm::Value *loc,
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001406 const InitListExpr *init) {
1407 ASTContext &ctx = getContext();
1408 QualType element = GetStdInitializerListElementType(init->getType());
1409 unsigned numInits = init->getNumInits();
1410 llvm::APInt size(ctx.getTypeSize(ctx.getSizeType()), numInits);
1411 QualType array =ctx.getConstantArrayType(element, size, ArrayType::Normal, 0);
1412 QualType arrayPtr = ctx.getPointerType(array);
1413 llvm::Type *arrayPtrType = ConvertType(arrayPtr);
1414
1415 // lvalue is the location of a std::initializer_list, which as its first
1416 // element has a pointer to the array we want to destroy.
Sebastian Redlaf130fd2012-02-19 12:28:02 +00001417 llvm::Value *startPointer = Builder.CreateStructGEP(loc, 0, "startPointer");
1418 llvm::Value *startAddress = Builder.CreateLoad(startPointer, "startAddress");
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001419
Sebastian Redlaf130fd2012-02-19 12:28:02 +00001420 ::EmitRecursiveStdInitializerListCleanup(*this, startAddress, init);
1421
1422 llvm::Value *arrayAddress =
1423 Builder.CreateBitCast(startAddress, arrayPtrType, "arrayAddress");
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001424 ::EmitStdInitializerListCleanup(*this, array, arrayAddress, init);
1425}