blob: f3eb34567bde3c9f1d01185d05a4547598143534 [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"
Fariborz Jahanian082b02e2009-07-08 01:18:33 +000015#include "CGObjCRuntime.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "CodeGenModule.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"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000021#include "llvm/IR/Constants.h"
22#include "llvm/IR/Function.h"
23#include "llvm/IR/GlobalVariable.h"
24#include "llvm/IR/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
John McCall9eda3ab2013-03-07 21:37:17 +000032llvm::Value *AggValueSlot::getPaddedAtomicAddr() const {
33 assert(isValueOfAtomic());
34 llvm::GEPOperator *op = cast<llvm::GEPOperator>(getAddr());
35 assert(op->getNumIndices() == 2);
36 assert(op->hasAllZeroIndices());
37 return op->getPointerOperand();
38}
39
Chris Lattner9c033562007-08-21 04:25:47 +000040namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000041class AggExprEmitter : public StmtVisitor<AggExprEmitter> {
Chris Lattner9c033562007-08-21 04:25:47 +000042 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000043 CGBuilderTy &Builder;
John McCall558d2ab2010-09-15 10:14:12 +000044 AggValueSlot Dest;
John McCallef072fd2010-05-22 01:48:05 +000045
John McCall410ffb22011-08-25 23:04:34 +000046 /// We want to use 'dest' as the return slot except under two
47 /// conditions:
48 /// - The destination slot requires garbage collection, so we
49 /// need to use the GC API.
50 /// - The destination slot is potentially aliased.
51 bool shouldUseDestForReturnSlot() const {
52 return !(Dest.requiresGCollection() || Dest.isPotentiallyAliased());
53 }
54
John McCallef072fd2010-05-22 01:48:05 +000055 ReturnValueSlot getReturnValueSlot() const {
John McCall410ffb22011-08-25 23:04:34 +000056 if (!shouldUseDestForReturnSlot())
57 return ReturnValueSlot();
John McCallfa037bd2010-05-22 22:13:32 +000058
John McCall558d2ab2010-09-15 10:14:12 +000059 return ReturnValueSlot(Dest.getAddr(), Dest.isVolatile());
60 }
61
62 AggValueSlot EnsureSlot(QualType T) {
63 if (!Dest.isIgnored()) return Dest;
64 return CGF.CreateAggTemp(T, "agg.tmp.ensured");
John McCallef072fd2010-05-22 01:48:05 +000065 }
John McCalle0c11682012-07-02 23:58:38 +000066 void EnsureDest(QualType T) {
67 if (!Dest.isIgnored()) return;
68 Dest = CGF.CreateAggTemp(T, "agg.tmp.ensured");
69 }
John McCallfa037bd2010-05-22 22:13:32 +000070
Chris Lattner9c033562007-08-21 04:25:47 +000071public:
John McCalle0c11682012-07-02 23:58:38 +000072 AggExprEmitter(CodeGenFunction &cgf, AggValueSlot Dest)
73 : CGF(cgf), Builder(CGF.Builder), Dest(Dest) {
Chris Lattner9c033562007-08-21 04:25:47 +000074 }
75
Chris Lattneree755f92007-08-21 04:59:27 +000076 //===--------------------------------------------------------------------===//
77 // Utilities
78 //===--------------------------------------------------------------------===//
79
Chris Lattner9c033562007-08-21 04:25:47 +000080 /// EmitAggLoadOfLValue - Given an expression with aggregate type that
81 /// represents a value lvalue, this method emits the address of the lvalue,
82 /// then loads the result into DestPtr.
83 void EmitAggLoadOfLValue(const Expr *E);
Eli Friedman922696f2008-05-19 17:51:16 +000084
Mike Stump4ac20dd2009-05-23 20:28:01 +000085 /// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
John McCalle0c11682012-07-02 23:58:38 +000086 void EmitFinalDestCopy(QualType type, const LValue &src);
87 void EmitFinalDestCopy(QualType type, RValue src,
88 CharUnits srcAlignment = CharUnits::Zero());
89 void EmitCopy(QualType type, const AggValueSlot &dest,
90 const AggValueSlot &src);
Mike Stump4ac20dd2009-05-23 20:28:01 +000091
John McCall410ffb22011-08-25 23:04:34 +000092 void EmitMoveFromReturnSlot(const Expr *E, RValue Src);
John McCallfa037bd2010-05-22 22:13:32 +000093
Sebastian Redl32cf1f22012-02-17 08:42:25 +000094 void EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
95 QualType elementType, InitListExpr *E);
96
John McCall7c2349b2011-08-25 20:40:09 +000097 AggValueSlot::NeedsGCBarriers_t needsGC(QualType T) {
David Blaikie4e4d0842012-03-11 07:00:24 +000098 if (CGF.getLangOpts().getGC() && TypeRequiresGCollection(T))
John McCall7c2349b2011-08-25 20:40:09 +000099 return AggValueSlot::NeedsGCBarriers;
100 return AggValueSlot::DoesNotNeedGCBarriers;
101 }
102
John McCallfa037bd2010-05-22 22:13:32 +0000103 bool TypeRequiresGCollection(QualType T);
104
Chris Lattneree755f92007-08-21 04:59:27 +0000105 //===--------------------------------------------------------------------===//
106 // Visitor Methods
107 //===--------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Chris Lattner9c033562007-08-21 04:25:47 +0000109 void VisitStmt(Stmt *S) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000110 CGF.ErrorUnsupported(S, "aggregate expression");
Chris Lattner9c033562007-08-21 04:25:47 +0000111 }
112 void VisitParenExpr(ParenExpr *PE) { Visit(PE->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000113 void VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
114 Visit(GE->getResultExpr());
115 }
Eli Friedman12444a22009-01-27 09:03:41 +0000116 void VisitUnaryExtension(UnaryOperator *E) { Visit(E->getSubExpr()); }
John McCall91a57552011-07-15 05:09:51 +0000117 void VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
118 return Visit(E->getReplacement());
119 }
Chris Lattner9c033562007-08-21 04:25:47 +0000120
121 // l-values.
John McCallf4b88a42012-03-10 09:33:50 +0000122 void VisitDeclRefExpr(DeclRefExpr *E) {
John McCalldd2ecee2012-03-10 03:05:10 +0000123 // For aggregates, we should always be able to emit the variable
124 // as an l-value unless it's a reference. This is due to the fact
125 // that we can't actually ever see a normal l2r conversion on an
126 // aggregate in C++, and in C there's no language standard
127 // actively preventing us from listing variables in the captures
128 // list of a block.
John McCallf4b88a42012-03-10 09:33:50 +0000129 if (E->getDecl()->getType()->isReferenceType()) {
John McCalldd2ecee2012-03-10 03:05:10 +0000130 if (CodeGenFunction::ConstantEmission result
John McCallf4b88a42012-03-10 09:33:50 +0000131 = CGF.tryEmitAsConstant(E)) {
John McCalle0c11682012-07-02 23:58:38 +0000132 EmitFinalDestCopy(E->getType(), result.getReferenceLValue(CGF, E));
John McCalldd2ecee2012-03-10 03:05:10 +0000133 return;
134 }
135 }
136
John McCallf4b88a42012-03-10 09:33:50 +0000137 EmitAggLoadOfLValue(E);
John McCalldd2ecee2012-03-10 03:05:10 +0000138 }
139
Seo Sanghyeon9b73b392007-12-14 02:04:12 +0000140 void VisitMemberExpr(MemberExpr *ME) { EmitAggLoadOfLValue(ME); }
141 void VisitUnaryDeref(UnaryOperator *E) { EmitAggLoadOfLValue(E); }
Daniel Dunbar5be028f2010-01-04 18:47:06 +0000142 void VisitStringLiteral(StringLiteral *E) { EmitAggLoadOfLValue(E); }
Douglas Gregor751ec9b2011-06-17 04:59:12 +0000143 void VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Seo Sanghyeon9b73b392007-12-14 02:04:12 +0000144 void VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
145 EmitAggLoadOfLValue(E);
146 }
Chris Lattnerf0a990c2009-04-21 23:00:09 +0000147 void VisitPredefinedExpr(const PredefinedExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000148 EmitAggLoadOfLValue(E);
Chris Lattnerf0a990c2009-04-21 23:00:09 +0000149 }
Mike Stump1eb44332009-09-09 15:08:12 +0000150
Chris Lattner9c033562007-08-21 04:25:47 +0000151 // Operators.
Anders Carlsson4d8673b2009-08-07 23:22:37 +0000152 void VisitCastExpr(CastExpr *E);
Anders Carlsson148fe672007-10-31 22:04:46 +0000153 void VisitCallExpr(const CallExpr *E);
Chris Lattnerb2d963f2007-08-31 22:54:14 +0000154 void VisitStmtExpr(const StmtExpr *E);
Chris Lattner9c033562007-08-21 04:25:47 +0000155 void VisitBinaryOperator(const BinaryOperator *BO);
Fariborz Jahanian8bfd31f2009-10-22 22:57:31 +0000156 void VisitPointerToDataMemberBinaryOperator(const BinaryOperator *BO);
Chris Lattner03d6fb92007-08-21 04:43:17 +0000157 void VisitBinAssign(const BinaryOperator *E);
Eli Friedman07fa52a2008-05-20 07:56:31 +0000158 void VisitBinComma(const BinaryOperator *E);
Chris Lattner9c033562007-08-21 04:25:47 +0000159
Chris Lattner8fdf3282008-06-24 17:04:18 +0000160 void VisitObjCMessageExpr(ObjCMessageExpr *E);
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000161 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
162 EmitAggLoadOfLValue(E);
163 }
Mike Stump1eb44332009-09-09 15:08:12 +0000164
John McCall56ca35d2011-02-17 10:25:35 +0000165 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO);
Anders Carlssona294ca82009-07-08 18:33:14 +0000166 void VisitChooseExpr(const ChooseExpr *CE);
Devang Patel636c3d02007-10-26 17:44:44 +0000167 void VisitInitListExpr(InitListExpr *E);
Anders Carlsson30311fa2009-12-16 06:57:54 +0000168 void VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
Chris Lattner04421082008-04-08 04:40:51 +0000169 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
170 Visit(DAE->getExpr());
171 }
Richard Smithc3bf52c2013-04-20 22:23:05 +0000172 void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
173 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
174 Visit(DIE->getExpr());
175 }
Anders Carlssonb58d0172009-05-30 23:23:33 +0000176 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
Anders Carlsson31ccf372009-05-03 17:47:16 +0000177 void VisitCXXConstructExpr(const CXXConstructExpr *E);
Eli Friedman4c5d8af2012-02-09 03:32:31 +0000178 void VisitLambdaExpr(LambdaExpr *E);
Richard Smith7c3e6152013-06-12 22:31:48 +0000179 void VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
John McCall4765fa02010-12-06 08:20:24 +0000180 void VisitExprWithCleanups(ExprWithCleanups *E);
Douglas Gregored8abf12010-07-08 06:14:04 +0000181 void VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Mike Stump2710c412009-11-18 00:40:12 +0000182 void VisitCXXTypeidExpr(CXXTypeidExpr *E) { EmitAggLoadOfLValue(E); }
Douglas Gregor03e80032011-06-21 17:03:29 +0000183 void VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
John McCalle996ffd2011-02-16 08:02:54 +0000184 void VisitOpaqueValueExpr(OpaqueValueExpr *E);
185
John McCall4b9c2d22011-11-06 09:01:30 +0000186 void VisitPseudoObjectExpr(PseudoObjectExpr *E) {
187 if (E->isGLValue()) {
188 LValue LV = CGF.EmitPseudoObjectLValue(E);
John McCalle0c11682012-07-02 23:58:38 +0000189 return EmitFinalDestCopy(E->getType(), LV);
John McCall4b9c2d22011-11-06 09:01:30 +0000190 }
191
192 CGF.EmitPseudoObjectRValue(E, EnsureSlot(E->getType()));
193 }
194
Eli Friedmanb1851242008-05-27 15:51:49 +0000195 void VisitVAArgExpr(VAArgExpr *E);
Chris Lattnerf81557c2008-04-04 18:42:16 +0000196
Chad Rosier649b4a12012-03-29 17:37:10 +0000197 void EmitInitializationToLValue(Expr *E, LValue Address);
John McCalla07398e2011-06-16 04:16:24 +0000198 void EmitNullInitializationToLValue(LValue Address);
Chris Lattner9c033562007-08-21 04:25:47 +0000199 // case Expr::ChooseExprClass:
Mike Stump39406b12009-12-09 19:24:08 +0000200 void VisitCXXThrowExpr(const CXXThrowExpr *E) { CGF.EmitCXXThrowExpr(E); }
Eli Friedman276b0612011-10-11 02:20:01 +0000201 void VisitAtomicExpr(AtomicExpr *E) {
202 CGF.EmitAtomicExpr(E, EnsureSlot(E->getType()).getAddr());
203 }
Chris Lattner9c033562007-08-21 04:25:47 +0000204};
John McCall9eda3ab2013-03-07 21:37:17 +0000205
206/// A helper class for emitting expressions into the value sub-object
207/// of a padded atomic type.
208class ValueDestForAtomic {
209 AggValueSlot Dest;
210public:
211 ValueDestForAtomic(CodeGenFunction &CGF, AggValueSlot dest, QualType type)
212 : Dest(dest) {
213 assert(!Dest.isValueOfAtomic());
214 if (!Dest.isIgnored() && CGF.CGM.isPaddedAtomicType(type)) {
215 llvm::Value *valueAddr = CGF.Builder.CreateStructGEP(Dest.getAddr(), 0);
216 Dest = AggValueSlot::forAddr(valueAddr,
217 Dest.getAlignment(),
218 Dest.getQualifiers(),
219 Dest.isExternallyDestructed(),
220 Dest.requiresGCollection(),
221 Dest.isPotentiallyAliased(),
222 Dest.isZeroed(),
223 AggValueSlot::IsValueOfAtomic);
224 }
225 }
226
227 const AggValueSlot &getDest() const { return Dest; }
228
229 ~ValueDestForAtomic() {
230 // Kill the GEP if we made one and it didn't end up used.
231 if (Dest.isValueOfAtomic()) {
232 llvm::Instruction *addr = cast<llvm::GetElementPtrInst>(Dest.getAddr());
233 if (addr->use_empty()) addr->eraseFromParent();
234 }
235 }
236};
Chris Lattner9c033562007-08-21 04:25:47 +0000237} // end anonymous namespace.
238
Chris Lattneree755f92007-08-21 04:59:27 +0000239//===----------------------------------------------------------------------===//
240// Utilities
241//===----------------------------------------------------------------------===//
Chris Lattner9c033562007-08-21 04:25:47 +0000242
Chris Lattner883f6a72007-08-11 00:04:45 +0000243/// EmitAggLoadOfLValue - Given an expression with aggregate type that
244/// represents a value lvalue, this method emits the address of the lvalue,
245/// then loads the result into DestPtr.
Chris Lattner9c033562007-08-21 04:25:47 +0000246void AggExprEmitter::EmitAggLoadOfLValue(const Expr *E) {
247 LValue LV = CGF.EmitLValue(E);
John McCall9eda3ab2013-03-07 21:37:17 +0000248
249 // If the type of the l-value is atomic, then do an atomic load.
250 if (LV.getType()->isAtomicType()) {
251 ValueDestForAtomic valueDest(CGF, Dest, LV.getType());
252 CGF.EmitAtomicLoad(LV, valueDest.getDest());
253 return;
254 }
255
John McCalle0c11682012-07-02 23:58:38 +0000256 EmitFinalDestCopy(E->getType(), LV);
Mike Stump4ac20dd2009-05-23 20:28:01 +0000257}
258
John McCallfa037bd2010-05-22 22:13:32 +0000259/// \brief True if the given aggregate type requires special GC API calls.
260bool AggExprEmitter::TypeRequiresGCollection(QualType T) {
261 // Only record types have members that might require garbage collection.
262 const RecordType *RecordTy = T->getAs<RecordType>();
263 if (!RecordTy) return false;
264
265 // Don't mess with non-trivial C++ types.
266 RecordDecl *Record = RecordTy->getDecl();
267 if (isa<CXXRecordDecl>(Record) &&
Richard Smith426391c2012-11-16 00:53:38 +0000268 (cast<CXXRecordDecl>(Record)->hasNonTrivialCopyConstructor() ||
John McCallfa037bd2010-05-22 22:13:32 +0000269 !cast<CXXRecordDecl>(Record)->hasTrivialDestructor()))
270 return false;
271
272 // Check whether the type has an object member.
273 return Record->hasObjectMember();
274}
275
John McCall410ffb22011-08-25 23:04:34 +0000276/// \brief Perform the final move to DestPtr if for some reason
277/// getReturnValueSlot() didn't use it directly.
John McCallfa037bd2010-05-22 22:13:32 +0000278///
279/// The idea is that you do something like this:
280/// RValue Result = EmitSomething(..., getReturnValueSlot());
John McCall410ffb22011-08-25 23:04:34 +0000281/// EmitMoveFromReturnSlot(E, Result);
282///
283/// If nothing interferes, this will cause the result to be emitted
284/// directly into the return value slot. Otherwise, a final move
285/// will be performed.
John McCalle0c11682012-07-02 23:58:38 +0000286void AggExprEmitter::EmitMoveFromReturnSlot(const Expr *E, RValue src) {
John McCall410ffb22011-08-25 23:04:34 +0000287 if (shouldUseDestForReturnSlot()) {
288 // Logically, Dest.getAddr() should equal Src.getAggregateAddr().
289 // The possibility of undef rvalues complicates that a lot,
290 // though, so we can't really assert.
291 return;
Fariborz Jahanian55bcace2010-06-15 22:44:06 +0000292 }
John McCall410ffb22011-08-25 23:04:34 +0000293
John McCalle0c11682012-07-02 23:58:38 +0000294 // Otherwise, copy from there to the destination.
295 assert(Dest.getAddr() != src.getAggregateAddr());
296 std::pair<CharUnits, CharUnits> typeInfo =
Chad Rosier26397ed2012-04-17 01:14:29 +0000297 CGF.getContext().getTypeInfoInChars(E->getType());
John McCalle0c11682012-07-02 23:58:38 +0000298 EmitFinalDestCopy(E->getType(), src, typeInfo.second);
John McCallfa037bd2010-05-22 22:13:32 +0000299}
300
Mike Stump4ac20dd2009-05-23 20:28:01 +0000301/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
John McCalle0c11682012-07-02 23:58:38 +0000302void AggExprEmitter::EmitFinalDestCopy(QualType type, RValue src,
303 CharUnits srcAlign) {
304 assert(src.isAggregate() && "value must be aggregate value!");
305 LValue srcLV = CGF.MakeAddrLValue(src.getAggregateAddr(), type, srcAlign);
306 EmitFinalDestCopy(type, srcLV);
307}
Mike Stump4ac20dd2009-05-23 20:28:01 +0000308
John McCalle0c11682012-07-02 23:58:38 +0000309/// EmitFinalDestCopy - Perform the final copy to DestPtr, if desired.
310void AggExprEmitter::EmitFinalDestCopy(QualType type, const LValue &src) {
John McCall558d2ab2010-09-15 10:14:12 +0000311 // If Dest is ignored, then we're evaluating an aggregate expression
John McCalle0c11682012-07-02 23:58:38 +0000312 // in a context that doesn't care about the result. Note that loads
313 // from volatile l-values force the existence of a non-ignored
314 // destination.
315 if (Dest.isIgnored())
316 return;
Fariborz Jahanian8a970052010-10-22 22:05:03 +0000317
John McCalle0c11682012-07-02 23:58:38 +0000318 AggValueSlot srcAgg =
319 AggValueSlot::forLValue(src, AggValueSlot::IsDestructed,
320 needsGC(type), AggValueSlot::IsAliased);
321 EmitCopy(type, Dest, srcAgg);
322}
Chris Lattner883f6a72007-08-11 00:04:45 +0000323
John McCalle0c11682012-07-02 23:58:38 +0000324/// Perform a copy from the source into the destination.
325///
326/// \param type - the type of the aggregate being copied; qualifiers are
327/// ignored
328void AggExprEmitter::EmitCopy(QualType type, const AggValueSlot &dest,
329 const AggValueSlot &src) {
330 if (dest.requiresGCollection()) {
331 CharUnits sz = CGF.getContext().getTypeSizeInChars(type);
332 llvm::Value *size = llvm::ConstantInt::get(CGF.SizeTy, sz.getQuantity());
Fariborz Jahanian08c32132009-08-31 19:33:16 +0000333 CGF.CGM.getObjCRuntime().EmitGCMemmoveCollectable(CGF,
John McCalle0c11682012-07-02 23:58:38 +0000334 dest.getAddr(),
335 src.getAddr(),
336 size);
Fariborz Jahanian08c32132009-08-31 19:33:16 +0000337 return;
338 }
John McCalle0c11682012-07-02 23:58:38 +0000339
Mike Stump4ac20dd2009-05-23 20:28:01 +0000340 // If the result of the assignment is used, copy the LHS there also.
John McCalle0c11682012-07-02 23:58:38 +0000341 // It's volatile if either side is. Use the minimum alignment of
342 // the two sides.
343 CGF.EmitAggregateCopy(dest.getAddr(), src.getAddr(), type,
344 dest.isVolatile() || src.isVolatile(),
345 std::min(dest.getAlignment(), src.getAlignment()));
Chris Lattner883f6a72007-08-11 00:04:45 +0000346}
347
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000348/// \brief Emit the initializer for a std::initializer_list initialized with a
349/// real initializer list.
Richard Smith7c3e6152013-06-12 22:31:48 +0000350void
351AggExprEmitter::VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E) {
352 // Emit an array containing the elements. The array is externally destructed
353 // if the std::initializer_list object is.
354 ASTContext &Ctx = CGF.getContext();
355 LValue Array = CGF.EmitLValue(E->getSubExpr());
356 assert(Array.isSimple() && "initializer_list array not a simple lvalue");
357 llvm::Value *ArrayPtr = Array.getAddress();
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000358
Richard Smith7c3e6152013-06-12 22:31:48 +0000359 const ConstantArrayType *ArrayType =
360 Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
361 assert(ArrayType && "std::initializer_list constructed from non-array");
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000362
Richard Smith7c3e6152013-06-12 22:31:48 +0000363 // FIXME: Perform the checks on the field types in SemaInit.
364 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
365 RecordDecl::field_iterator Field = Record->field_begin();
366 if (Field == Record->field_end()) {
367 CGF.ErrorUnsupported(E, "weird std::initializer_list");
Sebastian Redlbabcf9d2012-02-25 20:51:13 +0000368 return;
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000369 }
370
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000371 // Start pointer.
Richard Smith7c3e6152013-06-12 22:31:48 +0000372 if (!Field->getType()->isPointerType() ||
373 !Ctx.hasSameType(Field->getType()->getPointeeType(),
374 ArrayType->getElementType())) {
375 CGF.ErrorUnsupported(E, "weird std::initializer_list");
Sebastian Redlbabcf9d2012-02-25 20:51:13 +0000376 return;
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000377 }
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000378
Richard Smith7c3e6152013-06-12 22:31:48 +0000379 AggValueSlot Dest = EnsureSlot(E->getType());
380 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddr(), E->getType(),
381 Dest.getAlignment());
382 LValue Start = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
383 llvm::Value *Zero = llvm::ConstantInt::get(CGF.PtrDiffTy, 0);
384 llvm::Value *IdxStart[] = { Zero, Zero };
385 llvm::Value *ArrayStart =
386 Builder.CreateInBoundsGEP(ArrayPtr, IdxStart, "arraystart");
387 CGF.EmitStoreThroughLValue(RValue::get(ArrayStart), Start);
388 ++Field;
389
390 if (Field == Record->field_end()) {
391 CGF.ErrorUnsupported(E, "weird std::initializer_list");
Sebastian Redlbabcf9d2012-02-25 20:51:13 +0000392 return;
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000393 }
Richard Smith7c3e6152013-06-12 22:31:48 +0000394
395 llvm::Value *Size = Builder.getInt(ArrayType->getSize());
396 LValue EndOrLength = CGF.EmitLValueForFieldInitialization(DestLV, *Field);
397 if (Field->getType()->isPointerType() &&
398 Ctx.hasSameType(Field->getType()->getPointeeType(),
399 ArrayType->getElementType())) {
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000400 // End pointer.
Richard Smith7c3e6152013-06-12 22:31:48 +0000401 llvm::Value *IdxEnd[] = { Zero, Size };
402 llvm::Value *ArrayEnd =
403 Builder.CreateInBoundsGEP(ArrayPtr, IdxEnd, "arrayend");
404 CGF.EmitStoreThroughLValue(RValue::get(ArrayEnd), EndOrLength);
405 } else if (Ctx.hasSameType(Field->getType(), Ctx.getSizeType())) {
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000406 // Length.
Richard Smith7c3e6152013-06-12 22:31:48 +0000407 CGF.EmitStoreThroughLValue(RValue::get(Size), EndOrLength);
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000408 } else {
Richard Smith7c3e6152013-06-12 22:31:48 +0000409 CGF.ErrorUnsupported(E, "weird std::initializer_list");
Sebastian Redlbabcf9d2012-02-25 20:51:13 +0000410 return;
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000411 }
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000412}
413
414/// \brief Emit initialization of an array from an initializer list.
415void AggExprEmitter::EmitArrayInit(llvm::Value *DestPtr, llvm::ArrayType *AType,
416 QualType elementType, InitListExpr *E) {
417 uint64_t NumInitElements = E->getNumInits();
418
419 uint64_t NumArrayElements = AType->getNumElements();
420 assert(NumInitElements <= NumArrayElements);
421
422 // DestPtr is an array*. Construct an elementType* by drilling
423 // down a level.
424 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
425 llvm::Value *indices[] = { zero, zero };
426 llvm::Value *begin =
427 Builder.CreateInBoundsGEP(DestPtr, indices, "arrayinit.begin");
428
429 // Exception safety requires us to destroy all the
430 // already-constructed members if an initializer throws.
431 // For that, we'll need an EH cleanup.
432 QualType::DestructionKind dtorKind = elementType.isDestructedType();
433 llvm::AllocaInst *endOfInit = 0;
434 EHScopeStack::stable_iterator cleanup;
435 llvm::Instruction *cleanupDominator = 0;
436 if (CGF.needsEHCleanup(dtorKind)) {
437 // In principle we could tell the cleanup where we are more
438 // directly, but the control flow can get so varied here that it
439 // would actually be quite complex. Therefore we go through an
440 // alloca.
441 endOfInit = CGF.CreateTempAlloca(begin->getType(),
442 "arrayinit.endOfInit");
443 cleanupDominator = Builder.CreateStore(begin, endOfInit);
444 CGF.pushIrregularPartialArrayCleanup(begin, endOfInit, elementType,
445 CGF.getDestroyer(dtorKind));
446 cleanup = CGF.EHStack.stable_begin();
447
448 // Otherwise, remember that we didn't need a cleanup.
449 } else {
450 dtorKind = QualType::DK_none;
451 }
452
453 llvm::Value *one = llvm::ConstantInt::get(CGF.SizeTy, 1);
454
455 // The 'current element to initialize'. The invariants on this
456 // variable are complicated. Essentially, after each iteration of
457 // the loop, it points to the last initialized element, except
458 // that it points to the beginning of the array before any
459 // elements have been initialized.
460 llvm::Value *element = begin;
461
462 // Emit the explicit initializers.
463 for (uint64_t i = 0; i != NumInitElements; ++i) {
464 // Advance to the next element.
465 if (i > 0) {
466 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.element");
467
468 // Tell the cleanup that it needs to destroy up to this
469 // element. TODO: some of these stores can be trivially
470 // observed to be unnecessary.
471 if (endOfInit) Builder.CreateStore(element, endOfInit);
472 }
473
Richard Smith7c3e6152013-06-12 22:31:48 +0000474 LValue elementLV = CGF.MakeAddrLValue(element, elementType);
475 EmitInitializationToLValue(E->getInit(i), elementLV);
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000476 }
477
478 // Check whether there's a non-trivial array-fill expression.
479 // Note that this will be a CXXConstructExpr even if the element
480 // type is an array (or array of array, etc.) of class type.
481 Expr *filler = E->getArrayFiller();
482 bool hasTrivialFiller = true;
483 if (CXXConstructExpr *cons = dyn_cast_or_null<CXXConstructExpr>(filler)) {
484 assert(cons->getConstructor()->isDefaultConstructor());
485 hasTrivialFiller = cons->getConstructor()->isTrivial();
486 }
487
488 // Any remaining elements need to be zero-initialized, possibly
489 // using the filler expression. We can skip this if the we're
490 // emitting to zeroed memory.
491 if (NumInitElements != NumArrayElements &&
492 !(Dest.isZeroed() && hasTrivialFiller &&
493 CGF.getTypes().isZeroInitializable(elementType))) {
494
495 // Use an actual loop. This is basically
496 // do { *array++ = filler; } while (array != end);
497
498 // Advance to the start of the rest of the array.
499 if (NumInitElements) {
500 element = Builder.CreateInBoundsGEP(element, one, "arrayinit.start");
501 if (endOfInit) Builder.CreateStore(element, endOfInit);
502 }
503
504 // Compute the end of the array.
505 llvm::Value *end = Builder.CreateInBoundsGEP(begin,
506 llvm::ConstantInt::get(CGF.SizeTy, NumArrayElements),
507 "arrayinit.end");
508
509 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
510 llvm::BasicBlock *bodyBB = CGF.createBasicBlock("arrayinit.body");
511
512 // Jump into the body.
513 CGF.EmitBlock(bodyBB);
514 llvm::PHINode *currentElement =
515 Builder.CreatePHI(element->getType(), 2, "arrayinit.cur");
516 currentElement->addIncoming(element, entryBB);
517
518 // Emit the actual filler expression.
519 LValue elementLV = CGF.MakeAddrLValue(currentElement, elementType);
520 if (filler)
Chad Rosier649b4a12012-03-29 17:37:10 +0000521 EmitInitializationToLValue(filler, elementLV);
Sebastian Redl32cf1f22012-02-17 08:42:25 +0000522 else
523 EmitNullInitializationToLValue(elementLV);
524
525 // Move on to the next element.
526 llvm::Value *nextElement =
527 Builder.CreateInBoundsGEP(currentElement, one, "arrayinit.next");
528
529 // Tell the EH cleanup that we finished with the last element.
530 if (endOfInit) Builder.CreateStore(nextElement, endOfInit);
531
532 // Leave the loop if we're done.
533 llvm::Value *done = Builder.CreateICmpEQ(nextElement, end,
534 "arrayinit.done");
535 llvm::BasicBlock *endBB = CGF.createBasicBlock("arrayinit.end");
536 Builder.CreateCondBr(done, endBB, bodyBB);
537 currentElement->addIncoming(nextElement, Builder.GetInsertBlock());
538
539 CGF.EmitBlock(endBB);
540 }
541
542 // Leave the partial-array cleanup if we entered one.
543 if (dtorKind) CGF.DeactivateCleanupBlock(cleanup, cleanupDominator);
544}
545
Chris Lattneree755f92007-08-21 04:59:27 +0000546//===----------------------------------------------------------------------===//
547// Visitor Methods
548//===----------------------------------------------------------------------===//
549
Douglas Gregor03e80032011-06-21 17:03:29 +0000550void AggExprEmitter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E){
551 Visit(E->GetTemporaryExpr());
552}
553
John McCalle996ffd2011-02-16 08:02:54 +0000554void AggExprEmitter::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
John McCalle0c11682012-07-02 23:58:38 +0000555 EmitFinalDestCopy(e->getType(), CGF.getOpaqueLValueMapping(e));
John McCalle996ffd2011-02-16 08:02:54 +0000556}
557
Douglas Gregor751ec9b2011-06-17 04:59:12 +0000558void
559AggExprEmitter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
John McCall1723f632013-03-07 21:36:54 +0000560 if (Dest.isPotentiallyAliased() &&
561 E->getType().isPODType(CGF.getContext())) {
Douglas Gregor673e98b2011-06-17 16:37:20 +0000562 // For a POD type, just emit a load of the lvalue + a copy, because our
563 // compound literal might alias the destination.
Douglas Gregor673e98b2011-06-17 16:37:20 +0000564 EmitAggLoadOfLValue(E);
565 return;
566 }
567
Douglas Gregor751ec9b2011-06-17 04:59:12 +0000568 AggValueSlot Slot = EnsureSlot(E->getType());
569 CGF.EmitAggExpr(E->getInitializer(), Slot);
570}
571
John McCall9eda3ab2013-03-07 21:37:17 +0000572/// Attempt to look through various unimportant expressions to find a
573/// cast of the given kind.
574static Expr *findPeephole(Expr *op, CastKind kind) {
575 while (true) {
576 op = op->IgnoreParens();
577 if (CastExpr *castE = dyn_cast<CastExpr>(op)) {
578 if (castE->getCastKind() == kind)
579 return castE->getSubExpr();
580 if (castE->getCastKind() == CK_NoOp)
581 continue;
582 }
583 return 0;
584 }
585}
Douglas Gregor751ec9b2011-06-17 04:59:12 +0000586
Anders Carlsson4d8673b2009-08-07 23:22:37 +0000587void AggExprEmitter::VisitCastExpr(CastExpr *E) {
Anders Carlsson30168422009-09-29 01:23:39 +0000588 switch (E->getCastKind()) {
Anders Carlsson575b3742011-04-11 02:03:26 +0000589 case CK_Dynamic: {
Richard Smith2c9f87c2012-08-24 00:54:33 +0000590 // FIXME: Can this actually happen? We have no test coverage for it.
Douglas Gregor69cfeb12010-05-14 21:31:02 +0000591 assert(isa<CXXDynamicCastExpr>(E) && "CK_Dynamic without a dynamic_cast?");
Richard Smith2c9f87c2012-08-24 00:54:33 +0000592 LValue LV = CGF.EmitCheckedLValue(E->getSubExpr(),
Richard Smith7ac9ef12012-09-08 02:08:36 +0000593 CodeGenFunction::TCK_Load);
Douglas Gregor69cfeb12010-05-14 21:31:02 +0000594 // FIXME: Do we also need to handle property references here?
595 if (LV.isSimple())
596 CGF.EmitDynamicCast(LV.getAddress(), cast<CXXDynamicCastExpr>(E));
597 else
598 CGF.CGM.ErrorUnsupported(E, "non-simple lvalue dynamic_cast");
599
John McCall558d2ab2010-09-15 10:14:12 +0000600 if (!Dest.isIgnored())
601 CGF.CGM.ErrorUnsupported(E, "lvalue dynamic_cast with a destination");
Douglas Gregor69cfeb12010-05-14 21:31:02 +0000602 break;
603 }
604
John McCall2de56d12010-08-25 11:45:40 +0000605 case CK_ToUnion: {
John McCall65912712011-04-12 22:02:02 +0000606 if (Dest.isIgnored()) break;
607
Anders Carlsson4d8673b2009-08-07 23:22:37 +0000608 // GCC union extension
Daniel Dunbar79c39282010-08-21 03:15:20 +0000609 QualType Ty = E->getSubExpr()->getType();
610 QualType PtrTy = CGF.getContext().getPointerType(Ty);
John McCall558d2ab2010-09-15 10:14:12 +0000611 llvm::Value *CastPtr = Builder.CreateBitCast(Dest.getAddr(),
Eli Friedman34ebf4d2009-06-03 20:45:06 +0000612 CGF.ConvertType(PtrTy));
John McCalla07398e2011-06-16 04:16:24 +0000613 EmitInitializationToLValue(E->getSubExpr(),
Chad Rosier649b4a12012-03-29 17:37:10 +0000614 CGF.MakeAddrLValue(CastPtr, Ty));
Anders Carlsson30168422009-09-29 01:23:39 +0000615 break;
Nuno Lopes7e916272009-01-15 20:14:33 +0000616 }
Mike Stump1eb44332009-09-09 15:08:12 +0000617
John McCall2de56d12010-08-25 11:45:40 +0000618 case CK_DerivedToBase:
619 case CK_BaseToDerived:
620 case CK_UncheckedDerivedToBase: {
David Blaikieb219cfc2011-09-23 05:06:16 +0000621 llvm_unreachable("cannot perform hierarchy conversion in EmitAggExpr: "
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000622 "should have been unpacked before we got here");
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000623 }
624
John McCall9eda3ab2013-03-07 21:37:17 +0000625 case CK_NonAtomicToAtomic:
626 case CK_AtomicToNonAtomic: {
627 bool isToAtomic = (E->getCastKind() == CK_NonAtomicToAtomic);
628
629 // Determine the atomic and value types.
630 QualType atomicType = E->getSubExpr()->getType();
631 QualType valueType = E->getType();
632 if (isToAtomic) std::swap(atomicType, valueType);
633
634 assert(atomicType->isAtomicType());
635 assert(CGF.getContext().hasSameUnqualifiedType(valueType,
636 atomicType->castAs<AtomicType>()->getValueType()));
637
638 // Just recurse normally if we're ignoring the result or the
639 // atomic type doesn't change representation.
640 if (Dest.isIgnored() || !CGF.CGM.isPaddedAtomicType(atomicType)) {
641 return Visit(E->getSubExpr());
642 }
643
644 CastKind peepholeTarget =
645 (isToAtomic ? CK_AtomicToNonAtomic : CK_NonAtomicToAtomic);
646
647 // These two cases are reverses of each other; try to peephole them.
648 if (Expr *op = findPeephole(E->getSubExpr(), peepholeTarget)) {
649 assert(CGF.getContext().hasSameUnqualifiedType(op->getType(),
650 E->getType()) &&
651 "peephole significantly changed types?");
652 return Visit(op);
653 }
654
655 // If we're converting an r-value of non-atomic type to an r-value
656 // of atomic type, just make an atomic temporary, emit into that,
657 // and then copy the value out. (FIXME: do we need to
658 // zero-initialize it first?)
659 if (isToAtomic) {
660 ValueDestForAtomic valueDest(CGF, Dest, atomicType);
661 CGF.EmitAggExpr(E->getSubExpr(), valueDest.getDest());
662 return;
663 }
664
665 // Otherwise, we're converting an atomic type to a non-atomic type.
666
667 // If the dest is a value-of-atomic subobject, drill back out.
668 if (Dest.isValueOfAtomic()) {
669 AggValueSlot atomicSlot =
670 AggValueSlot::forAddr(Dest.getPaddedAtomicAddr(),
671 Dest.getAlignment(),
672 Dest.getQualifiers(),
673 Dest.isExternallyDestructed(),
674 Dest.requiresGCollection(),
675 Dest.isPotentiallyAliased(),
676 Dest.isZeroed(),
677 AggValueSlot::IsNotValueOfAtomic);
678 CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
679 return;
680 }
681
682 // Otherwise, make an atomic temporary, emit into that, and then
683 // copy the value out.
684 AggValueSlot atomicSlot =
685 CGF.CreateAggTemp(atomicType, "atomic-to-nonatomic.temp");
686 CGF.EmitAggExpr(E->getSubExpr(), atomicSlot);
687
688 llvm::Value *valueAddr =
689 Builder.CreateStructGEP(atomicSlot.getAddr(), 0);
690 RValue rvalue = RValue::getAggregate(valueAddr, atomicSlot.isVolatile());
691 return EmitFinalDestCopy(valueType, rvalue);
692 }
693
John McCalle0c11682012-07-02 23:58:38 +0000694 case CK_LValueToRValue:
695 // If we're loading from a volatile type, force the destination
696 // into existence.
697 if (E->getSubExpr()->getType().isVolatileQualified()) {
698 EnsureDest(E->getType());
699 return Visit(E->getSubExpr());
700 }
John McCall9eda3ab2013-03-07 21:37:17 +0000701
John McCalle0c11682012-07-02 23:58:38 +0000702 // fallthrough
703
John McCall2de56d12010-08-25 11:45:40 +0000704 case CK_NoOp:
705 case CK_UserDefinedConversion:
706 case CK_ConstructorConversion:
Anders Carlsson30168422009-09-29 01:23:39 +0000707 assert(CGF.getContext().hasSameUnqualifiedType(E->getSubExpr()->getType(),
708 E->getType()) &&
709 "Implicit cast types must be compatible");
710 Visit(E->getSubExpr());
711 break;
John McCall0ae287a2010-12-01 04:43:34 +0000712
John McCall2de56d12010-08-25 11:45:40 +0000713 case CK_LValueBitCast:
John McCall0ae287a2010-12-01 04:43:34 +0000714 llvm_unreachable("should not be emitting lvalue bitcast as rvalue");
John McCall1de4d4e2011-04-07 08:22:57 +0000715
John McCall0ae287a2010-12-01 04:43:34 +0000716 case CK_Dependent:
717 case CK_BitCast:
718 case CK_ArrayToPointerDecay:
719 case CK_FunctionToPointerDecay:
720 case CK_NullToPointer:
721 case CK_NullToMemberPointer:
722 case CK_BaseToDerivedMemberPointer:
723 case CK_DerivedToBaseMemberPointer:
724 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +0000725 case CK_ReinterpretMemberPointer:
John McCall0ae287a2010-12-01 04:43:34 +0000726 case CK_IntegralToPointer:
727 case CK_PointerToIntegral:
728 case CK_PointerToBoolean:
729 case CK_ToVoid:
730 case CK_VectorSplat:
731 case CK_IntegralCast:
732 case CK_IntegralToBoolean:
733 case CK_IntegralToFloating:
734 case CK_FloatingToIntegral:
735 case CK_FloatingToBoolean:
736 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +0000737 case CK_CPointerToObjCPointerCast:
738 case CK_BlockPointerToObjCPointerCast:
John McCall0ae287a2010-12-01 04:43:34 +0000739 case CK_AnyPointerToBlockPointerCast:
740 case CK_ObjCObjectLValueCast:
741 case CK_FloatingRealToComplex:
742 case CK_FloatingComplexToReal:
743 case CK_FloatingComplexToBoolean:
744 case CK_FloatingComplexCast:
745 case CK_FloatingComplexToIntegralComplex:
746 case CK_IntegralRealToComplex:
747 case CK_IntegralComplexToReal:
748 case CK_IntegralComplexToBoolean:
749 case CK_IntegralComplexCast:
750 case CK_IntegralComplexToFloatingComplex:
John McCall33e56f32011-09-10 06:18:15 +0000751 case CK_ARCProduceObject:
752 case CK_ARCConsumeObject:
753 case CK_ARCReclaimReturnedObject:
754 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +0000755 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000756 case CK_BuiltinFnToFnPtr:
Guy Benyeie6b9d802013-01-20 12:31:11 +0000757 case CK_ZeroToOCLEvent:
John McCall0ae287a2010-12-01 04:43:34 +0000758 llvm_unreachable("cast kind invalid for aggregate types");
Anders Carlsson30168422009-09-29 01:23:39 +0000759 }
Anders Carlssone4707ff2008-01-14 06:28:57 +0000760}
761
Chris Lattner96196622008-07-26 22:37:01 +0000762void AggExprEmitter::VisitCallExpr(const CallExpr *E) {
Anders Carlssone70e8f72009-05-27 16:45:02 +0000763 if (E->getCallReturnType()->isReferenceType()) {
764 EmitAggLoadOfLValue(E);
765 return;
766 }
Mike Stump1eb44332009-09-09 15:08:12 +0000767
John McCallfa037bd2010-05-22 22:13:32 +0000768 RValue RV = CGF.EmitCallExpr(E, getReturnValueSlot());
John McCall410ffb22011-08-25 23:04:34 +0000769 EmitMoveFromReturnSlot(E, RV);
Anders Carlsson148fe672007-10-31 22:04:46 +0000770}
Chris Lattner96196622008-07-26 22:37:01 +0000771
772void AggExprEmitter::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCallfa037bd2010-05-22 22:13:32 +0000773 RValue RV = CGF.EmitObjCMessageExpr(E, getReturnValueSlot());
John McCall410ffb22011-08-25 23:04:34 +0000774 EmitMoveFromReturnSlot(E, RV);
Chris Lattner8fdf3282008-06-24 17:04:18 +0000775}
Anders Carlsson148fe672007-10-31 22:04:46 +0000776
Chris Lattner96196622008-07-26 22:37:01 +0000777void AggExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCall2a416372010-12-05 02:00:02 +0000778 CGF.EmitIgnoredExpr(E->getLHS());
John McCall558d2ab2010-09-15 10:14:12 +0000779 Visit(E->getRHS());
Eli Friedman07fa52a2008-05-20 07:56:31 +0000780}
781
Chris Lattnerb2d963f2007-08-31 22:54:14 +0000782void AggExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCall150b4622011-01-26 04:00:11 +0000783 CodeGenFunction::StmtExprEvaluation eval(CGF);
John McCall558d2ab2010-09-15 10:14:12 +0000784 CGF.EmitCompoundStmt(*E->getSubStmt(), true, Dest);
Chris Lattnerb2d963f2007-08-31 22:54:14 +0000785}
786
Chris Lattner9c033562007-08-21 04:25:47 +0000787void AggExprEmitter::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +0000788 if (E->getOpcode() == BO_PtrMemD || E->getOpcode() == BO_PtrMemI)
Fariborz Jahanian8bfd31f2009-10-22 22:57:31 +0000789 VisitPointerToDataMemberBinaryOperator(E);
790 else
791 CGF.ErrorUnsupported(E, "aggregate binary expression");
792}
793
794void AggExprEmitter::VisitPointerToDataMemberBinaryOperator(
795 const BinaryOperator *E) {
796 LValue LV = CGF.EmitPointerToDataMemberBinaryExpr(E);
John McCalle0c11682012-07-02 23:58:38 +0000797 EmitFinalDestCopy(E->getType(), LV);
798}
799
800/// Is the value of the given expression possibly a reference to or
801/// into a __block variable?
802static bool isBlockVarRef(const Expr *E) {
803 // Make sure we look through parens.
804 E = E->IgnoreParens();
805
806 // Check for a direct reference to a __block variable.
807 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
808 const VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
809 return (var && var->hasAttr<BlocksAttr>());
810 }
811
812 // More complicated stuff.
813
814 // Binary operators.
815 if (const BinaryOperator *op = dyn_cast<BinaryOperator>(E)) {
816 // For an assignment or pointer-to-member operation, just care
817 // about the LHS.
818 if (op->isAssignmentOp() || op->isPtrMemOp())
819 return isBlockVarRef(op->getLHS());
820
821 // For a comma, just care about the RHS.
822 if (op->getOpcode() == BO_Comma)
823 return isBlockVarRef(op->getRHS());
824
825 // FIXME: pointer arithmetic?
826 return false;
827
828 // Check both sides of a conditional operator.
829 } else if (const AbstractConditionalOperator *op
830 = dyn_cast<AbstractConditionalOperator>(E)) {
831 return isBlockVarRef(op->getTrueExpr())
832 || isBlockVarRef(op->getFalseExpr());
833
834 // OVEs are required to support BinaryConditionalOperators.
835 } else if (const OpaqueValueExpr *op
836 = dyn_cast<OpaqueValueExpr>(E)) {
837 if (const Expr *src = op->getSourceExpr())
838 return isBlockVarRef(src);
839
840 // Casts are necessary to get things like (*(int*)&var) = foo().
841 // We don't really care about the kind of cast here, except
842 // we don't want to look through l2r casts, because it's okay
843 // to get the *value* in a __block variable.
844 } else if (const CastExpr *cast = dyn_cast<CastExpr>(E)) {
845 if (cast->getCastKind() == CK_LValueToRValue)
846 return false;
847 return isBlockVarRef(cast->getSubExpr());
848
849 // Handle unary operators. Again, just aggressively look through
850 // it, ignoring the operation.
851 } else if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E)) {
852 return isBlockVarRef(uop->getSubExpr());
853
854 // Look into the base of a field access.
855 } else if (const MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
856 return isBlockVarRef(mem->getBase());
857
858 // Look into the base of a subscript.
859 } else if (const ArraySubscriptExpr *sub = dyn_cast<ArraySubscriptExpr>(E)) {
860 return isBlockVarRef(sub->getBase());
861 }
862
863 return false;
Chris Lattneree755f92007-08-21 04:59:27 +0000864}
865
Chris Lattner03d6fb92007-08-21 04:43:17 +0000866void AggExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Eli Friedmanff6e2b72008-02-11 01:09:17 +0000867 // For an assignment to work, the value on the right has
868 // to be compatible with the value on the left.
Eli Friedman2dce5f82009-05-28 23:04:00 +0000869 assert(CGF.getContext().hasSameUnqualifiedType(E->getLHS()->getType(),
870 E->getRHS()->getType())
Eli Friedmanff6e2b72008-02-11 01:09:17 +0000871 && "Invalid assignment");
John McCallcd940a12010-12-06 06:10:02 +0000872
John McCalle0c11682012-07-02 23:58:38 +0000873 // If the LHS might be a __block variable, and the RHS can
874 // potentially cause a block copy, we need to evaluate the RHS first
875 // so that the assignment goes the right place.
876 // This is pretty semantically fragile.
877 if (isBlockVarRef(E->getLHS()) &&
878 E->getRHS()->HasSideEffects(CGF.getContext())) {
879 // Ensure that we have a destination, and evaluate the RHS into that.
880 EnsureDest(E->getRHS()->getType());
881 Visit(E->getRHS());
882
883 // Now emit the LHS and copy into it.
Richard Smith4def70d2012-10-09 19:52:38 +0000884 LValue LHS = CGF.EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCalle0c11682012-07-02 23:58:38 +0000885
John McCall9eda3ab2013-03-07 21:37:17 +0000886 // That copy is an atomic copy if the LHS is atomic.
887 if (LHS.getType()->isAtomicType()) {
888 CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
889 return;
890 }
891
John McCalle0c11682012-07-02 23:58:38 +0000892 EmitCopy(E->getLHS()->getType(),
893 AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
894 needsGC(E->getLHS()->getType()),
895 AggValueSlot::IsAliased),
896 Dest);
897 return;
898 }
Chad Rosier649b4a12012-03-29 17:37:10 +0000899
Chris Lattner9c033562007-08-21 04:25:47 +0000900 LValue LHS = CGF.EmitLValue(E->getLHS());
Chris Lattner883f6a72007-08-11 00:04:45 +0000901
John McCall9eda3ab2013-03-07 21:37:17 +0000902 // If we have an atomic type, evaluate into the destination and then
903 // do an atomic copy.
904 if (LHS.getType()->isAtomicType()) {
905 EnsureDest(E->getRHS()->getType());
906 Visit(E->getRHS());
907 CGF.EmitAtomicStore(Dest.asRValue(), LHS, /*isInit*/ false);
908 return;
909 }
910
John McCalldb458062011-11-07 03:59:57 +0000911 // Codegen the RHS so that it stores directly into the LHS.
912 AggValueSlot LHSSlot =
913 AggValueSlot::forLValue(LHS, AggValueSlot::IsDestructed,
914 needsGC(E->getLHS()->getType()),
Chad Rosier649b4a12012-03-29 17:37:10 +0000915 AggValueSlot::IsAliased);
Fariborz Jahanian3ac83d62013-01-25 23:57:05 +0000916 // A non-volatile aggregate destination might have volatile member.
917 if (!LHSSlot.isVolatile() &&
918 CGF.hasVolatileMember(E->getLHS()->getType()))
919 LHSSlot.setVolatile(true);
920
John McCalle0c11682012-07-02 23:58:38 +0000921 CGF.EmitAggExpr(E->getRHS(), LHSSlot);
922
923 // Copy into the destination if the assignment isn't ignored.
924 EmitFinalDestCopy(E->getType(), LHS);
Chris Lattner883f6a72007-08-11 00:04:45 +0000925}
926
John McCall56ca35d2011-02-17 10:25:35 +0000927void AggExprEmitter::
928VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Daniel Dunbar9615ecb2008-11-13 01:38:36 +0000929 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
930 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
931 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Mike Stump1eb44332009-09-09 15:08:12 +0000932
John McCall56ca35d2011-02-17 10:25:35 +0000933 // Bind the common expression if necessary.
Eli Friedmand97927d2012-01-06 20:42:20 +0000934 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
John McCall56ca35d2011-02-17 10:25:35 +0000935
John McCall150b4622011-01-26 04:00:11 +0000936 CodeGenFunction::ConditionalEvaluation eval(CGF);
Eli Friedman8e274bd2009-12-25 06:17:05 +0000937 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000938
John McCall74fb0ed2010-11-17 00:07:33 +0000939 // Save whether the destination's lifetime is externally managed.
John McCallfd71fb82011-08-26 08:02:37 +0000940 bool isExternallyDestructed = Dest.isExternallyDestructed();
Chris Lattner883f6a72007-08-11 00:04:45 +0000941
John McCall150b4622011-01-26 04:00:11 +0000942 eval.begin(CGF);
943 CGF.EmitBlock(LHSBlock);
John McCall56ca35d2011-02-17 10:25:35 +0000944 Visit(E->getTrueExpr());
John McCall150b4622011-01-26 04:00:11 +0000945 eval.end(CGF);
Mike Stump1eb44332009-09-09 15:08:12 +0000946
John McCall150b4622011-01-26 04:00:11 +0000947 assert(CGF.HaveInsertPoint() && "expression evaluation ended with no IP!");
948 CGF.Builder.CreateBr(ContBlock);
Mike Stump1eb44332009-09-09 15:08:12 +0000949
John McCall74fb0ed2010-11-17 00:07:33 +0000950 // If the result of an agg expression is unused, then the emission
951 // of the LHS might need to create a destination slot. That's fine
952 // with us, and we can safely emit the RHS into the same slot, but
John McCallfd71fb82011-08-26 08:02:37 +0000953 // we shouldn't claim that it's already being destructed.
954 Dest.setExternallyDestructed(isExternallyDestructed);
John McCall74fb0ed2010-11-17 00:07:33 +0000955
John McCall150b4622011-01-26 04:00:11 +0000956 eval.begin(CGF);
957 CGF.EmitBlock(RHSBlock);
John McCall56ca35d2011-02-17 10:25:35 +0000958 Visit(E->getFalseExpr());
John McCall150b4622011-01-26 04:00:11 +0000959 eval.end(CGF);
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Chris Lattner9c033562007-08-21 04:25:47 +0000961 CGF.EmitBlock(ContBlock);
Chris Lattner883f6a72007-08-11 00:04:45 +0000962}
Chris Lattneree755f92007-08-21 04:59:27 +0000963
Anders Carlssona294ca82009-07-08 18:33:14 +0000964void AggExprEmitter::VisitChooseExpr(const ChooseExpr *CE) {
965 Visit(CE->getChosenSubExpr(CGF.getContext()));
966}
967
Eli Friedmanb1851242008-05-27 15:51:49 +0000968void AggExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Daniel Dunbar07855702009-02-11 22:25:55 +0000969 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000970 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
971
Sebastian Redl0262f022009-01-09 21:09:38 +0000972 if (!ArgPtr) {
Anders Carlssonddf7cac2008-11-04 05:30:00 +0000973 CGF.ErrorUnsupported(VE, "aggregate va_arg expression");
Sebastian Redl0262f022009-01-09 21:09:38 +0000974 return;
975 }
976
John McCalle0c11682012-07-02 23:58:38 +0000977 EmitFinalDestCopy(VE->getType(), CGF.MakeAddrLValue(ArgPtr, VE->getType()));
Eli Friedmanb1851242008-05-27 15:51:49 +0000978}
979
Anders Carlssonb58d0172009-05-30 23:23:33 +0000980void AggExprEmitter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
John McCall558d2ab2010-09-15 10:14:12 +0000981 // Ensure that we have a slot, but if we already do, remember
John McCallfd71fb82011-08-26 08:02:37 +0000982 // whether it was externally destructed.
983 bool wasExternallyDestructed = Dest.isExternallyDestructed();
John McCalle0c11682012-07-02 23:58:38 +0000984 EnsureDest(E->getType());
John McCallfd71fb82011-08-26 08:02:37 +0000985
986 // We're going to push a destructor if there isn't already one.
987 Dest.setExternallyDestructed();
Mike Stump1eb44332009-09-09 15:08:12 +0000988
John McCall558d2ab2010-09-15 10:14:12 +0000989 Visit(E->getSubExpr());
Anders Carlssonb58d0172009-05-30 23:23:33 +0000990
John McCallfd71fb82011-08-26 08:02:37 +0000991 // Push that destructor we promised.
992 if (!wasExternallyDestructed)
Peter Collingbourne86811602011-11-27 22:09:22 +0000993 CGF.EmitCXXTemporary(E->getTemporary(), E->getType(), Dest.getAddr());
Anders Carlssonb58d0172009-05-30 23:23:33 +0000994}
995
Anders Carlssonb14095a2009-04-17 00:06:03 +0000996void
Anders Carlsson31ccf372009-05-03 17:47:16 +0000997AggExprEmitter::VisitCXXConstructExpr(const CXXConstructExpr *E) {
John McCall558d2ab2010-09-15 10:14:12 +0000998 AggValueSlot Slot = EnsureSlot(E->getType());
999 CGF.EmitCXXConstructExpr(E, Slot);
Anders Carlsson7f6ad152009-05-19 04:48:36 +00001000}
1001
Eli Friedman4c5d8af2012-02-09 03:32:31 +00001002void
1003AggExprEmitter::VisitLambdaExpr(LambdaExpr *E) {
1004 AggValueSlot Slot = EnsureSlot(E->getType());
1005 CGF.EmitLambdaExpr(E, Slot);
1006}
1007
John McCall4765fa02010-12-06 08:20:24 +00001008void AggExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
John McCall1a343eb2011-11-10 08:15:53 +00001009 CGF.enterFullExpression(E);
1010 CodeGenFunction::RunCleanupsScope cleanups(CGF);
1011 Visit(E->getSubExpr());
Anders Carlssonb14095a2009-04-17 00:06:03 +00001012}
1013
Douglas Gregored8abf12010-07-08 06:14:04 +00001014void AggExprEmitter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
John McCall558d2ab2010-09-15 10:14:12 +00001015 QualType T = E->getType();
1016 AggValueSlot Slot = EnsureSlot(T);
John McCalla07398e2011-06-16 04:16:24 +00001017 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
Anders Carlsson30311fa2009-12-16 06:57:54 +00001018}
1019
1020void AggExprEmitter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
John McCall558d2ab2010-09-15 10:14:12 +00001021 QualType T = E->getType();
1022 AggValueSlot Slot = EnsureSlot(T);
John McCalla07398e2011-06-16 04:16:24 +00001023 EmitNullInitializationToLValue(CGF.MakeAddrLValue(Slot.getAddr(), T));
Nuno Lopes329763b2009-10-18 15:18:11 +00001024}
1025
Chris Lattner1b726772010-12-02 07:07:26 +00001026/// isSimpleZero - If emitting this value will obviously just cause a store of
1027/// zero to memory, return true. This can return false if uncertain, so it just
1028/// handles simple cases.
1029static bool isSimpleZero(const Expr *E, CodeGenFunction &CGF) {
Peter Collingbournef111d932011-04-15 00:35:48 +00001030 E = E->IgnoreParens();
1031
Chris Lattner1b726772010-12-02 07:07:26 +00001032 // 0
1033 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E))
1034 return IL->getValue() == 0;
1035 // +0.0
1036 if (const FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E))
1037 return FL->getValue().isPosZero();
1038 // int()
1039 if ((isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) &&
1040 CGF.getTypes().isZeroInitializable(E->getType()))
1041 return true;
1042 // (int*)0 - Null pointer expressions.
1043 if (const CastExpr *ICE = dyn_cast<CastExpr>(E))
1044 return ICE->getCastKind() == CK_NullToPointer;
1045 // '\0'
1046 if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E))
1047 return CL->getValue() == 0;
1048
1049 // Otherwise, hard case: conservatively return false.
1050 return false;
1051}
1052
1053
Anders Carlsson78e83f82010-02-03 17:33:16 +00001054void
Chad Rosier649b4a12012-03-29 17:37:10 +00001055AggExprEmitter::EmitInitializationToLValue(Expr* E, LValue LV) {
John McCalla07398e2011-06-16 04:16:24 +00001056 QualType type = LV.getType();
Mike Stump7f79f9b2009-05-29 15:46:01 +00001057 // FIXME: Ignore result?
Chris Lattnerf81557c2008-04-04 18:42:16 +00001058 // FIXME: Are initializers affected by volatile?
Chris Lattner1b726772010-12-02 07:07:26 +00001059 if (Dest.isZeroed() && isSimpleZero(E, CGF)) {
1060 // Storing "i32 0" to a zero'd memory location is a noop.
John McCall9d232c82013-03-07 21:37:08 +00001061 return;
Richard Smith0dbe2fb2012-12-21 03:17:28 +00001062 } else if (isa<ImplicitValueInitExpr>(E) || isa<CXXScalarValueInitExpr>(E)) {
John McCall9d232c82013-03-07 21:37:08 +00001063 return EmitNullInitializationToLValue(LV);
John McCalla07398e2011-06-16 04:16:24 +00001064 } else if (type->isReferenceType()) {
Anders Carlsson32f36ba2010-06-26 16:35:32 +00001065 RValue RV = CGF.EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
John McCall9d232c82013-03-07 21:37:08 +00001066 return CGF.EmitStoreThroughLValue(RV, LV);
1067 }
1068
1069 switch (CGF.getEvaluationKind(type)) {
1070 case TEK_Complex:
1071 CGF.EmitComplexExprIntoLValue(E, LV, /*isInit*/ true);
1072 return;
1073 case TEK_Aggregate:
John McCall7c2349b2011-08-25 20:40:09 +00001074 CGF.EmitAggExpr(E, AggValueSlot::forLValue(LV,
1075 AggValueSlot::IsDestructed,
1076 AggValueSlot::DoesNotNeedGCBarriers,
John McCall410ffb22011-08-25 23:04:34 +00001077 AggValueSlot::IsNotAliased,
John McCalla07398e2011-06-16 04:16:24 +00001078 Dest.isZeroed()));
John McCall9d232c82013-03-07 21:37:08 +00001079 return;
1080 case TEK_Scalar:
1081 if (LV.isSimple()) {
1082 CGF.EmitScalarInit(E, /*D=*/0, LV, /*Captured=*/false);
1083 } else {
1084 CGF.EmitStoreThroughLValue(RValue::get(CGF.EmitScalarExpr(E)), LV);
1085 }
1086 return;
Chris Lattnerf81557c2008-04-04 18:42:16 +00001087 }
John McCall9d232c82013-03-07 21:37:08 +00001088 llvm_unreachable("bad evaluation kind");
Chris Lattnerf81557c2008-04-04 18:42:16 +00001089}
1090
John McCalla07398e2011-06-16 04:16:24 +00001091void AggExprEmitter::EmitNullInitializationToLValue(LValue lv) {
1092 QualType type = lv.getType();
1093
Chris Lattner1b726772010-12-02 07:07:26 +00001094 // If the destination slot is already zeroed out before the aggregate is
1095 // copied into it, we don't have to emit any zeros here.
John McCalla07398e2011-06-16 04:16:24 +00001096 if (Dest.isZeroed() && CGF.getTypes().isZeroInitializable(type))
Chris Lattner1b726772010-12-02 07:07:26 +00001097 return;
1098
John McCall9d232c82013-03-07 21:37:08 +00001099 if (CGF.hasScalarEvaluationKind(type)) {
Richard Smith0dbe2fb2012-12-21 03:17:28 +00001100 // For non-aggregates, we can store the appropriate null constant.
1101 llvm::Value *null = CGF.CGM.EmitNullConstant(type);
Eli Friedmanb1e3f322012-02-22 05:38:59 +00001102 // Note that the following is not equivalent to
1103 // EmitStoreThroughBitfieldLValue for ARC types.
Eli Friedman5a13d4d2012-02-24 23:53:49 +00001104 if (lv.isBitField()) {
Eli Friedmanb1e3f322012-02-22 05:38:59 +00001105 CGF.EmitStoreThroughBitfieldLValue(RValue::get(null), lv);
Eli Friedman5a13d4d2012-02-24 23:53:49 +00001106 } else {
1107 assert(lv.isSimple());
1108 CGF.EmitStoreOfScalar(null, lv, /* isInitialization */ true);
1109 }
Lauro Ramos Venancio145cd892008-02-19 19:27:31 +00001110 } else {
Chris Lattnerf81557c2008-04-04 18:42:16 +00001111 // There's a potential optimization opportunity in combining
1112 // memsets; that would be easy for arrays, but relatively
1113 // difficult for structures with the current code.
John McCalla07398e2011-06-16 04:16:24 +00001114 CGF.EmitNullInitialization(lv.getAddress(), lv.getType());
Chris Lattnerf81557c2008-04-04 18:42:16 +00001115 }
1116}
1117
Chris Lattnerf81557c2008-04-04 18:42:16 +00001118void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
Eli Friedmana385b3c2008-12-02 01:17:45 +00001119#if 0
Eli Friedman13a5be12009-12-04 01:30:56 +00001120 // FIXME: Assess perf here? Figure out what cases are worth optimizing here
1121 // (Length of globals? Chunks of zeroed-out space?).
Eli Friedmana385b3c2008-12-02 01:17:45 +00001122 //
Mike Stumpf5408fe2009-05-16 07:57:57 +00001123 // If we can, prefer a copy from a global; this is a lot less code for long
1124 // globals, and it's easier for the current optimizers to analyze.
Eli Friedman13a5be12009-12-04 01:30:56 +00001125 if (llvm::Constant* C = CGF.CGM.EmitConstantExpr(E, E->getType(), &CGF)) {
Eli Friedman994ffef2008-11-30 02:11:09 +00001126 llvm::GlobalVariable* GV =
Eli Friedman13a5be12009-12-04 01:30:56 +00001127 new llvm::GlobalVariable(CGF.CGM.getModule(), C->getType(), true,
1128 llvm::GlobalValue::InternalLinkage, C, "");
John McCalle0c11682012-07-02 23:58:38 +00001129 EmitFinalDestCopy(E->getType(), CGF.MakeAddrLValue(GV, E->getType()));
Eli Friedman994ffef2008-11-30 02:11:09 +00001130 return;
1131 }
Eli Friedmana385b3c2008-12-02 01:17:45 +00001132#endif
Chris Lattnerd0db03a2010-09-06 00:11:41 +00001133 if (E->hadArrayRangeDesignator())
Douglas Gregora9c87802009-01-29 19:42:23 +00001134 CGF.ErrorUnsupported(E, "GNU array range designator extension");
Douglas Gregora9c87802009-01-29 19:42:23 +00001135
Richard Smithe69fb202013-05-23 21:54:14 +00001136 AggValueSlot Dest = EnsureSlot(E->getType());
1137
Eli Friedman377ecc72012-04-16 03:54:45 +00001138 LValue DestLV = CGF.MakeAddrLValue(Dest.getAddr(), E->getType(),
1139 Dest.getAlignment());
John McCall558d2ab2010-09-15 10:14:12 +00001140
Chris Lattnerf81557c2008-04-04 18:42:16 +00001141 // Handle initialization of an array.
1142 if (E->getType()->isArrayType()) {
Richard Smithfe587202012-04-15 02:50:59 +00001143 if (E->isStringLiteralInit())
1144 return Visit(E->getInit(0));
Eli Friedman922696f2008-05-19 17:51:16 +00001145
Eli Friedman5c89c392012-02-23 02:25:10 +00001146 QualType elementType =
1147 CGF.getContext().getAsArrayType(E->getType())->getElementType();
Argyrios Kyrtzidis3b4d4902011-04-28 18:53:58 +00001148
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001149 llvm::PointerType *APType =
Eli Friedman377ecc72012-04-16 03:54:45 +00001150 cast<llvm::PointerType>(Dest.getAddr()->getType());
Sebastian Redl32cf1f22012-02-17 08:42:25 +00001151 llvm::ArrayType *AType =
1152 cast<llvm::ArrayType>(APType->getElementType());
Chris Lattner1b726772010-12-02 07:07:26 +00001153
Eli Friedman377ecc72012-04-16 03:54:45 +00001154 EmitArrayInit(Dest.getAddr(), AType, elementType, E);
Chris Lattnerf81557c2008-04-04 18:42:16 +00001155 return;
1156 }
Mike Stump1eb44332009-09-09 15:08:12 +00001157
Chris Lattnerf81557c2008-04-04 18:42:16 +00001158 assert(E->getType()->isRecordType() && "Only support structs/unions here!");
Mike Stump1eb44332009-09-09 15:08:12 +00001159
Chris Lattnerf81557c2008-04-04 18:42:16 +00001160 // Do struct initialization; this code just sets each individual member
1161 // to the approprate value. This makes bitfield support automatic;
1162 // the disadvantage is that the generated code is more difficult for
1163 // the optimizer, especially with bitfields.
1164 unsigned NumInitElements = E->getNumInits();
John McCall2b30dcf2011-07-11 19:35:02 +00001165 RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
Richard Smithc3bf52c2013-04-20 22:23:05 +00001166
1167 // Prepare a 'this' for CXXDefaultInitExprs.
1168 CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddr());
1169
John McCall2b30dcf2011-07-11 19:35:02 +00001170 if (record->isUnion()) {
Douglas Gregor0bb76892009-01-29 16:53:55 +00001171 // Only initialize one field of a union. The field itself is
1172 // specified by the initializer list.
1173 if (!E->getInitializedFieldInUnion()) {
1174 // Empty union; we have nothing to do.
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Douglas Gregor0bb76892009-01-29 16:53:55 +00001176#ifndef NDEBUG
1177 // Make sure that it's really an empty and not a failure of
1178 // semantic analysis.
John McCall2b30dcf2011-07-11 19:35:02 +00001179 for (RecordDecl::field_iterator Field = record->field_begin(),
1180 FieldEnd = record->field_end();
Douglas Gregor0bb76892009-01-29 16:53:55 +00001181 Field != FieldEnd; ++Field)
1182 assert(Field->isUnnamedBitfield() && "Only unnamed bitfields allowed");
1183#endif
1184 return;
1185 }
1186
1187 // FIXME: volatility
1188 FieldDecl *Field = E->getInitializedFieldInUnion();
Douglas Gregor0bb76892009-01-29 16:53:55 +00001189
Eli Friedman377ecc72012-04-16 03:54:45 +00001190 LValue FieldLoc = CGF.EmitLValueForFieldInitialization(DestLV, Field);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001191 if (NumInitElements) {
1192 // Store the initializer into the field
Chad Rosier649b4a12012-03-29 17:37:10 +00001193 EmitInitializationToLValue(E->getInit(0), FieldLoc);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001194 } else {
Chris Lattner1b726772010-12-02 07:07:26 +00001195 // Default-initialize to null.
John McCalla07398e2011-06-16 04:16:24 +00001196 EmitNullInitializationToLValue(FieldLoc);
Douglas Gregor0bb76892009-01-29 16:53:55 +00001197 }
1198
1199 return;
1200 }
Mike Stump1eb44332009-09-09 15:08:12 +00001201
John McCall2b30dcf2011-07-11 19:35:02 +00001202 // We'll need to enter cleanup scopes in case any of the member
1203 // initializers throw an exception.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001204 SmallVector<EHScopeStack::stable_iterator, 16> cleanups;
John McCall6f103ba2011-11-10 10:43:54 +00001205 llvm::Instruction *cleanupDominator = 0;
John McCall2b30dcf2011-07-11 19:35:02 +00001206
Chris Lattnerf81557c2008-04-04 18:42:16 +00001207 // Here we iterate over the fields; this makes it simpler to both
1208 // default-initialize fields and skip over unnamed fields.
John McCall2b30dcf2011-07-11 19:35:02 +00001209 unsigned curInitIndex = 0;
1210 for (RecordDecl::field_iterator field = record->field_begin(),
1211 fieldEnd = record->field_end();
1212 field != fieldEnd; ++field) {
1213 // We're done once we hit the flexible array member.
1214 if (field->getType()->isIncompleteArrayType())
Douglas Gregor44b43212008-12-11 16:49:14 +00001215 break;
1216
John McCall2b30dcf2011-07-11 19:35:02 +00001217 // Always skip anonymous bitfields.
1218 if (field->isUnnamedBitfield())
Chris Lattnerf81557c2008-04-04 18:42:16 +00001219 continue;
Douglas Gregor34e79462009-01-28 23:36:17 +00001220
John McCall2b30dcf2011-07-11 19:35:02 +00001221 // We're done if we reach the end of the explicit initializers, we
1222 // have a zeroed object, and the rest of the fields are
1223 // zero-initializable.
1224 if (curInitIndex == NumInitElements && Dest.isZeroed() &&
Chris Lattner1b726772010-12-02 07:07:26 +00001225 CGF.getTypes().isZeroInitializable(E->getType()))
1226 break;
1227
Eli Friedman377ecc72012-04-16 03:54:45 +00001228
David Blaikie581deb32012-06-06 20:45:41 +00001229 LValue LV = CGF.EmitLValueForFieldInitialization(DestLV, *field);
Fariborz Jahanian14674ff2009-05-27 19:54:11 +00001230 // We never generate write-barries for initialized fields.
John McCall2b30dcf2011-07-11 19:35:02 +00001231 LV.setNonGC(true);
Chris Lattner1b726772010-12-02 07:07:26 +00001232
John McCall2b30dcf2011-07-11 19:35:02 +00001233 if (curInitIndex < NumInitElements) {
Chris Lattnerb35baae2010-03-08 21:08:07 +00001234 // Store the initializer into the field.
Chad Rosier649b4a12012-03-29 17:37:10 +00001235 EmitInitializationToLValue(E->getInit(curInitIndex++), LV);
Chris Lattnerf81557c2008-04-04 18:42:16 +00001236 } else {
1237 // We're out of initalizers; default-initialize to null
John McCall2b30dcf2011-07-11 19:35:02 +00001238 EmitNullInitializationToLValue(LV);
1239 }
1240
1241 // Push a destructor if necessary.
1242 // FIXME: if we have an array of structures, all explicitly
1243 // initialized, we can end up pushing a linear number of cleanups.
1244 bool pushedCleanup = false;
1245 if (QualType::DestructionKind dtorKind
1246 = field->getType().isDestructedType()) {
1247 assert(LV.isSimple());
1248 if (CGF.needsEHCleanup(dtorKind)) {
John McCall6f103ba2011-11-10 10:43:54 +00001249 if (!cleanupDominator)
1250 cleanupDominator = CGF.Builder.CreateUnreachable(); // placeholder
1251
John McCall2b30dcf2011-07-11 19:35:02 +00001252 CGF.pushDestroy(EHCleanup, LV.getAddress(), field->getType(),
1253 CGF.getDestroyer(dtorKind), false);
1254 cleanups.push_back(CGF.EHStack.stable_begin());
1255 pushedCleanup = true;
1256 }
Chris Lattnerf81557c2008-04-04 18:42:16 +00001257 }
Chris Lattner1b726772010-12-02 07:07:26 +00001258
1259 // If the GEP didn't get used because of a dead zero init or something
1260 // else, clean it up for -O0 builds and general tidiness.
John McCall2b30dcf2011-07-11 19:35:02 +00001261 if (!pushedCleanup && LV.isSimple())
Chris Lattner1b726772010-12-02 07:07:26 +00001262 if (llvm::GetElementPtrInst *GEP =
John McCall2b30dcf2011-07-11 19:35:02 +00001263 dyn_cast<llvm::GetElementPtrInst>(LV.getAddress()))
Chris Lattner1b726772010-12-02 07:07:26 +00001264 if (GEP->use_empty())
1265 GEP->eraseFromParent();
Lauro Ramos Venancio145cd892008-02-19 19:27:31 +00001266 }
John McCall2b30dcf2011-07-11 19:35:02 +00001267
1268 // Deactivate all the partial cleanups in reverse order, which
1269 // generally means popping them.
1270 for (unsigned i = cleanups.size(); i != 0; --i)
John McCall6f103ba2011-11-10 10:43:54 +00001271 CGF.DeactivateCleanupBlock(cleanups[i-1], cleanupDominator);
1272
1273 // Destroy the placeholder if we made one.
1274 if (cleanupDominator)
1275 cleanupDominator->eraseFromParent();
Devang Patel636c3d02007-10-26 17:44:44 +00001276}
1277
Chris Lattneree755f92007-08-21 04:59:27 +00001278//===----------------------------------------------------------------------===//
1279// Entry Points into this File
1280//===----------------------------------------------------------------------===//
1281
Chris Lattner1b726772010-12-02 07:07:26 +00001282/// GetNumNonZeroBytesInInit - Get an approximate count of the number of
1283/// non-zero bytes that will be stored when outputting the initializer for the
1284/// specified initializer expression.
Ken Dyck02c45332011-04-24 17:17:56 +00001285static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
Peter Collingbournef111d932011-04-15 00:35:48 +00001286 E = E->IgnoreParens();
Chris Lattner1b726772010-12-02 07:07:26 +00001287
1288 // 0 and 0.0 won't require any non-zero stores!
Ken Dyck02c45332011-04-24 17:17:56 +00001289 if (isSimpleZero(E, CGF)) return CharUnits::Zero();
Chris Lattner1b726772010-12-02 07:07:26 +00001290
1291 // If this is an initlist expr, sum up the size of sizes of the (present)
1292 // elements. If this is something weird, assume the whole thing is non-zero.
1293 const InitListExpr *ILE = dyn_cast<InitListExpr>(E);
1294 if (ILE == 0 || !CGF.getTypes().isZeroInitializable(ILE->getType()))
Ken Dyck02c45332011-04-24 17:17:56 +00001295 return CGF.getContext().getTypeSizeInChars(E->getType());
Chris Lattner1b726772010-12-02 07:07:26 +00001296
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001297 // InitListExprs for structs have to be handled carefully. If there are
1298 // reference members, we need to consider the size of the reference, not the
1299 // referencee. InitListExprs for unions and arrays can't have references.
Chris Lattner8c00ad12010-12-02 22:52:04 +00001300 if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
1301 if (!RT->isUnionType()) {
1302 RecordDecl *SD = E->getType()->getAs<RecordType>()->getDecl();
Ken Dyck02c45332011-04-24 17:17:56 +00001303 CharUnits NumNonZeroBytes = CharUnits::Zero();
Chris Lattner8c00ad12010-12-02 22:52:04 +00001304
1305 unsigned ILEElement = 0;
1306 for (RecordDecl::field_iterator Field = SD->field_begin(),
1307 FieldEnd = SD->field_end(); Field != FieldEnd; ++Field) {
1308 // We're done once we hit the flexible array member or run out of
1309 // InitListExpr elements.
1310 if (Field->getType()->isIncompleteArrayType() ||
1311 ILEElement == ILE->getNumInits())
1312 break;
1313 if (Field->isUnnamedBitfield())
1314 continue;
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001315
Chris Lattner8c00ad12010-12-02 22:52:04 +00001316 const Expr *E = ILE->getInit(ILEElement++);
1317
1318 // Reference values are always non-null and have the width of a pointer.
1319 if (Field->getType()->isReferenceType())
Ken Dyck02c45332011-04-24 17:17:56 +00001320 NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
John McCall64aa4b32013-04-16 22:48:15 +00001321 CGF.getTarget().getPointerWidth(0));
Chris Lattner8c00ad12010-12-02 22:52:04 +00001322 else
1323 NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
1324 }
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001325
Chris Lattner8c00ad12010-12-02 22:52:04 +00001326 return NumNonZeroBytes;
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001327 }
Chris Lattnerd1d56df2010-12-02 18:29:00 +00001328 }
1329
1330
Ken Dyck02c45332011-04-24 17:17:56 +00001331 CharUnits NumNonZeroBytes = CharUnits::Zero();
Chris Lattner1b726772010-12-02 07:07:26 +00001332 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1333 NumNonZeroBytes += GetNumNonZeroBytesInInit(ILE->getInit(i), CGF);
1334 return NumNonZeroBytes;
1335}
1336
1337/// CheckAggExprForMemSetUse - If the initializer is large and has a lot of
1338/// zeros in it, emit a memset and avoid storing the individual zeros.
1339///
1340static void CheckAggExprForMemSetUse(AggValueSlot &Slot, const Expr *E,
1341 CodeGenFunction &CGF) {
1342 // If the slot is already known to be zeroed, nothing to do. Don't mess with
1343 // volatile stores.
1344 if (Slot.isZeroed() || Slot.isVolatile() || Slot.getAddr() == 0) return;
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +00001345
1346 // C++ objects with a user-declared constructor don't need zero'ing.
Richard Smith7edf9e32012-11-01 22:30:59 +00001347 if (CGF.getLangOpts().CPlusPlus)
Argyrios Kyrtzidis657baf12011-04-28 22:57:55 +00001348 if (const RecordType *RT = CGF.getContext()
1349 .getBaseElementType(E->getType())->getAs<RecordType>()) {
1350 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1351 if (RD->hasUserDeclaredConstructor())
1352 return;
1353 }
1354
Chris Lattner1b726772010-12-02 07:07:26 +00001355 // If the type is 16-bytes or smaller, prefer individual stores over memset.
Ken Dyck5ff1a352011-04-24 17:25:32 +00001356 std::pair<CharUnits, CharUnits> TypeInfo =
1357 CGF.getContext().getTypeInfoInChars(E->getType());
1358 if (TypeInfo.first <= CharUnits::fromQuantity(16))
Chris Lattner1b726772010-12-02 07:07:26 +00001359 return;
1360
1361 // Check to see if over 3/4 of the initializer are known to be zero. If so,
1362 // we prefer to emit memset + individual stores for the rest.
Ken Dyck5ff1a352011-04-24 17:25:32 +00001363 CharUnits NumNonZeroBytes = GetNumNonZeroBytesInInit(E, CGF);
1364 if (NumNonZeroBytes*4 > TypeInfo.first)
Chris Lattner1b726772010-12-02 07:07:26 +00001365 return;
1366
1367 // Okay, it seems like a good idea to use an initial memset, emit the call.
Ken Dyck5ff1a352011-04-24 17:25:32 +00001368 llvm::Constant *SizeVal = CGF.Builder.getInt64(TypeInfo.first.getQuantity());
1369 CharUnits Align = TypeInfo.second;
Chris Lattner1b726772010-12-02 07:07:26 +00001370
1371 llvm::Value *Loc = Slot.getAddr();
Chris Lattner1b726772010-12-02 07:07:26 +00001372
Chris Lattner8b418682012-02-07 00:39:47 +00001373 Loc = CGF.Builder.CreateBitCast(Loc, CGF.Int8PtrTy);
Ken Dyck5ff1a352011-04-24 17:25:32 +00001374 CGF.Builder.CreateMemSet(Loc, CGF.Builder.getInt8(0), SizeVal,
1375 Align.getQuantity(), false);
Chris Lattner1b726772010-12-02 07:07:26 +00001376
1377 // Tell the AggExprEmitter that the slot is known zero.
1378 Slot.setZeroed();
1379}
1380
1381
1382
1383
Mike Stumpe1129a92009-05-26 18:57:45 +00001384/// EmitAggExpr - Emit the computation of the specified expression of aggregate
1385/// type. The result is computed into DestPtr. Note that if DestPtr is null,
1386/// the value of the aggregate expression is not needed. If VolatileDest is
1387/// true, DestPtr cannot be 0.
John McCalle0c11682012-07-02 23:58:38 +00001388void CodeGenFunction::EmitAggExpr(const Expr *E, AggValueSlot Slot) {
John McCall9d232c82013-03-07 21:37:08 +00001389 assert(E && hasAggregateEvaluationKind(E->getType()) &&
Chris Lattneree755f92007-08-21 04:59:27 +00001390 "Invalid aggregate expression to emit");
Chris Lattner1b726772010-12-02 07:07:26 +00001391 assert((Slot.getAddr() != 0 || Slot.isIgnored()) &&
1392 "slot has bits but no address");
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Chris Lattner1b726772010-12-02 07:07:26 +00001394 // Optimize the slot if possible.
1395 CheckAggExprForMemSetUse(Slot, E, *this);
1396
John McCalle0c11682012-07-02 23:58:38 +00001397 AggExprEmitter(*this, Slot).Visit(const_cast<Expr*>(E));
Chris Lattneree755f92007-08-21 04:59:27 +00001398}
Daniel Dunbar7482d122008-09-09 20:49:46 +00001399
Daniel Dunbar18aba0d2010-02-05 19:38:31 +00001400LValue CodeGenFunction::EmitAggExprToLValue(const Expr *E) {
John McCall9d232c82013-03-07 21:37:08 +00001401 assert(hasAggregateEvaluationKind(E->getType()) && "Invalid argument!");
Daniel Dunbar195337d2010-02-09 02:48:28 +00001402 llvm::Value *Temp = CreateMemTemp(E->getType());
Daniel Dunbar79c39282010-08-21 03:15:20 +00001403 LValue LV = MakeAddrLValue(Temp, E->getType());
John McCall7c2349b2011-08-25 20:40:09 +00001404 EmitAggExpr(E, AggValueSlot::forLValue(LV, AggValueSlot::IsNotDestructed,
John McCall44184392011-08-26 07:31:35 +00001405 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001406 AggValueSlot::IsNotAliased));
Daniel Dunbar79c39282010-08-21 03:15:20 +00001407 return LV;
Daniel Dunbar18aba0d2010-02-05 19:38:31 +00001408}
1409
Chad Rosier649b4a12012-03-29 17:37:10 +00001410void CodeGenFunction::EmitAggregateCopy(llvm::Value *DestPtr,
1411 llvm::Value *SrcPtr, QualType Ty,
John McCalle0c11682012-07-02 23:58:38 +00001412 bool isVolatile,
Benjamin Kramer6cacae82012-09-30 12:43:37 +00001413 CharUnits alignment,
1414 bool isAssignment) {
Chad Rosier649b4a12012-03-29 17:37:10 +00001415 assert(!Ty->isAnyComplexType() && "Shouldn't happen for complex");
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Richard Smith7edf9e32012-11-01 22:30:59 +00001417 if (getLangOpts().CPlusPlus) {
Chad Rosier649b4a12012-03-29 17:37:10 +00001418 if (const RecordType *RT = Ty->getAs<RecordType>()) {
1419 CXXRecordDecl *Record = cast<CXXRecordDecl>(RT->getDecl());
1420 assert((Record->hasTrivialCopyConstructor() ||
1421 Record->hasTrivialCopyAssignment() ||
1422 Record->hasTrivialMoveConstructor() ||
1423 Record->hasTrivialMoveAssignment()) &&
Richard Smith426391c2012-11-16 00:53:38 +00001424 "Trying to aggregate-copy a type without a trivial copy/move "
Douglas Gregore9979482010-05-20 15:39:01 +00001425 "constructor or assignment operator");
Chad Rosier649b4a12012-03-29 17:37:10 +00001426 // Ignore empty classes in C++.
1427 if (Record->isEmpty())
Anders Carlsson0d7c5832010-05-03 01:20:20 +00001428 return;
1429 }
1430 }
1431
Chris Lattner83c96292009-02-28 18:31:01 +00001432 // Aggregate assignment turns into llvm.memcpy. This is almost valid per
Chris Lattnerca4fc2c2009-02-28 18:18:58 +00001433 // C99 6.5.16.1p3, which states "If the value being stored in an object is
1434 // read from another object that overlaps in anyway the storage of the first
1435 // object, then the overlap shall be exact and the two objects shall have
1436 // qualified or unqualified versions of a compatible type."
1437 //
Chris Lattner83c96292009-02-28 18:31:01 +00001438 // memcpy is not defined if the source and destination pointers are exactly
Chris Lattnerca4fc2c2009-02-28 18:18:58 +00001439 // equal, but other compilers do this optimization, and almost every memcpy
1440 // implementation handles this case safely. If there is a libc that does not
1441 // safely handle this, we can add a target hook.
Chad Rosier649b4a12012-03-29 17:37:10 +00001442
Benjamin Kramer6cacae82012-09-30 12:43:37 +00001443 // Get data size and alignment info for this aggregate. If this is an
1444 // assignment don't copy the tail padding. Otherwise copying it is fine.
1445 std::pair<CharUnits, CharUnits> TypeInfo;
1446 if (isAssignment)
1447 TypeInfo = getContext().getTypeInfoDataSizeInChars(Ty);
1448 else
1449 TypeInfo = getContext().getTypeInfoInChars(Ty);
Chad Rosier649b4a12012-03-29 17:37:10 +00001450
John McCalle0c11682012-07-02 23:58:38 +00001451 if (alignment.isZero())
1452 alignment = TypeInfo.second;
Chad Rosier649b4a12012-03-29 17:37:10 +00001453
1454 // FIXME: Handle variable sized types.
1455
1456 // FIXME: If we have a volatile struct, the optimizer can remove what might
1457 // appear to be `extra' memory ops:
1458 //
1459 // volatile struct { int i; } a, b;
1460 //
1461 // int main() {
1462 // a = b;
1463 // a = b;
1464 // }
1465 //
1466 // we need to use a different call here. We use isVolatile to indicate when
1467 // either the source or the destination is volatile.
1468
1469 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
1470 llvm::Type *DBP =
1471 llvm::Type::getInt8PtrTy(getLLVMContext(), DPT->getAddressSpace());
1472 DestPtr = Builder.CreateBitCast(DestPtr, DBP);
1473
1474 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
1475 llvm::Type *SBP =
1476 llvm::Type::getInt8PtrTy(getLLVMContext(), SPT->getAddressSpace());
1477 SrcPtr = Builder.CreateBitCast(SrcPtr, SBP);
1478
1479 // Don't do any of the memmove_collectable tests if GC isn't set.
1480 if (CGM.getLangOpts().getGC() == LangOptions::NonGC) {
1481 // fall through
1482 } else if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
1483 RecordDecl *Record = RecordTy->getDecl();
1484 if (Record->hasObjectMember()) {
1485 CharUnits size = TypeInfo.first;
1486 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1487 llvm::Value *SizeVal = llvm::ConstantInt::get(SizeTy, size.getQuantity());
1488 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1489 SizeVal);
1490 return;
1491 }
1492 } else if (Ty->isArrayType()) {
1493 QualType BaseType = getContext().getBaseElementType(Ty);
1494 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
1495 if (RecordTy->getDecl()->hasObjectMember()) {
1496 CharUnits size = TypeInfo.first;
1497 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1498 llvm::Value *SizeVal =
1499 llvm::ConstantInt::get(SizeTy, size.getQuantity());
1500 CGM.getObjCRuntime().EmitGCMemmoveCollectable(*this, DestPtr, SrcPtr,
1501 SizeVal);
1502 return;
1503 }
1504 }
1505 }
Dan Gohmanb22c7dc2012-09-28 21:58:29 +00001506
1507 // Determine the metadata to describe the position of any padding in this
1508 // memcpy, as well as the TBAA tags for the members of the struct, in case
1509 // the optimizer wishes to expand it in to scalar memory operations.
1510 llvm::MDNode *TBAAStructTag = CGM.getTBAAStructInfo(Ty);
Fariborz Jahanian55bcace2010-06-15 22:44:06 +00001511
Chad Rosier649b4a12012-03-29 17:37:10 +00001512 Builder.CreateMemCpy(DestPtr, SrcPtr,
1513 llvm::ConstantInt::get(IntPtrTy,
1514 TypeInfo.first.getQuantity()),
Dan Gohmanb22c7dc2012-09-28 21:58:29 +00001515 alignment.getQuantity(), isVolatile,
1516 /*TBAATag=*/0, TBAAStructTag);
Daniel Dunbar7482d122008-09-09 20:49:46 +00001517}