blob: a688dbfacbc4966196e72ee0ade21a336e5b2df7 [file] [log] [blame]
Chris Lattnere47e4402007-06-01 18:02:12 +00001//===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnere47e4402007-06-01 18:02:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
John McCall5d865c322010-08-31 07:33:07 +000015#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CGCall.h"
Devang Pateld3a6b0f2011-03-04 18:54:42 +000017#include "CGDebugInfo.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "CGRecordLayout.h"
20#include "CodeGenModule.h"
John McCallcbc038a2011-09-21 08:08:30 +000021#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000022#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000023#include "clang/AST/DeclObjC.h"
Chandler Carruth85098242010-06-15 23:19:56 +000024#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "llvm/ADT/Hashing.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Intrinsics.h"
28#include "llvm/IR/LLVMContext.h"
29#include "llvm/IR/MDBuilder.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000030#include "llvm/Support/ConvertUTF.h"
31
Chris Lattnere47e4402007-06-01 18:02:12 +000032using namespace clang;
33using namespace CodeGen;
34
Chris Lattnerd7f58862007-06-02 05:24:33 +000035//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000036// Miscellaneous Helper Methods
37//===--------------------------------------------------------------------===//
38
John McCallad7c5c12011-02-08 08:22:06 +000039llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
40 unsigned addressSpace =
41 cast<llvm::PointerType>(value->getType())->getAddressSpace();
42
Chris Lattner2192fe52011-07-18 04:24:23 +000043 llvm::PointerType *destType = Int8PtrTy;
John McCallad7c5c12011-02-08 08:22:06 +000044 if (addressSpace)
45 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
46
47 if (value->getType() == destType) return value;
48 return Builder.CreateBitCast(value, destType);
49}
50
Chris Lattnere9a64532007-06-22 21:44:33 +000051/// CreateTempAlloca - This creates a alloca and inserts it into the entry
52/// block.
Chris Lattner2192fe52011-07-18 04:24:23 +000053llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000054 const Twine &Name) {
Chris Lattner47640222009-03-22 00:24:14 +000055 if (!Builder.isNamePreserving())
Daniel Dunbarb5aacc22009-10-19 01:21:05 +000056 return new llvm::AllocaInst(Ty, 0, "", AllocaInsertPt);
Devang Pateldac79de2009-10-12 22:29:02 +000057 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +000058}
Chris Lattner8394d792007-06-05 20:53:16 +000059
John McCall2e6567a2010-04-22 01:10:34 +000060void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var,
61 llvm::Value *Init) {
62 llvm::StoreInst *Store = new llvm::StoreInst(Init, Var);
63 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
64 Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
65}
66
Chris Lattnerc401de92010-07-05 20:21:00 +000067llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000068 const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +000069 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name);
70 // FIXME: Should we prefer the preferred type alignment here?
71 CharUnits Align = getContext().getTypeAlignInChars(Ty);
72 Alloc->setAlignment(Align.getQuantity());
73 return Alloc;
74}
75
Chris Lattnerc401de92010-07-05 20:21:00 +000076llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000077 const Twine &Name) {
Daniel Dunbara7566f12010-02-09 02:48:28 +000078 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name);
79 // FIXME: Should we prefer the preferred type alignment here?
80 CharUnits Align = getContext().getTypeAlignInChars(Ty);
81 Alloc->setAlignment(Align.getQuantity());
82 return Alloc;
83}
84
Chris Lattner8394d792007-06-05 20:53:16 +000085/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
86/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +000087llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
John McCall7a9aac22010-08-23 01:21:21 +000088 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +000089 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +000090 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +000091 }
John McCall7a9aac22010-08-23 01:21:21 +000092
93 QualType BoolTy = getContext().BoolTy;
Chris Lattnerf3bc75a2008-04-04 16:54:41 +000094 if (!E->getType()->isAnyComplexType())
Chris Lattner268fcce2007-08-26 16:46:58 +000095 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
Chris Lattner8394d792007-06-05 20:53:16 +000096
Chris Lattner268fcce2007-08-26 16:46:58 +000097 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
Chris Lattnerf0106d22007-06-02 19:33:17 +000098}
99
John McCalla2342eb2010-12-05 02:00:02 +0000100/// EmitIgnoredExpr - Emit code to compute the specified expression,
101/// ignoring the result.
102void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
103 if (E->isRValue())
104 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
105
106 // Just emit it as an l-value and drop the result.
107 EmitLValue(E);
108}
109
John McCall7a626f62010-09-15 10:14:12 +0000110/// EmitAnyExpr - Emit code to compute the specified expression which
111/// can have any type. The result is returned as an RValue struct.
112/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000113/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000114RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
115 AggValueSlot aggSlot,
116 bool ignoreResult) {
Chris Lattner4647a212007-08-31 22:49:20 +0000117 if (!hasAggregateLLVMType(E->getType()))
John McCall4e8ca4f2012-07-02 23:58:38 +0000118 return RValue::get(EmitScalarExpr(E, ignoreResult));
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000119 else if (E->getType()->isAnyComplexType())
John McCall4e8ca4f2012-07-02 23:58:38 +0000120 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
Mike Stump4a3999f2009-09-09 13:00:44 +0000121
John McCall4e8ca4f2012-07-02 23:58:38 +0000122 if (!ignoreResult && aggSlot.isIgnored())
123 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
124 EmitAggExpr(E, aggSlot);
125 return aggSlot.asRValue();
Chris Lattner4647a212007-08-31 22:49:20 +0000126}
127
Mike Stump4a3999f2009-09-09 13:00:44 +0000128/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
129/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000130RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
131 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000132
133 if (hasAggregateLLVMType(E->getType()) &&
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000134 !E->getType()->isAnyComplexType())
John McCall7a626f62010-09-15 10:14:12 +0000135 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
136 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000137}
138
John McCall21886962010-04-21 10:05:39 +0000139/// EmitAnyExprToMem - Evaluate an expression into a given memory
140/// location.
141void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
142 llvm::Value *Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000143 Qualifiers Quals,
144 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000145 // FIXME: This function should take an LValue as an argument.
146 if (E->getType()->isAnyComplexType()) {
John McCall31168b02011-06-15 23:02:42 +0000147 EmitComplexExprIntoAddr(E, Location, Quals.hasVolatile());
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000148 } else if (hasAggregateLLVMType(E->getType())) {
Eli Friedman38cd36d2011-12-03 02:13:40 +0000149 CharUnits Alignment = getContext().getTypeAlignInChars(E->getType());
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000150 EmitAggExpr(E, AggValueSlot::forAddr(Location, Alignment, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000151 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000152 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000153 AggValueSlot::IsAliased_t(!IsInit)));
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000154 } else {
John McCall21886962010-04-21 10:05:39 +0000155 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000156 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000157 EmitStoreThroughLValue(RV, LV);
John McCall21886962010-04-21 10:05:39 +0000158 }
159}
160
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000161static llvm::Value *
Chris Lattner24516962011-07-20 04:59:57 +0000162CreateReferenceTemporary(CodeGenFunction &CGF, QualType Type,
Anders Carlsson18c205e2010-06-27 17:23:46 +0000163 const NamedDecl *InitializedDecl) {
164 if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
165 if (VD->hasGlobalStorage()) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000166 SmallString<256> Name;
Rafael Espindola3968cd02011-02-11 02:52:17 +0000167 llvm::raw_svector_ostream Out(Name);
168 CGF.CGM.getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
169 Out.flush();
170
Chris Lattner2192fe52011-07-18 04:24:23 +0000171 llvm::Type *RefTempTy = CGF.ConvertTypeForMem(Type);
Anders Carlsson18c205e2010-06-27 17:23:46 +0000172
173 // Create the reference temporary.
174 llvm::GlobalValue *RefTemp =
175 new llvm::GlobalVariable(CGF.CGM.getModule(),
176 RefTempTy, /*isConstant=*/false,
177 llvm::GlobalValue::InternalLinkage,
178 llvm::Constant::getNullValue(RefTempTy),
179 Name.str());
180 return RefTemp;
181 }
182 }
183
184 return CGF.CreateMemTemp(Type, "ref.tmp");
185}
186
187static llvm::Value *
Chris Lattnerf53c0962010-09-06 00:11:41 +0000188EmitExprForReferenceBinding(CodeGenFunction &CGF, const Expr *E,
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000189 llvm::Value *&ReferenceTemporary,
190 const CXXDestructorDecl *&ReferenceTemporaryDtor,
John McCall31168b02011-06-15 23:02:42 +0000191 QualType &ObjCARCReferenceLifetimeType,
Anders Carlsson18c205e2010-06-27 17:23:46 +0000192 const NamedDecl *InitializedDecl) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000193 const MaterializeTemporaryExpr *M = NULL;
Rafael Espindola9c006de2012-10-27 01:03:43 +0000194 E = E->findMaterializedTemporary(M);
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000195 // Objective-C++ ARC:
196 // If we are binding a reference to a temporary that has ownership, we
197 // need to perform retain/release operations on the temporary.
Richard Smith9c6890a2012-11-01 22:30:59 +0000198 if (M && CGF.getLangOpts().ObjCAutoRefCount &&
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000199 M->getType()->isObjCLifetimeType() &&
200 (M->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
201 M->getType().getObjCLifetime() == Qualifiers::OCL_Weak ||
202 M->getType().getObjCLifetime() == Qualifiers::OCL_Autoreleasing))
203 ObjCARCReferenceLifetimeType = M->getType();
Sebastian Redl29526f02011-11-27 16:50:07 +0000204
John McCall08ef4662011-11-10 08:15:53 +0000205 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(E)) {
206 CGF.enterFullExpression(EWC);
John McCallbd309292010-07-06 01:34:17 +0000207 CodeGenFunction::RunCleanupsScope Scope(CGF);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000208
John McCall08ef4662011-11-10 08:15:53 +0000209 return EmitExprForReferenceBinding(CGF, EWC->getSubExpr(),
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000210 ReferenceTemporary,
211 ReferenceTemporaryDtor,
John McCall31168b02011-06-15 23:02:42 +0000212 ObjCARCReferenceLifetimeType,
Anders Carlsson18c205e2010-06-27 17:23:46 +0000213 InitializedDecl);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000214 }
215
216 RValue RV;
Douglas Gregor9c399a22011-01-22 02:44:21 +0000217 if (E->isGLValue()) {
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000218 // Emit the expression as an lvalue.
219 LValue LV = CGF.EmitLValue(E);
Chris Lattner13ee4f42011-07-10 05:34:54 +0000220
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000221 if (LV.isSimple())
222 return LV.getAddress();
Anders Carlsson824e0612010-02-04 17:32:58 +0000223
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000224 // We have to load the lvalue.
John McCall55e1fbc2011-06-25 02:11:03 +0000225 RV = CGF.EmitLoadOfLValue(LV);
Eli Friedmanc21cb442009-05-20 02:31:19 +0000226 } else {
Douglas Gregor58df5092011-06-22 16:12:01 +0000227 if (!ObjCARCReferenceLifetimeType.isNull()) {
228 ReferenceTemporary = CreateReferenceTemporary(CGF,
229 ObjCARCReferenceLifetimeType,
230 InitializedDecl);
231
232
233 LValue RefTempDst = CGF.MakeAddrLValue(ReferenceTemporary,
234 ObjCARCReferenceLifetimeType);
235
236 CGF.EmitScalarInit(E, dyn_cast_or_null<ValueDecl>(InitializedDecl),
237 RefTempDst, false);
238
239 bool ExtendsLifeOfTemporary = false;
240 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
241 if (Var->extendsLifetimeOfTemporary())
242 ExtendsLifeOfTemporary = true;
243 } else if (InitializedDecl && isa<FieldDecl>(InitializedDecl)) {
244 ExtendsLifeOfTemporary = true;
245 }
246
247 if (!ExtendsLifeOfTemporary) {
248 // Since the lifetime of this temporary isn't going to be extended,
249 // we need to clean it up ourselves at the end of the full expression.
250 switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
251 case Qualifiers::OCL_None:
252 case Qualifiers::OCL_ExplicitNone:
253 case Qualifiers::OCL_Autoreleasing:
254 break;
255
John McCall4bd0fb12011-07-12 16:41:08 +0000256 case Qualifiers::OCL_Strong: {
257 assert(!ObjCARCReferenceLifetimeType->isArrayType());
258 CleanupKind cleanupKind = CGF.getARCCleanupKind();
259 CGF.pushDestroy(cleanupKind,
260 ReferenceTemporary,
261 ObjCARCReferenceLifetimeType,
262 CodeGenFunction::destroyARCStrongImprecise,
263 cleanupKind & EHCleanup);
Douglas Gregor58df5092011-06-22 16:12:01 +0000264 break;
John McCall4bd0fb12011-07-12 16:41:08 +0000265 }
Douglas Gregor58df5092011-06-22 16:12:01 +0000266
267 case Qualifiers::OCL_Weak:
John McCall4bd0fb12011-07-12 16:41:08 +0000268 assert(!ObjCARCReferenceLifetimeType->isArrayType());
269 CGF.pushDestroy(NormalAndEHCleanup,
270 ReferenceTemporary,
271 ObjCARCReferenceLifetimeType,
272 CodeGenFunction::destroyARCWeak,
273 /*useEHCleanupForArray*/ true);
Douglas Gregor58df5092011-06-22 16:12:01 +0000274 break;
275 }
276
277 ObjCARCReferenceLifetimeType = QualType();
278 }
279
280 return ReferenceTemporary;
281 }
Rafael Espindolab4136762012-10-27 00:40:06 +0000282
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000283 SmallVector<SubobjectAdjustment, 2> Adjustments;
Rafael Espindola9c006de2012-10-27 01:03:43 +0000284 E = E->skipRValueSubobjectAdjustments(Adjustments);
Rafael Espindolab4136762012-10-27 00:40:06 +0000285 if (const OpaqueValueExpr *opaque = dyn_cast<OpaqueValueExpr>(E))
286 if (opaque->getType()->isRecordType())
287 return CGF.EmitOpaqueValueLValue(opaque).getAddress();
Douglas Gregoraae38d62010-05-22 05:17:18 +0000288
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000289 // Create a reference temporary if necessary.
John McCall7a626f62010-09-15 10:14:12 +0000290 AggValueSlot AggSlot = AggValueSlot::ignored();
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000291 if (CGF.hasAggregateLLVMType(E->getType()) &&
John McCall7a626f62010-09-15 10:14:12 +0000292 !E->getType()->isAnyComplexType()) {
Anders Carlsson18c205e2010-06-27 17:23:46 +0000293 ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
294 InitializedDecl);
Eli Friedman38cd36d2011-12-03 02:13:40 +0000295 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(E->getType());
John McCall8d6fc952011-08-25 20:40:09 +0000296 AggValueSlot::IsDestructed_t isDestructed
297 = AggValueSlot::IsDestructed_t(InitializedDecl != 0);
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000298 AggSlot = AggValueSlot::forAddr(ReferenceTemporary, Alignment,
299 Qualifiers(), isDestructed,
John McCalla5efa732011-08-25 23:04:34 +0000300 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000301 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000302 }
John McCall31168b02011-06-15 23:02:42 +0000303
Anders Carlsson18c205e2010-06-27 17:23:46 +0000304 if (InitializedDecl) {
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000305 // Get the destructor for the reference temporary.
Richard Smithd712d0d2013-02-02 01:13:06 +0000306 if (const RecordType *RT =
307 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000308 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
309 if (!ClassDecl->hasTrivialDestructor())
Douglas Gregorbac74902010-07-01 14:13:13 +0000310 ReferenceTemporaryDtor = ClassDecl->getDestructor();
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000311 }
312 }
313
John McCall31168b02011-06-15 23:02:42 +0000314 RV = CGF.EmitAnyExpr(E, AggSlot);
315
Douglas Gregor7c38f152010-05-20 08:36:28 +0000316 // Check if need to perform derived-to-base casts and/or field accesses, to
317 // get from the temporary object we created (and, potentially, for which we
318 // extended the lifetime) to the subobject we're binding the reference to.
319 if (!Adjustments.empty()) {
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000320 llvm::Value *Object = RV.getAggregateAddr();
Douglas Gregor7c38f152010-05-20 08:36:28 +0000321 for (unsigned I = Adjustments.size(); I != 0; --I) {
322 SubobjectAdjustment &Adjustment = Adjustments[I-1];
323 switch (Adjustment.Kind) {
324 case SubobjectAdjustment::DerivedToBaseAdjustment:
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000325 Object =
326 CGF.GetAddressOfBaseClass(Object,
327 Adjustment.DerivedToBase.DerivedClass,
John McCallcf142162010-08-07 06:22:56 +0000328 Adjustment.DerivedToBase.BasePath->path_begin(),
329 Adjustment.DerivedToBase.BasePath->path_end(),
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000330 /*NullCheckValue=*/false);
Douglas Gregor7c38f152010-05-20 08:36:28 +0000331 break;
332
333 case SubobjectAdjustment::FieldAdjustment: {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000334 LValue LV = CGF.MakeAddrLValue(Object, E->getType());
335 LV = CGF.EmitLValueForField(LV, Adjustment.Field);
Douglas Gregor7c38f152010-05-20 08:36:28 +0000336 if (LV.isSimple()) {
337 Object = LV.getAddress();
338 break;
339 }
340
341 // For non-simple lvalues, we actually have to create a copy of
342 // the object we're binding to.
Daniel Dunbare8b6cda2010-08-21 03:37:02 +0000343 QualType T = Adjustment.Field->getType().getNonReferenceType()
344 .getUnqualifiedType();
Anders Carlsson3f48c602010-06-27 17:52:15 +0000345 Object = CreateReferenceTemporary(CGF, T, InitializedDecl);
Daniel Dunbare8b6cda2010-08-21 03:37:02 +0000346 LValue TempLV = CGF.MakeAddrLValue(Object,
347 Adjustment.Field->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000348 CGF.EmitStoreThroughLValue(CGF.EmitLoadOfLValue(LV), TempLV);
Douglas Gregor7c38f152010-05-20 08:36:28 +0000349 break;
350 }
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000351
Eli Friedman13ffdd82012-06-15 23:51:06 +0000352 case SubobjectAdjustment::MemberPointerAdjustment: {
Rafael Espindolae7b11f52012-10-27 00:36:38 +0000353 llvm::Value *Ptr = CGF.EmitScalarExpr(Adjustment.Ptr.RHS);
Eli Friedman13ffdd82012-06-15 23:51:06 +0000354 Object = CGF.CGM.getCXXABI().EmitMemberDataPointerAddress(
Rafael Espindolae7b11f52012-10-27 00:36:38 +0000355 CGF, Object, Ptr, Adjustment.Ptr.MPT);
Eli Friedman13ffdd82012-06-15 23:51:06 +0000356 break;
357 }
Douglas Gregor7c38f152010-05-20 08:36:28 +0000358 }
359 }
Eli Friedmanb6069252011-03-16 22:34:09 +0000360
361 return Object;
Anders Carlsson66413c22009-10-15 00:51:46 +0000362 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000363 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000364
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000365 if (RV.isAggregate())
366 return RV.getAggregateAddr();
Eli Friedmanc21cb442009-05-20 02:31:19 +0000367
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000368 // Create a temporary variable that we can bind the reference to.
Anders Carlsson18c205e2010-06-27 17:23:46 +0000369 ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
370 InitializedDecl);
371
Daniel Dunbar03816342010-08-21 02:24:36 +0000372
373 unsigned Alignment =
374 CGF.getContext().getTypeAlignInChars(E->getType()).getQuantity();
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000375 if (RV.isScalar())
376 CGF.EmitStoreOfScalar(RV.getScalarVal(), ReferenceTemporary,
Daniel Dunbar03816342010-08-21 02:24:36 +0000377 /*Volatile=*/false, Alignment, E->getType());
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000378 else
379 CGF.StoreComplexToAddr(RV.getComplexVal(), ReferenceTemporary,
380 /*Volatile=*/false);
381 return ReferenceTemporary;
382}
383
384RValue
Chris Lattnerf53c0962010-09-06 00:11:41 +0000385CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E,
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000386 const NamedDecl *InitializedDecl) {
387 llvm::Value *ReferenceTemporary = 0;
388 const CXXDestructorDecl *ReferenceTemporaryDtor = 0;
John McCall31168b02011-06-15 23:02:42 +0000389 QualType ObjCARCReferenceLifetimeType;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000390 llvm::Value *Value = EmitExprForReferenceBinding(*this, E, ReferenceTemporary,
391 ReferenceTemporaryDtor,
John McCall31168b02011-06-15 23:02:42 +0000392 ObjCARCReferenceLifetimeType,
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000393 InitializedDecl);
Richard Smithb1b0ab42012-11-05 22:21:05 +0000394 if (SanitizePerformTypeCheck && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000395 // C++11 [dcl.ref]p5 (as amended by core issue 453):
396 // If a glvalue to which a reference is directly bound designates neither
397 // an existing object or function of an appropriate type nor a region of
398 // storage of suitable size and alignment to contain an object of the
399 // reference's type, the behavior is undefined.
400 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000401 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000402 }
John McCall31168b02011-06-15 23:02:42 +0000403 if (!ReferenceTemporaryDtor && ObjCARCReferenceLifetimeType.isNull())
Anders Carlsson3f48c602010-06-27 17:52:15 +0000404 return RValue::get(Value);
405
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000406 // Make sure to call the destructor for the reference temporary.
John McCall31168b02011-06-15 23:02:42 +0000407 const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl);
408 if (VD && VD->hasGlobalStorage()) {
409 if (ReferenceTemporaryDtor) {
Richard Smithd712d0d2013-02-02 01:13:06 +0000410 llvm::Constant *CleanupFn;
411 llvm::Constant *CleanupArg;
412 if (E->getType()->isArrayType()) {
413 CleanupFn = CodeGenFunction(CGM).generateDestroyHelper(
414 cast<llvm::Constant>(ReferenceTemporary), E->getType(),
415 destroyCXXObject, getLangOpts().Exceptions);
416 CleanupArg = llvm::Constant::getNullValue(Int8PtrTy);
417 } else {
418 CleanupFn =
419 CGM.GetAddrOfCXXDestructor(ReferenceTemporaryDtor, Dtor_Complete);
420 CleanupArg = cast<llvm::Constant>(ReferenceTemporary);
421 }
422 CGM.getCXXABI().registerGlobalDtor(*this, CleanupFn, CleanupArg);
John McCall31168b02011-06-15 23:02:42 +0000423 } else {
424 assert(!ObjCARCReferenceLifetimeType.isNull());
425 // Note: We intentionally do not register a global "destructor" to
426 // release the object.
Anders Carlsson3f48c602010-06-27 17:52:15 +0000427 }
John McCall31168b02011-06-15 23:02:42 +0000428
429 return RValue::get(Value);
Anders Carlsson3f48c602010-06-27 17:52:15 +0000430 }
John McCall8680f872010-07-21 06:29:51 +0000431
Richard Smithd712d0d2013-02-02 01:13:06 +0000432 if (ReferenceTemporaryDtor) {
433 if (E->getType()->isArrayType())
434 pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
435 destroyCXXObject, getLangOpts().Exceptions);
436 else
437 PushDestructorCleanup(ReferenceTemporaryDtor, ReferenceTemporary);
438 } else {
John McCall31168b02011-06-15 23:02:42 +0000439 switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
440 case Qualifiers::OCL_None:
David Blaikie83d382b2011-09-23 05:06:16 +0000441 llvm_unreachable(
442 "Not a reference temporary that needs to be deallocated");
John McCall31168b02011-06-15 23:02:42 +0000443 case Qualifiers::OCL_ExplicitNone:
444 case Qualifiers::OCL_Autoreleasing:
445 // Nothing to do.
446 break;
447
John McCall4bd0fb12011-07-12 16:41:08 +0000448 case Qualifiers::OCL_Strong: {
449 bool precise = VD && VD->hasAttr<ObjCPreciseLifetimeAttr>();
450 CleanupKind cleanupKind = getARCCleanupKind();
Benjamin Kramerae2d3442011-07-12 18:37:23 +0000451 pushDestroy(cleanupKind, ReferenceTemporary, ObjCARCReferenceLifetimeType,
Peter Collingbourne1425b452012-01-26 03:33:36 +0000452 precise ? destroyARCStrongPrecise : destroyARCStrongImprecise,
453 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000454 break;
John McCall4bd0fb12011-07-12 16:41:08 +0000455 }
John McCall31168b02011-06-15 23:02:42 +0000456
Benjamin Kramerae2d3442011-07-12 18:37:23 +0000457 case Qualifiers::OCL_Weak: {
John McCall31168b02011-06-15 23:02:42 +0000458 // __weak objects always get EH cleanups; otherwise, exceptions
459 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000460 pushDestroy(NormalAndEHCleanup, ReferenceTemporary,
Peter Collingbourne1425b452012-01-26 03:33:36 +0000461 ObjCARCReferenceLifetimeType, destroyARCWeak, true);
John McCall31168b02011-06-15 23:02:42 +0000462 break;
463 }
Benjamin Kramerae2d3442011-07-12 18:37:23 +0000464 }
John McCall31168b02011-06-15 23:02:42 +0000465 }
466
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000467 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000468}
469
470
Mike Stump4a3999f2009-09-09 13:00:44 +0000471/// getAccessedFieldNo - Given an encoded value and a result number, return the
472/// input field number being accessed.
473unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000474 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000475 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
476 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000477}
478
Richard Smith4d3110a2012-10-25 02:14:12 +0000479/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
480static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
481 llvm::Value *High) {
482 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
483 llvm::Value *K47 = Builder.getInt64(47);
484 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
485 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
486 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
487 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
488 return Builder.CreateMul(B1, KMul);
489}
490
Richard Smithe30752c2012-10-09 19:52:38 +0000491void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
492 llvm::Value *Address,
Richard Smith4d1458e2012-09-08 02:08:36 +0000493 QualType Ty, CharUnits Alignment) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000494 if (!SanitizePerformTypeCheck)
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000495 return;
496
Richard Smith2d8b2942012-11-01 07:22:08 +0000497 // Don't check pointers outside the default address space. The null check
498 // isn't correct, the object-size check isn't supported by LLVM, and we can't
499 // communicate the addresses to the runtime handler for the vptr check.
500 if (Address->getType()->getPointerAddressSpace())
501 return;
502
Richard Smith69d0d262012-08-24 00:54:33 +0000503 llvm::Value *Cond = 0;
Richard Smith2c5868c2013-02-13 21:18:23 +0000504 llvm::BasicBlock *Done = 0;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000505
Will Dietzf54319c2013-01-18 11:30:38 +0000506 if (SanOpts->Null) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000507 // The glvalue must not be an empty glvalue.
508 Cond = Builder.CreateICmpNE(
509 Address, llvm::Constant::getNullValue(Address->getType()));
Richard Smith2c5868c2013-02-13 21:18:23 +0000510
511 if (TCK == TCK_DowncastPointer) {
512 // When performing a pointer downcast, it's OK if the value is null.
513 // Skip the remaining checks in that case.
514 Done = createBasicBlock("null");
515 llvm::BasicBlock *Rest = createBasicBlock("not.null");
516 Builder.CreateCondBr(Cond, Rest, Done);
517 EmitBlock(Rest);
518 Cond = 0;
519 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000520 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000521
Will Dietzf54319c2013-01-18 11:30:38 +0000522 if (SanOpts->ObjectSize && !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000523 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000524
Richard Smith69d0d262012-08-24 00:54:33 +0000525 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000526 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000527 // to check this.
528 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, IntPtrTy);
529 llvm::Value *Min = Builder.getFalse();
Richard Smith2d8b2942012-11-01 07:22:08 +0000530 llvm::Value *CastAddr = Builder.CreateBitCast(Address, Int8PtrTy);
Richard Smith69d0d262012-08-24 00:54:33 +0000531 llvm::Value *LargeEnough =
Richard Smith2d8b2942012-11-01 07:22:08 +0000532 Builder.CreateICmpUGE(Builder.CreateCall2(F, CastAddr, Min),
Richard Smith69d0d262012-08-24 00:54:33 +0000533 llvm::ConstantInt::get(IntPtrTy, Size));
534 Cond = Cond ? Builder.CreateAnd(Cond, LargeEnough) : LargeEnough;
Richard Smithe30752c2012-10-09 19:52:38 +0000535 }
Richard Smith69d0d262012-08-24 00:54:33 +0000536
Richard Smithb1b0ab42012-11-05 22:21:05 +0000537 uint64_t AlignVal = 0;
538
Will Dietzf54319c2013-01-18 11:30:38 +0000539 if (SanOpts->Alignment) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000540 AlignVal = Alignment.getQuantity();
541 if (!Ty->isIncompleteType() && !AlignVal)
542 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
543
Richard Smith69d0d262012-08-24 00:54:33 +0000544 // The glvalue must be suitably aligned.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000545 if (AlignVal) {
546 llvm::Value *Align =
547 Builder.CreateAnd(Builder.CreatePtrToInt(Address, IntPtrTy),
548 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
549 llvm::Value *Aligned =
550 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
551 Cond = Cond ? Builder.CreateAnd(Cond, Aligned) : Aligned;
552 }
Richard Smith69d0d262012-08-24 00:54:33 +0000553 }
554
Richard Smithe30752c2012-10-09 19:52:38 +0000555 if (Cond) {
556 llvm::Constant *StaticData[] = {
557 EmitCheckSourceLocation(Loc),
558 EmitCheckTypeDescriptor(Ty),
559 llvm::ConstantInt::get(SizeTy, AlignVal),
560 llvm::ConstantInt::get(Int8Ty, TCK)
561 };
Will Dietz88e02332012-12-02 19:50:33 +0000562 EmitCheck(Cond, "type_mismatch", StaticData, Address, CRK_Recoverable);
Richard Smithe30752c2012-10-09 19:52:38 +0000563 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000564
Richard Smithb1b0ab42012-11-05 22:21:05 +0000565 // If possible, check that the vptr indicates that there is a subobject of
566 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000567 //
568 // C++11 [basic.life]p5,6:
569 // [For storage which does not refer to an object within its lifetime]
570 // The program has undefined behavior if:
571 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000572 // or call a non-static member function
Richard Smith4d3110a2012-10-25 02:14:12 +0000573 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Will Dietzf54319c2013-01-18 11:30:38 +0000574 if (SanOpts->Vptr &&
Richard Smith2c5868c2013-02-13 21:18:23 +0000575 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
576 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference) &&
Richard Smith4d3110a2012-10-25 02:14:12 +0000577 RD && RD->hasDefinition() && RD->isDynamicClass()) {
Richard Smith4d3110a2012-10-25 02:14:12 +0000578 // Compute a hash of the mangled name of the type.
579 //
580 // FIXME: This is not guaranteed to be deterministic! Move to a
581 // fingerprinting mechanism once LLVM provides one. For the time
582 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000583 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000584 llvm::raw_svector_ostream Out(MangledName);
585 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
586 Out);
587 llvm::hash_code TypeHash = hash_value(Out.str());
588
589 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
590 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
591 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
592 llvm::Value *VPtrAddr = Builder.CreateBitCast(Address, VPtrTy);
593 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
594 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
595
596 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
597 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
598
599 // Look the hash up in our cache.
600 const int CacheSize = 128;
601 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
602 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
603 "__ubsan_vptr_type_cache");
604 llvm::Value *Slot = Builder.CreateAnd(Hash,
605 llvm::ConstantInt::get(IntPtrTy,
606 CacheSize-1));
607 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
608 llvm::Value *CacheVal =
609 Builder.CreateLoad(Builder.CreateInBoundsGEP(Cache, Indices));
610
611 // If the hash isn't in the cache, call a runtime handler to perform the
612 // hard work of checking whether the vptr is for an object of the right
613 // type. This will either fill in the cache and return, or produce a
614 // diagnostic.
615 llvm::Constant *StaticData[] = {
616 EmitCheckSourceLocation(Loc),
617 EmitCheckTypeDescriptor(Ty),
618 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
619 llvm::ConstantInt::get(Int8Ty, TCK)
620 };
621 llvm::Value *DynamicData[] = { Address, Hash };
622 EmitCheck(Builder.CreateICmpEQ(CacheVal, Hash),
Will Dietz88e02332012-12-02 19:50:33 +0000623 "dynamic_type_cache_miss", StaticData, DynamicData,
624 CRK_AlwaysRecoverable);
Richard Smith4d3110a2012-10-25 02:14:12 +0000625 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000626
627 if (Done) {
628 Builder.CreateBr(Done);
629 EmitBlock(Done);
630 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000631}
Chris Lattner4647a212007-08-31 22:49:20 +0000632
Richard Smith539e4a72013-02-23 02:53:19 +0000633/// Determine whether this expression refers to a flexible array member in a
634/// struct. We disable array bounds checks for such members.
635static bool isFlexibleArrayMemberExpr(const Expr *E) {
636 // For compatibility with existing code, we treat arrays of length 0 or
637 // 1 as flexible array members.
638 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
639 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
640 if (CAT->getSize().ugt(1))
641 return false;
642 } else if (!isa<IncompleteArrayType>(AT))
643 return false;
644
645 E = E->IgnoreParens();
646
647 // A flexible array member must be the last member in the class.
648 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
649 // FIXME: If the base type of the member expr is not FD->getParent(),
650 // this should not be treated as a flexible array member access.
651 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
652 RecordDecl::field_iterator FI(
653 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
654 return ++FI == FD->getParent()->field_end();
655 }
656 }
657
658 return false;
659}
660
661/// If Base is known to point to the start of an array, return the length of
662/// that array. Return 0 if the length cannot be determined.
663llvm::Value *getArrayIndexingBound(CodeGenFunction &CGF, const Expr *Base,
664 QualType &IndexedType) {
665 // For the vector indexing extension, the bound is the number of elements.
666 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
667 IndexedType = Base->getType();
668 return CGF.Builder.getInt32(VT->getNumElements());
669 }
670
671 Base = Base->IgnoreParens();
672
673 if (const CastExpr *CE = dyn_cast<CastExpr>(Base)) {
674 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
675 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
676 IndexedType = CE->getSubExpr()->getType();
677 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
678 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
679 return CGF.Builder.getInt(CAT->getSize());
680 else if (const VariableArrayType *VAT = cast<VariableArrayType>(AT))
681 return CGF.getVLASize(VAT).first;
682 }
683 }
684
685 return 0;
686}
687
688void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
689 llvm::Value *Index, QualType IndexType,
690 bool Accessed) {
691 QualType IndexedType;
692 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
693 if (!Bound)
694 return;
695
696 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
697 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
698 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
699
700 llvm::Constant *StaticData[] = {
701 EmitCheckSourceLocation(E->getExprLoc()),
702 EmitCheckTypeDescriptor(IndexedType),
703 EmitCheckTypeDescriptor(IndexType)
704 };
705 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
706 : Builder.CreateICmpULE(IndexVal, BoundVal);
707 EmitCheck(Check, "out_of_bounds", StaticData, Index, CRK_Recoverable);
708}
709
Chris Lattner116ce8f2010-01-09 21:40:03 +0000710
Chris Lattner116ce8f2010-01-09 21:40:03 +0000711CodeGenFunction::ComplexPairTy CodeGenFunction::
712EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
713 bool isInc, bool isPre) {
714 ComplexPairTy InVal = LoadComplexFromAddr(LV.getAddress(),
715 LV.isVolatileQualified());
716
717 llvm::Value *NextVal;
718 if (isa<llvm::IntegerType>(InVal.first->getType())) {
719 uint64_t AmountVal = isInc ? 1 : -1;
720 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
721
722 // Add the inc/dec to the real part.
723 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
724 } else {
725 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
726 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
727 if (!isInc)
728 FVal.changeSign();
729 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
730
731 // Add the inc/dec to the real part.
732 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
733 }
734
735 ComplexPairTy IncVal(NextVal, InVal.second);
736
737 // Store the updated result through the lvalue.
738 StoreComplexToAddr(IncVal, LV.getAddress(), LV.isVolatileQualified());
739
740 // If this is a postinc, return the value read from memory, otherwise use the
741 // updated value.
742 return isPre ? IncVal : InVal;
743}
744
745
Chris Lattnera45c5af2007-06-02 19:47:04 +0000746//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000747// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000748//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000749
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000750RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000751 if (Ty->isVoidType())
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000752 return RValue::get(0);
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000753
754 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000755 llvm::Type *EltTy = ConvertType(CTy->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +0000756 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000757 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000758 }
759
Chris Lattner65526f02010-08-23 05:26:13 +0000760 // If this is a use of an undefined aggregate type, the aggregate must have an
761 // identifiable address. Just because the contents of the value are undefined
762 // doesn't mean that the address can't be taken and compared.
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000763 if (hasAggregateLLVMType(Ty)) {
Chris Lattner65526f02010-08-23 05:26:13 +0000764 llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
765 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000766 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000767
768 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
Daniel Dunbarbb197e42009-01-09 16:50:52 +0000769}
770
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000771RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
772 const char *Name) {
773 ErrorUnsupported(E, Name);
774 return GetUndefRValue(E->getType());
775}
776
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000777LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
778 const char *Name) {
779 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000780 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000781 return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000782}
783
Richard Smith4d1458e2012-09-08 02:08:36 +0000784LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +0000785 LValue LV;
786 if (SanOpts->Bounds && isa<ArraySubscriptExpr>(E))
787 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
788 else
789 LV = EmitLValue(E);
Daniel Dunbardc406b82010-04-05 21:36:35 +0000790 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
Richard Smithe30752c2012-10-09 19:52:38 +0000791 EmitTypeCheck(TCK, E->getExprLoc(), LV.getAddress(),
792 E->getType(), LV.getAlignment());
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000793 return LV;
794}
795
Chris Lattner8394d792007-06-05 20:53:16 +0000796/// EmitLValue - Emit code to compute a designator that specifies the location
797/// of the expression.
798///
Mike Stump4a3999f2009-09-09 13:00:44 +0000799/// This can return one of two things: a simple address or a bitfield reference.
800/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
801/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +0000802///
Mike Stump4a3999f2009-09-09 13:00:44 +0000803/// If this returns a bitfield reference, nothing about the pointee type of the
804/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +0000805///
Mike Stump4a3999f2009-09-09 13:00:44 +0000806/// If this returns a normal address, and if the lvalue's C type is fixed size,
807/// this method guarantees that the returned pointer type will point to an LLVM
808/// type of the same size of the lvalue's type. If the lvalue has a variable
809/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +0000810///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000811LValue CodeGenFunction::EmitLValue(const Expr *E) {
812 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000813 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000814
John McCallc109a252011-11-07 03:59:57 +0000815 case Expr::ObjCPropertyRefExprClass:
816 llvm_unreachable("cannot emit a property reference directly");
817
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000818 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +0000819 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000820 case Expr::ObjCIsaExprClass:
821 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000822 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +0000823 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
Douglas Gregor914af212010-04-23 04:16:32 +0000824 case Expr::CompoundAssignOperatorClass:
John McCalla2342eb2010-12-05 02:00:02 +0000825 if (!E->getType()->isAnyComplexType())
826 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
827 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000828 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +0000829 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000830 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +0000831 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000832 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +0000833 case Expr::VAArgExprClass:
834 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000835 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000836 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +0000837 case Expr::ParenExprClass:
838 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +0000839 case Expr::GenericSelectionExprClass:
840 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +0000841 case Expr::PredefinedExprClass:
842 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +0000843 case Expr::StringLiteralClass:
844 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +0000845 case Expr::ObjCEncodeExprClass:
846 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +0000847 case Expr::PseudoObjectExprClass:
848 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +0000849 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +0000850 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +0000851 case Expr::CXXTemporaryObjectExprClass:
852 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +0000853 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
854 case Expr::CXXBindTemporaryExprClass:
855 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +0000856 case Expr::CXXUuidofExprClass:
857 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +0000858 case Expr::LambdaExprClass:
859 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +0000860
861 case Expr::ExprWithCleanupsClass: {
862 const ExprWithCleanups *cleanups = cast<ExprWithCleanups>(E);
863 enterFullExpression(cleanups);
864 RunCleanupsScope Scope(*this);
865 return EmitLValue(cleanups->getSubExpr());
866 }
867
Douglas Gregor747eb782010-07-08 06:14:04 +0000868 case Expr::CXXScalarValueInitExprClass:
869 return EmitNullInitializationLValue(cast<CXXScalarValueInitExpr>(E));
Anders Carlsson52ce3bb2009-11-14 01:51:50 +0000870 case Expr::CXXDefaultArgExprClass:
871 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Mike Stumpc9b231c2009-11-15 08:09:41 +0000872 case Expr::CXXTypeidExprClass:
873 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +0000874
Daniel Dunbarc8317a42008-08-23 10:51:21 +0000875 case Expr::ObjCMessageExprClass:
876 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000877 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +0000878 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +0000879 case Expr::StmtExprClass:
880 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000881 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +0000882 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000883 case Expr::ArraySubscriptExprClass:
884 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +0000885 case Expr::ExtVectorElementExprClass:
886 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000887 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +0000888 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +0000889 case Expr::CompoundLiteralExprClass:
890 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +0000891 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +0000892 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +0000893 case Expr::BinaryConditionalOperatorClass:
894 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +0000895 case Expr::ChooseExprClass:
Eli Friedmane0a5b8b2009-03-04 05:52:32 +0000896 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext()));
John McCall1bf58462011-02-16 08:02:54 +0000897 case Expr::OpaqueValueExprClass:
898 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +0000899 case Expr::SubstNonTypeTemplateParmExprClass:
900 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +0000901 case Expr::ImplicitCastExprClass:
902 case Expr::CStyleCastExprClass:
903 case Expr::CXXFunctionalCastExprClass:
904 case Expr::CXXStaticCastExprClass:
905 case Expr::CXXDynamicCastExprClass:
906 case Expr::CXXReinterpretCastExprClass:
907 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +0000908 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +0000909 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +0000910
Douglas Gregorfe314812011-06-21 17:03:29 +0000911 case Expr::MaterializeTemporaryExprClass:
912 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000913 }
914}
915
John McCall71335052012-03-10 03:05:10 +0000916/// Given an object of the given canonical type, can we safely copy a
917/// value out of it based on its initializer?
918static bool isConstantEmittableObjectType(QualType type) {
919 assert(type.isCanonical());
920 assert(!type->isReferenceType());
921
922 // Must be const-qualified but non-volatile.
923 Qualifiers qs = type.getLocalQualifiers();
924 if (!qs.hasConst() || qs.hasVolatile()) return false;
925
926 // Otherwise, all object types satisfy this except C++ classes with
927 // mutable subobjects or non-trivial copy/destroy behavior.
928 if (const RecordType *RT = dyn_cast<RecordType>(type))
929 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
930 if (RD->hasMutableFields() || !RD->isTrivial())
931 return false;
932
933 return true;
934}
935
936/// Can we constant-emit a load of a reference to a variable of the
937/// given type? This is different from predicates like
938/// Decl::isUsableInConstantExpressions because we do want it to apply
939/// in situations that don't necessarily satisfy the language's rules
940/// for this (e.g. C++'s ODR-use rules). For example, we want to able
941/// to do this with const float variables even if those variables
942/// aren't marked 'constexpr'.
943enum ConstantEmissionKind {
944 CEK_None,
945 CEK_AsReferenceOnly,
946 CEK_AsValueOrReference,
947 CEK_AsValueOnly
948};
949static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
950 type = type.getCanonicalType();
951 if (const ReferenceType *ref = dyn_cast<ReferenceType>(type)) {
952 if (isConstantEmittableObjectType(ref->getPointeeType()))
953 return CEK_AsValueOrReference;
954 return CEK_AsReferenceOnly;
955 }
956 if (isConstantEmittableObjectType(type))
957 return CEK_AsValueOnly;
958 return CEK_None;
959}
960
961/// Try to emit a reference to the given value without producing it as
962/// an l-value. This is actually more than an optimization: we can't
963/// produce an l-value for variables that we never actually captured
964/// in a block or lambda, which means const int variables or constexpr
965/// literals or similar.
966CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +0000967CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
968 ValueDecl *value = refExpr->getDecl();
969
John McCall71335052012-03-10 03:05:10 +0000970 // The value needs to be an enum constant or a constant variable.
971 ConstantEmissionKind CEK;
972 if (isa<ParmVarDecl>(value)) {
973 CEK = CEK_None;
974 } else if (VarDecl *var = dyn_cast<VarDecl>(value)) {
975 CEK = checkVarTypeForConstantEmission(var->getType());
976 } else if (isa<EnumConstantDecl>(value)) {
977 CEK = CEK_AsValueOnly;
978 } else {
979 CEK = CEK_None;
980 }
981 if (CEK == CEK_None) return ConstantEmission();
982
John McCall71335052012-03-10 03:05:10 +0000983 Expr::EvalResult result;
984 bool resultIsReference;
985 QualType resultType;
986
987 // It's best to evaluate all the way as an r-value if that's permitted.
988 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +0000989 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +0000990 resultIsReference = false;
991 resultType = refExpr->getType();
992
993 // Otherwise, try to evaluate as an l-value.
994 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +0000995 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +0000996 resultIsReference = true;
997 resultType = value->getType();
998
999 // Failure.
1000 } else {
1001 return ConstantEmission();
1002 }
1003
1004 // In any case, if the initializer has side-effects, abandon ship.
1005 if (result.HasSideEffects)
1006 return ConstantEmission();
1007
1008 // Emit as a constant.
1009 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1010
1011 // Make sure we emit a debug reference to the global variable.
1012 // This should probably fire even for
1013 if (isa<VarDecl>(value)) {
1014 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
John McCall113bee02012-03-10 09:33:50 +00001015 EmitDeclRefExprDbgValue(refExpr, C);
John McCall71335052012-03-10 03:05:10 +00001016 } else {
1017 assert(isa<EnumConstantDecl>(value));
John McCall113bee02012-03-10 09:33:50 +00001018 EmitDeclRefExprDbgValue(refExpr, C);
John McCall71335052012-03-10 03:05:10 +00001019 }
1020
1021 // If we emitted a reference constant, we need to dereference that.
1022 if (resultIsReference)
1023 return ConstantEmission::forReference(C);
1024
1025 return ConstantEmission::forValue(C);
1026}
1027
John McCall1553b192011-06-16 04:16:24 +00001028llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue) {
1029 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
Eli Friedmana0544d62011-12-03 04:14:32 +00001030 lvalue.getAlignment().getQuantity(),
1031 lvalue.getType(), lvalue.getTBAAInfo());
John McCall1553b192011-06-16 04:16:24 +00001032}
1033
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001034static bool hasBooleanRepresentation(QualType Ty) {
1035 if (Ty->isBooleanType())
1036 return true;
1037
1038 if (const EnumType *ET = Ty->getAs<EnumType>())
1039 return ET->getDecl()->getIntegerType()->isBooleanType();
1040
Douglas Gregor298f43d2012-04-12 20:42:30 +00001041 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1042 return hasBooleanRepresentation(AT->getValueType());
1043
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001044 return false;
1045}
1046
Richard Smith1629da92012-12-13 07:11:50 +00001047static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1048 llvm::APInt &Min, llvm::APInt &End,
1049 bool StrictEnums) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001050 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001051 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1052 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001053 bool IsBool = hasBooleanRepresentation(Ty);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001054 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001055 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001056
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001057 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001058 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1059 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001060 } else {
1061 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001062 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001063 unsigned Bitwidth = LTy->getScalarSizeInBits();
1064 unsigned NumNegativeBits = ED->getNumNegativeBits();
1065 unsigned NumPositiveBits = ED->getNumPositiveBits();
1066
1067 if (NumNegativeBits) {
1068 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1069 assert(NumBits <= Bitwidth);
1070 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1071 Min = -End;
1072 } else {
1073 assert(NumPositiveBits <= Bitwidth);
1074 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1075 Min = llvm::APInt(Bitwidth, 0);
1076 }
1077 }
Richard Smith1629da92012-12-13 07:11:50 +00001078 return true;
1079}
1080
1081llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1082 llvm::APInt Min, End;
1083 if (!getRangeForType(*this, Ty, Min, End,
1084 CGM.getCodeGenOpts().StrictEnums))
1085 return 0;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001086
Duncan Sandsc720e782012-04-15 18:04:54 +00001087 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001088 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001089}
1090
Daniel Dunbar1d425462009-02-10 00:57:50 +00001091llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
Dan Gohman947c9af2010-10-14 23:06:10 +00001092 unsigned Alignment, QualType Ty,
1093 llvm::MDNode *TBAAInfo) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001094
1095 // For better performance, handle vector loads differently.
1096 if (Ty->isVectorType()) {
1097 llvm::Value *V;
1098 const llvm::Type *EltTy =
1099 cast<llvm::PointerType>(Addr->getType())->getElementType();
1100
1101 const llvm::VectorType *VTy = cast<llvm::VectorType>(EltTy);
1102
1103 // Handle vectors of size 3, like size 4 for better performance.
1104 if (VTy->getNumElements() == 3) {
1105
1106 // Bitcast to vec4 type.
1107 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
1108 4);
1109 llvm::PointerType *ptVec4Ty =
1110 llvm::PointerType::get(vec4Ty,
1111 (cast<llvm::PointerType>(
1112 Addr->getType()))->getAddressSpace());
1113 llvm::Value *Cast = Builder.CreateBitCast(Addr, ptVec4Ty,
1114 "castToVec4");
1115 // Now load value.
1116 llvm::Value *LoadVal = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001117
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001118 // Shuffle vector to get vec3.
Richard Smithf0480fc2012-12-13 05:41:48 +00001119 llvm::Constant *Mask[] = {
1120 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 0),
1121 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 1),
1122 llvm::ConstantInt::get(llvm::Type::getInt32Ty(getLLVMContext()), 2)
1123 };
1124
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001125 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1126 V = Builder.CreateShuffleVector(LoadVal,
1127 llvm::UndefValue::get(vec4Ty),
1128 MaskV, "extractVec");
1129 return EmitFromMemory(V, Ty);
1130 }
1131 }
1132
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001133 llvm::LoadInst *Load = Builder.CreateLoad(Addr);
Daniel Dunbarc76493a2009-11-29 21:23:36 +00001134 if (Volatile)
1135 Load->setVolatile(true);
Daniel Dunbar03816342010-08-21 02:24:36 +00001136 if (Alignment)
1137 Load->setAlignment(Alignment);
Dan Gohman947c9af2010-10-14 23:06:10 +00001138 if (TBAAInfo)
1139 CGM.DecorateInstruction(Load, TBAAInfo);
David Chisnallfa35df62012-01-16 17:27:18 +00001140 // If this is an atomic type, all normal reads must be atomic
1141 if (Ty->isAtomicType())
1142 Load->setAtomic(llvm::SequentiallyConsistent);
Daniel Dunbar1d425462009-02-10 00:57:50 +00001143
Will Dietzf54319c2013-01-18 11:30:38 +00001144 if ((SanOpts->Bool && hasBooleanRepresentation(Ty)) ||
1145 (SanOpts->Enum && Ty->getAs<EnumType>())) {
Richard Smith1629da92012-12-13 07:11:50 +00001146 llvm::APInt Min, End;
1147 if (getRangeForType(*this, Ty, Min, End, true)) {
1148 --End;
1149 llvm::Value *Check;
1150 if (!Min)
1151 Check = Builder.CreateICmpULE(
1152 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1153 else {
1154 llvm::Value *Upper = Builder.CreateICmpSLE(
1155 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1156 llvm::Value *Lower = Builder.CreateICmpSGE(
1157 Load, llvm::ConstantInt::get(getLLVMContext(), Min));
1158 Check = Builder.CreateAnd(Upper, Lower);
1159 }
1160 // FIXME: Provide a SourceLocation.
1161 EmitCheck(Check, "load_invalid_value", EmitCheckTypeDescriptor(Ty),
1162 EmitCheckValue(Load), CRK_Recoverable);
1163 }
1164 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001165 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1166 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001167
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001168 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001169}
1170
John McCall3a7f6922010-10-27 20:58:56 +00001171llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1172 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001173 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001174 // This should really always be an i1, but sometimes it's already
1175 // an i8, and it's awkward to track those cases down.
1176 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001177 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1178 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1179 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001180 }
1181
1182 return Value;
1183}
1184
1185llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1186 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001187 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001188 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1189 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001190 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1191 }
1192
1193 return Value;
1194}
1195
Daniel Dunbar1d425462009-02-10 00:57:50 +00001196void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
Daniel Dunbar03816342010-08-21 02:24:36 +00001197 bool Volatile, unsigned Alignment,
Dan Gohman947c9af2010-10-14 23:06:10 +00001198 QualType Ty,
David Chisnallfa35df62012-01-16 17:27:18 +00001199 llvm::MDNode *TBAAInfo,
1200 bool isInit) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001201
1202 // Handle vectors differently to get better performance.
1203 if (Ty->isVectorType()) {
1204 llvm::Type *SrcTy = Value->getType();
1205 llvm::VectorType *VecTy = cast<llvm::VectorType>(SrcTy);
1206 // Handle vec3 special.
1207 if (VecTy->getNumElements() == 3) {
1208 llvm::LLVMContext &VMContext = getLLVMContext();
1209
1210 // Our source is a vec3, do a shuffle vector to make it a vec4.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001211 SmallVector<llvm::Constant*, 4> Mask;
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001212 Mask.push_back(llvm::ConstantInt::get(
1213 llvm::Type::getInt32Ty(VMContext),
1214 0));
1215 Mask.push_back(llvm::ConstantInt::get(
1216 llvm::Type::getInt32Ty(VMContext),
1217 1));
1218 Mask.push_back(llvm::ConstantInt::get(
1219 llvm::Type::getInt32Ty(VMContext),
1220 2));
1221 Mask.push_back(llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext)));
1222
1223 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1224 Value = Builder.CreateShuffleVector(Value,
1225 llvm::UndefValue::get(VecTy),
1226 MaskV, "extractVec");
1227 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1228 }
1229 llvm::PointerType *DstPtr = cast<llvm::PointerType>(Addr->getType());
1230 if (DstPtr->getElementType() != SrcTy) {
1231 llvm::Type *MemTy =
1232 llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace());
1233 Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp");
1234 }
1235 }
1236
John McCall3a7f6922010-10-27 20:58:56 +00001237 Value = EmitToMemory(Value, Ty);
Chris Lattner1a5f8972011-07-10 03:38:35 +00001238
Daniel Dunbar03816342010-08-21 02:24:36 +00001239 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1240 if (Alignment)
1241 Store->setAlignment(Alignment);
Dan Gohman947c9af2010-10-14 23:06:10 +00001242 if (TBAAInfo)
1243 CGM.DecorateInstruction(Store, TBAAInfo);
David Chisnallfa35df62012-01-16 17:27:18 +00001244 if (!isInit && Ty->isAtomicType())
1245 Store->setAtomic(llvm::SequentiallyConsistent);
Daniel Dunbar1d425462009-02-10 00:57:50 +00001246}
1247
David Chisnallfa35df62012-01-16 17:27:18 +00001248void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1249 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001250 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
Eli Friedmana0544d62011-12-03 04:14:32 +00001251 lvalue.getAlignment().getQuantity(), lvalue.getType(),
David Chisnallfa35df62012-01-16 17:27:18 +00001252 lvalue.getTBAAInfo(), isInit);
John McCall1553b192011-06-16 04:16:24 +00001253}
1254
Mike Stump4a3999f2009-09-09 13:00:44 +00001255/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1256/// method emits the address of the lvalue, then loads the result as an rvalue,
1257/// returning the rvalue.
John McCall55e1fbc2011-06-25 02:11:03 +00001258RValue CodeGenFunction::EmitLoadOfLValue(LValue LV) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001259 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001260 // load of a __weak object.
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001261 llvm::Value *AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001262 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1263 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001264 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001265 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1266 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1267 Object = EmitObjCConsumeObject(LV.getType(), Object);
1268 return RValue::get(Object);
1269 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001270
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001271 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001272 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001273
John McCalla1dee5302010-08-22 10:59:02 +00001274 // Everything needs a load.
John McCall55e1fbc2011-06-25 02:11:03 +00001275 return RValue::get(EmitLoadOfScalar(LV));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001276 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001277
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001278 if (LV.isVectorElt()) {
Eli Friedman610bb872012-03-22 22:36:39 +00001279 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddr(),
1280 LV.isVolatileQualified());
1281 Load->setAlignment(LV.getAlignment().getQuantity());
1282 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001283 "vecext"));
1284 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001285
1286 // If this is a reference to a subset of the elements of a vector, either
1287 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001288 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001289 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001290
John McCallc109a252011-11-07 03:59:57 +00001291 assert(LV.isBitField() && "Unknown LValue type!");
1292 return EmitLoadOfBitfieldLValue(LV);
Chris Lattner8394d792007-06-05 20:53:16 +00001293}
1294
John McCall55e1fbc2011-06-25 02:11:03 +00001295RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001296 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001297
Daniel Dunbar3447a022010-04-13 23:34:15 +00001298 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001299 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001300
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001301 llvm::Value *Ptr = LV.getBitFieldAddr();
1302 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(),
1303 "bf.load");
1304 cast<llvm::LoadInst>(Val)->setAlignment(Info.StorageAlignment);
Mike Stump4a3999f2009-09-09 13:00:44 +00001305
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001306 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001307 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001308 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1309 if (HighBits)
1310 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1311 if (Info.Offset + HighBits)
1312 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1313 } else {
1314 if (Info.Offset)
1315 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001316 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001317 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1318 Info.Size),
1319 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001320 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001321 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001322
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001323 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001324}
1325
Nate Begemanb699c9b2009-01-18 06:42:49 +00001326// If this is a reference to a subset of the elements of a vector, create an
1327// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001328RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
Eli Friedman610bb872012-03-22 22:36:39 +00001329 llvm::LoadInst *Load = Builder.CreateLoad(LV.getExtVectorAddr(),
1330 LV.isVolatileQualified());
1331 Load->setAlignment(LV.getAlignment().getQuantity());
1332 llvm::Value *Vec = Load;
Mike Stump4a3999f2009-09-09 13:00:44 +00001333
Nate Begemanf322eab2008-05-09 06:41:27 +00001334 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001335
1336 // If the result of the expression is a non-vector type, we must be extracting
1337 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001338 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001339 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001340 unsigned InIdx = getAccessedFieldNo(0, Elts);
Chris Lattner5e016ae2010-06-27 07:15:29 +00001341 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001342 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001343 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001344
1345 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001346 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001347
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001348 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001349 for (unsigned i = 0; i != NumResultElts; ++i)
1350 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001351
Chris Lattner91c08ad2011-02-15 00:14:06 +00001352 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1353 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001354 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001355 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001356}
1357
1358
Chris Lattner9369a562007-06-29 16:31:29 +00001359
Chris Lattner8394d792007-06-05 20:53:16 +00001360/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1361/// lvalue, where both are guaranteed to the have the same type, and that type
1362/// is 'Ty'.
David Chisnallfa35df62012-01-16 17:27:18 +00001363void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001364 if (!Dst.isSimple()) {
1365 if (Dst.isVectorElt()) {
1366 // Read/modify/write the vector, inserting the new element.
Eli Friedman610bb872012-03-22 22:36:39 +00001367 llvm::LoadInst *Load = Builder.CreateLoad(Dst.getVectorAddr(),
1368 Dst.isVolatileQualified());
1369 Load->setAlignment(Dst.getAlignment().getQuantity());
1370 llvm::Value *Vec = Load;
Chris Lattner4647a212007-08-31 22:49:20 +00001371 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001372 Dst.getVectorIdx(), "vecins");
Eli Friedman610bb872012-03-22 22:36:39 +00001373 llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getVectorAddr(),
1374 Dst.isVolatileQualified());
1375 Store->setAlignment(Dst.getAlignment().getQuantity());
Chris Lattner41d480e2007-08-03 16:28:33 +00001376 return;
1377 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001378
Nate Begemance4d7fc2008-04-18 23:10:10 +00001379 // If this is an update of extended vector elements, insert them as
1380 // appropriate.
1381 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001382 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001383
John McCallc109a252011-11-07 03:59:57 +00001384 assert(Dst.isBitField() && "Unknown LValue type");
1385 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001386 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001387
John McCall31168b02011-06-15 23:02:42 +00001388 // There's special magic for assigning into an ARC-qualified l-value.
1389 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1390 switch (Lifetime) {
1391 case Qualifiers::OCL_None:
1392 llvm_unreachable("present but none");
1393
1394 case Qualifiers::OCL_ExplicitNone:
1395 // nothing special
1396 break;
1397
1398 case Qualifiers::OCL_Strong:
John McCall55e1fbc2011-06-25 02:11:03 +00001399 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001400 return;
1401
1402 case Qualifiers::OCL_Weak:
1403 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1404 return;
1405
1406 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001407 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1408 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001409 // fall into the normal path
1410 break;
1411 }
1412 }
1413
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001414 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001415 // load of a __weak object.
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001416 llvm::Value *LvalueDst = Dst.getAddress();
1417 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001418 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001419 return;
1420 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001421
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001422 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001423 // load of a __strong object.
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001424 llvm::Value *LvalueDst = Dst.getAddress();
1425 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001426 if (Dst.isObjCIvar()) {
1427 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
Chris Lattner2192fe52011-07-18 04:24:23 +00001428 llvm::Type *ResultType = ConvertType(getContext().LongTy);
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001429 llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001430 llvm::Value *dst = RHS;
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001431 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1432 llvm::Value *LHS =
1433 Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
1434 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001435 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001436 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001437 } else if (Dst.isGlobalObjCRef()) {
1438 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1439 Dst.isThreadLocalRef());
1440 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001441 else
1442 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001443 return;
1444 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001445
Chris Lattner6278e6a2007-08-11 00:04:45 +00001446 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001447 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001448}
1449
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001450void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001451 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001452 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001453 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001454 llvm::Value *Ptr = Dst.getBitFieldAddr();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001455
Daniel Dunbar67aba792010-04-15 03:47:33 +00001456 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001457 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001458
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001459 // Cast the source to the storage type and shift it into place.
1460 SrcVal = Builder.CreateIntCast(SrcVal,
1461 Ptr->getType()->getPointerElementType(),
1462 /*IsSigned=*/false);
1463 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001464
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001465 // See if there are other bits in the bitfield's storage we'll need to load
1466 // and mask together with source before storing.
1467 if (Info.StorageSize != Info.Size) {
1468 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
1469 llvm::Value *Val = Builder.CreateLoad(Ptr, Dst.isVolatileQualified(),
1470 "bf.load");
1471 cast<llvm::LoadInst>(Val)->setAlignment(Info.StorageAlignment);
1472
1473 // Mask the source value as needed.
1474 if (!hasBooleanRepresentation(Dst.getType()))
1475 SrcVal = Builder.CreateAnd(SrcVal,
1476 llvm::APInt::getLowBitsSet(Info.StorageSize,
1477 Info.Size),
1478 "bf.value");
1479 MaskedVal = SrcVal;
1480 if (Info.Offset)
1481 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1482
1483 // Mask out the original value.
1484 Val = Builder.CreateAnd(Val,
1485 ~llvm::APInt::getBitsSet(Info.StorageSize,
1486 Info.Offset,
1487 Info.Offset + Info.Size),
1488 "bf.clear");
1489
1490 // Or together the unchanged values and the source value.
1491 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1492 } else {
1493 assert(Info.Offset == 0);
1494 }
1495
1496 // Write the new value back out.
1497 llvm::StoreInst *Store = Builder.CreateStore(SrcVal, Ptr,
1498 Dst.isVolatileQualified());
1499 Store->setAlignment(Info.StorageAlignment);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001500
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001501 // Return the new value of the bit-field, if requested.
1502 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001503 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001504
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001505 // Sign extend the value if needed.
1506 if (Info.IsSigned) {
1507 assert(Info.Size <= Info.StorageSize);
1508 unsigned HighBits = Info.StorageSize - Info.Size;
1509 if (HighBits) {
1510 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1511 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1512 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001513 }
1514
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001515 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1516 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001517 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001518 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001519}
1520
Nate Begemance4d7fc2008-04-18 23:10:10 +00001521void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001522 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001523 // This access turns into a read/modify/write of the vector. Load the input
1524 // value now.
Eli Friedman610bb872012-03-22 22:36:39 +00001525 llvm::LoadInst *Load = Builder.CreateLoad(Dst.getExtVectorAddr(),
1526 Dst.isVolatileQualified());
1527 Load->setAlignment(Dst.getAlignment().getQuantity());
1528 llvm::Value *Vec = Load;
Nate Begemanf322eab2008-05-09 06:41:27 +00001529 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001530
Chris Lattner4647a212007-08-31 22:49:20 +00001531 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001532
John McCall55e1fbc2011-06-25 02:11:03 +00001533 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001534 unsigned NumSrcElts = VTy->getNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001535 unsigned NumDstElts =
1536 cast<llvm::VectorType>(Vec->getType())->getNumElements();
1537 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001538 // Use shuffle vector is the src and destination are the same number of
1539 // elements and restore the vector mask since it is on the side it will be
1540 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001541 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001542 for (unsigned i = 0; i != NumSrcElts; ++i)
1543 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001544
Chris Lattner91c08ad2011-02-15 00:14:06 +00001545 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001546 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001547 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001548 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001549 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001550 // Extended the source vector to the same length and then shuffle it
1551 // into the destination.
1552 // FIXME: since we're shuffling with undef, can we just use the indices
1553 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001554 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001555 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001556 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001557 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001558 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001559 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001560 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001561 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001562 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001563 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001564 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001565 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001566 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001567
Nate Begemanb699c9b2009-01-18 06:42:49 +00001568 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001569 for (unsigned i = 0; i != NumSrcElts; ++i)
1570 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001571 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001572 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001573 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001574 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001575 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001576 }
1577 } else {
1578 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001579 unsigned InIdx = getAccessedFieldNo(0, Elts);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001580 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001581 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001582 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001583
Eli Friedman610bb872012-03-22 22:36:39 +00001584 llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getExtVectorAddr(),
1585 Dst.isVolatileQualified());
1586 Store->setAlignment(Dst.getAlignment().getQuantity());
Chris Lattner41d480e2007-08-03 16:28:33 +00001587}
1588
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001589// setObjCGCLValueClass - sets class of he lvalue for the purpose of
1590// generating write-barries API. It is currently a global, ivar,
1591// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001592static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001593 LValue &LV,
1594 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001595 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001596 return;
1597
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001598 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001599 QualType ExpTy = E->getType();
1600 if (IsMemberAccess && ExpTy->isPointerType()) {
1601 // If ivar is a structure pointer, assigning to field of
1602 // this struct follows gcc's behavior and makes it a non-ivar
1603 // writer-barrier conservatively.
1604 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1605 if (ExpTy->isRecordType()) {
1606 LV.setObjCIvar(false);
1607 return;
1608 }
1609 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001610 LV.setObjCIvar(true);
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001611 ObjCIvarRefExpr *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr*>(E));
1612 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001613 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001614 return;
1615 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001616
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001617 if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) {
1618 if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001619 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001620 LV.setGlobalObjCRef(true);
1621 LV.setThreadLocalRef(VD->isThreadSpecified());
Fariborz Jahanian217af242010-07-20 20:30:03 +00001622 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001623 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001624 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001625 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001626 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001627
1628 if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001629 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001630 return;
1631 }
1632
1633 if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001634 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001635 if (LV.isObjCIvar()) {
1636 // If cast is to a structure pointer, follow gcc's behavior and make it
1637 // a non-ivar write-barrier.
1638 QualType ExpTy = E->getType();
1639 if (ExpTy->isPointerType())
1640 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1641 if (ExpTy->isRecordType())
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001642 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001643 }
1644 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001645 }
Peter Collingbourne91147592011-04-15 00:35:48 +00001646
1647 if (const GenericSelectionExpr *Exp = dyn_cast<GenericSelectionExpr>(E)) {
1648 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1649 return;
1650 }
1651
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001652 if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001653 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001654 return;
1655 }
1656
1657 if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001658 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001659 return;
1660 }
John McCall31168b02011-06-15 23:02:42 +00001661
1662 if (const ObjCBridgedCastExpr *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001663 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00001664 return;
1665 }
1666
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001667 if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001668 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001669 if (LV.isObjCIvar() && !LV.isObjCArray())
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001670 // Using array syntax to assigning to what an ivar points to is not
1671 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001672 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001673 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
1674 // Using array syntax to assigning to what global points to is not
1675 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001676 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001677 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001678 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001679
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001680 if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001681 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001682 // We don't know if member is an 'ivar', but this flag is looked at
1683 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001684 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001685 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001686 }
1687}
1688
Chris Lattner3f32d692011-07-12 06:52:18 +00001689static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00001690EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00001691 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001692 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00001693 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00001694 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00001695}
1696
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001697static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1698 const Expr *E, const VarDecl *VD) {
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001699 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001700 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
1701 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00001702 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001703 QualType T = E->getType();
1704 LValue LV;
1705 if (VD->getType()->isReferenceType()) {
1706 llvm::LoadInst *LI = CGF.Builder.CreateLoad(V);
Eli Friedmana0544d62011-12-03 04:14:32 +00001707 LI->setAlignment(Alignment.getQuantity());
Eli Friedmand20adbd2011-11-16 00:42:57 +00001708 V = LI;
1709 LV = CGF.MakeNaturalAlignAddrLValue(V, T);
1710 } else {
1711 LV = CGF.MakeAddrLValue(V, E->getType(), Alignment);
1712 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001713 setObjCGCLValueClass(CGF.getContext(), E, LV);
1714 return LV;
1715}
1716
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001717static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
Chris Lattner13ee4f42011-07-10 05:34:54 +00001718 const Expr *E, const FunctionDecl *FD) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00001719 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001720 if (!FD->hasPrototype()) {
1721 if (const FunctionProtoType *Proto =
1722 FD->getType()->getAs<FunctionProtoType>()) {
1723 // Ugly case: for a K&R-style definition, the type of the definition
1724 // isn't the same as the type of a use. Correct for this with a
1725 // bitcast.
1726 QualType NoProtoType =
1727 CGF.getContext().getFunctionNoProtoType(Proto->getResultType());
1728 NoProtoType = CGF.getContext().getPointerType(NoProtoType);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001729 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001730 }
1731 }
Eli Friedmana0544d62011-12-03 04:14:32 +00001732 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
Daniel Dunbar5c816372010-08-21 04:20:22 +00001733 return CGF.MakeAddrLValue(V, E->getType(), Alignment);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001734}
1735
Chris Lattnerd7f58862007-06-02 05:24:33 +00001736LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00001737 const NamedDecl *ND = E->getDecl();
Eli Friedmana0544d62011-12-03 04:14:32 +00001738 CharUnits Alignment = getContext().getDeclAlign(ND);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001739 QualType T = E->getType();
Mike Stump4a3999f2009-09-09 13:00:44 +00001740
Richard Smith5a1104b2012-10-20 01:38:33 +00001741 // A DeclRefExpr for a reference initialized by a constant expression can
1742 // appear without being odr-used. Directly emit the constant initializer.
1743 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1744 const Expr *Init = VD->getAnyInitializer(VD);
1745 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
1746 VD->isUsableInConstantExpressions(getContext()) &&
1747 VD->checkInitIsICE()) {
1748 llvm::Constant *Val =
1749 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
1750 assert(Val && "failed to emit reference constant expression");
1751 // FIXME: Eventually we will want to emit vector element references.
1752 return MakeAddrLValue(Val, T, Alignment);
1753 }
1754 }
1755
Eli Friedman5720e342012-01-21 04:52:58 +00001756 // FIXME: We should be able to assert this for FunctionDecls as well!
1757 // FIXME: We should be able to assert this for all DeclRefExprs, not just
1758 // those with a valid source location.
1759 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
1760 !E->getLocation().isValid()) &&
1761 "Should not use decl without marking it used!");
1762
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001763 if (ND->hasAttr<WeakRefAttr>()) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00001764 const ValueDecl *VD = cast<ValueDecl>(ND);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001765 llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
Richard Smith5a1104b2012-10-20 01:38:33 +00001766 return MakeAddrLValue(Aliasee, T, Alignment);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001767 }
1768
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00001769 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00001770 // Check if this is a global variable.
Nick Lewycky230203c2013-01-10 01:46:29 +00001771 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001772 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00001773
John McCall113bee02012-03-10 09:33:50 +00001774 bool isBlockVariable = VD->hasAttr<BlocksAttr>();
1775
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00001776 bool NonGCable = VD->hasLocalStorage() &&
1777 !VD->getType()->isReferenceType() &&
John McCall113bee02012-03-10 09:33:50 +00001778 !isBlockVariable;
Anders Carlsson6eee9722009-11-07 22:46:42 +00001779
Nick Lewycky230203c2013-01-10 01:46:29 +00001780 llvm::Value *V = LocalDeclMap.lookup(VD);
Fariborz Jahanian366a9482010-09-07 23:26:17 +00001781 if (!V && VD->isStaticLocal())
Fariborz Jahanian4d55b2d2010-04-19 18:15:02 +00001782 V = CGM.getStaticLocalDeclAddress(VD);
Eli Friedman9fbeba02012-02-11 02:57:39 +00001783
1784 // Use special handling for lambdas.
John McCall113bee02012-03-10 09:33:50 +00001785 if (!V) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00001786 if (FieldDecl *FD = LambdaCaptureFields.lookup(VD)) {
1787 QualType LambdaTagType = getContext().getTagDeclType(FD->getParent());
1788 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue,
1789 LambdaTagType);
1790 return EmitLValueForField(LambdaLV, FD);
1791 }
Eli Friedman9fbeba02012-02-11 02:57:39 +00001792
John McCall113bee02012-03-10 09:33:50 +00001793 assert(isa<BlockDecl>(CurCodeDecl) && E->refersToEnclosingLocal());
John McCall113bee02012-03-10 09:33:50 +00001794 return MakeAddrLValue(GetAddrOfBlockDecl(VD, isBlockVariable),
Richard Smith5a1104b2012-10-20 01:38:33 +00001795 T, Alignment);
John McCall113bee02012-03-10 09:33:50 +00001796 }
1797
Anders Carlsson6eee9722009-11-07 22:46:42 +00001798 assert(V && "DeclRefExpr not entered in LocalDeclMap?");
1799
John McCall113bee02012-03-10 09:33:50 +00001800 if (isBlockVariable)
Fariborz Jahanian2f2fa722011-01-26 23:08:27 +00001801 V = BuildBlockByrefAddress(V, VD);
Daniel Dunbarf166a522010-08-21 03:44:13 +00001802
Eli Friedmand20adbd2011-11-16 00:42:57 +00001803 LValue LV;
1804 if (VD->getType()->isReferenceType()) {
1805 llvm::LoadInst *LI = Builder.CreateLoad(V);
Eli Friedmana0544d62011-12-03 04:14:32 +00001806 LI->setAlignment(Alignment.getQuantity());
Eli Friedmand20adbd2011-11-16 00:42:57 +00001807 V = LI;
1808 LV = MakeNaturalAlignAddrLValue(V, T);
1809 } else {
1810 LV = MakeAddrLValue(V, T, Alignment);
1811 }
Chris Lattner3f32d692011-07-12 06:52:18 +00001812
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00001813 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00001814 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00001815 LV.setNonGC(true);
1816 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001817 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00001818 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001819 }
John McCallf3a88602011-02-03 08:15:49 +00001820
1821 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND))
1822 return EmitFunctionDeclLValue(*this, E, fn);
1823
David Blaikie83d382b2011-09-23 05:06:16 +00001824 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00001825}
Chris Lattnere47e4402007-06-01 18:02:12 +00001826
Chris Lattner8394d792007-06-05 20:53:16 +00001827LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
1828 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00001829 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00001830 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00001831
Chris Lattner0f398c42008-07-26 22:37:01 +00001832 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00001833 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001834 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00001835 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001836 QualType T = E->getSubExpr()->getType()->getPointeeType();
1837 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00001838
Chris Lattner2415357a2011-12-19 21:16:08 +00001839 LValue LV = MakeNaturalAlignAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
Daniel Dunbarf166a522010-08-21 03:44:13 +00001840 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00001841
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001842 // We should not generate __weak write barrier on indirect reference
1843 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
1844 // But, we continue to generate __strong write barrier on indirect write
1845 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00001846 if (getLangOpts().ObjC1 &&
1847 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001848 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00001849 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001850 return LV;
1851 }
John McCalle3027922010-08-25 11:45:40 +00001852 case UO_Real:
1853 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00001854 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00001855 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
1856 llvm::Value *Addr = LV.getAddress();
1857
Richard Smith0b6b8e42012-02-18 20:53:32 +00001858 // __real is valid on scalars. This is a faster way of testing that.
1859 // __imag can only produce an rvalue on scalars.
1860 if (E->getOpcode() == UO_Real &&
1861 !cast<llvm::PointerType>(Addr->getType())
John McCalla2342eb2010-12-05 02:00:02 +00001862 ->getElementType()->isStructTy()) {
1863 assert(E->getSubExpr()->getType()->isArithmeticType());
1864 return LV;
1865 }
1866
1867 assert(E->getSubExpr()->getType()->isAnyComplexType());
1868
John McCalle3027922010-08-25 11:45:40 +00001869 unsigned Idx = E->getOpcode() == UO_Imag;
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00001870 return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(),
John McCalla2342eb2010-12-05 02:00:02 +00001871 Idx, "idx"),
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00001872 ExprTy);
Chris Lattner595db862007-10-30 22:53:42 +00001873 }
John McCalle3027922010-08-25 11:45:40 +00001874 case UO_PreInc:
1875 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00001876 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00001877 bool isInc = E->getOpcode() == UO_PreInc;
Chris Lattnerbb8976e2010-01-09 21:44:40 +00001878
1879 if (E->getType()->isAnyComplexType())
1880 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
1881 else
1882 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
1883 return LV;
1884 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00001885 }
Chris Lattner8394d792007-06-05 20:53:16 +00001886}
1887
Chris Lattner4347e3692007-06-06 04:54:52 +00001888LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001889 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
1890 E->getType());
Chris Lattner4347e3692007-06-06 04:54:52 +00001891}
1892
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001893LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001894 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
1895 E->getType());
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001896}
1897
Nico Weber3a691a32012-06-23 02:07:59 +00001898static llvm::Constant*
1899GetAddrOfConstantWideString(StringRef Str,
1900 const char *GlobalName,
1901 ASTContext &Context,
1902 QualType Ty, SourceLocation Loc,
1903 CodeGenModule &CGM) {
1904
1905 StringLiteral *SL = StringLiteral::Create(Context,
1906 Str,
1907 StringLiteral::Wide,
1908 /*Pascal = */false,
1909 Ty, Loc);
1910 llvm::Constant *C = CGM.GetConstantArrayFromStringLiteral(SL);
1911 llvm::GlobalVariable *GV =
1912 new llvm::GlobalVariable(CGM.getModule(), C->getType(),
1913 !CGM.getLangOpts().WritableStrings,
1914 llvm::GlobalValue::PrivateLinkage,
1915 C, GlobalName);
1916 const unsigned WideAlignment =
1917 Context.getTypeAlignInChars(Ty).getQuantity();
1918 GV->setAlignment(WideAlignment);
1919 return GV;
1920}
1921
Nico Weber3a691a32012-06-23 02:07:59 +00001922static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
1923 SmallString<32>& Target) {
1924 Target.resize(CharByteWidth * (Source.size() + 1));
Richard Smith639b8d02012-09-08 07:16:20 +00001925 char *ResultPtr = &Target[0];
1926 const UTF8 *ErrorPtr;
1927 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
Matt Beaumont-Gay36af16af2012-07-03 03:55:58 +00001928 (void)success;
Nico Weber4b18c3f2012-07-03 02:24:52 +00001929 assert(success);
Nico Weber3a691a32012-06-23 02:07:59 +00001930 Target.resize(ResultPtr - &Target[0]);
1931}
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001932
Mike Stump4a3999f2009-09-09 13:00:44 +00001933LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Daniel Dunbarb3517472008-10-17 21:58:32 +00001934 switch (E->getIdentType()) {
1935 default:
1936 return EmitUnsupportedLValue(E, "predefined expression");
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001937
Daniel Dunbarb3517472008-10-17 21:58:32 +00001938 case PredefinedExpr::Func:
1939 case PredefinedExpr::Function:
Nico Weber3a691a32012-06-23 02:07:59 +00001940 case PredefinedExpr::LFunction:
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001941 case PredefinedExpr::PrettyFunction: {
Nico Weber3a691a32012-06-23 02:07:59 +00001942 unsigned IdentType = E->getIdentType();
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001943 std::string GlobalVarName;
1944
Nico Weber3a691a32012-06-23 02:07:59 +00001945 switch (IdentType) {
David Blaikie83d382b2011-09-23 05:06:16 +00001946 default: llvm_unreachable("Invalid type");
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001947 case PredefinedExpr::Func:
1948 GlobalVarName = "__func__.";
1949 break;
1950 case PredefinedExpr::Function:
1951 GlobalVarName = "__FUNCTION__.";
1952 break;
Nico Weber3a691a32012-06-23 02:07:59 +00001953 case PredefinedExpr::LFunction:
1954 GlobalVarName = "L__FUNCTION__.";
1955 break;
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001956 case PredefinedExpr::PrettyFunction:
1957 GlobalVarName = "__PRETTY_FUNCTION__.";
1958 break;
1959 }
1960
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001961 StringRef FnName = CurFn->getName();
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001962 if (FnName.startswith("\01"))
1963 FnName = FnName.substr(1);
1964 GlobalVarName += FnName;
1965
1966 const Decl *CurDecl = CurCodeDecl;
1967 if (CurDecl == 0)
1968 CurDecl = getContext().getTranslationUnitDecl();
1969
1970 std::string FunctionName =
John McCall351762c2011-02-07 10:33:21 +00001971 (isa<BlockDecl>(CurDecl)
1972 ? FnName.str()
Nico Weber3a691a32012-06-23 02:07:59 +00001973 : PredefinedExpr::ComputeName((PredefinedExpr::IdentType)IdentType,
1974 CurDecl));
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001975
Nico Weber3a691a32012-06-23 02:07:59 +00001976 const Type* ElemType = E->getType()->getArrayElementTypeNoTypeQual();
1977 llvm::Constant *C;
1978 if (ElemType->isWideCharType()) {
1979 SmallString<32> RawChars;
1980 ConvertUTF8ToWideString(
1981 getContext().getTypeSizeInChars(ElemType).getQuantity(),
1982 FunctionName, RawChars);
1983 C = GetAddrOfConstantWideString(RawChars,
1984 GlobalVarName.c_str(),
1985 getContext(),
1986 E->getType(),
1987 E->getLocation(),
1988 CGM);
1989 } else {
1990 C = CGM.GetAddrOfConstantCString(FunctionName,
1991 GlobalVarName.c_str(),
1992 1);
1993 }
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001994 return MakeAddrLValue(C, E->getType());
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001995 }
Daniel Dunbarb3517472008-10-17 21:58:32 +00001996 }
Anders Carlsson625bfc82007-07-21 05:21:51 +00001997}
1998
Richard Smithe30752c2012-10-09 19:52:38 +00001999/// Emit a type description suitable for use by a runtime sanitizer library. The
2000/// format of a type descriptor is
2001///
2002/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002003/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002004/// \endcode
2005///
Richard Smith683398a2012-10-09 23:55:19 +00002006/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2007/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002008llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
2009 // FIXME: Only emit each type's descriptor once.
2010 uint16_t TypeKind = -1;
2011 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002012
Richard Smithe30752c2012-10-09 19:52:38 +00002013 if (T->isIntegerType()) {
2014 TypeKind = 0;
2015 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002016 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002017 } else if (T->isFloatingType()) {
2018 TypeKind = 1;
2019 TypeInfo = getContext().getTypeSize(T);
2020 }
2021
2022 // Format the type name as if for a diagnostic, including quotes and
2023 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002024 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002025 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2026 (intptr_t)T.getAsOpaquePtr(),
2027 0, 0, 0, 0, 0, 0, Buffer,
2028 ArrayRef<intptr_t>());
2029
2030 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002031 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2032 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002033 };
2034 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2035
2036 llvm::GlobalVariable *GV =
2037 new llvm::GlobalVariable(CGM.getModule(), Descriptor->getType(),
2038 /*isConstant=*/true,
2039 llvm::GlobalVariable::PrivateLinkage,
2040 Descriptor);
2041 GV->setUnnamedAddr(true);
2042 return GV;
2043}
2044
2045llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2046 llvm::Type *TargetTy = IntPtrTy;
2047
2048 // Integers which fit in intptr_t are zero-extended and passed directly.
2049 if (V->getType()->isIntegerTy() &&
2050 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2051 return Builder.CreateZExt(V, TargetTy);
2052
2053 // Pointers are passed directly, everything else is passed by address.
2054 if (!V->getType()->isPointerTy()) {
2055 llvm::Value *Ptr = Builder.CreateAlloca(V->getType());
2056 Builder.CreateStore(V, Ptr);
2057 V = Ptr;
2058 }
2059 return Builder.CreatePtrToInt(V, TargetTy);
2060}
2061
2062/// \brief Emit a representation of a SourceLocation for passing to a handler
2063/// in a sanitizer runtime library. The format for this data is:
2064/// \code
2065/// struct SourceLocation {
2066/// const char *Filename;
2067/// int32_t Line, Column;
2068/// };
2069/// \endcode
2070/// For an invalid SourceLocation, the Filename pointer is null.
2071llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
2072 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2073
2074 llvm::Constant *Data[] = {
2075 // FIXME: Only emit each file name once.
2076 PLoc.isValid() ? cast<llvm::Constant>(
2077 Builder.CreateGlobalStringPtr(PLoc.getFilename()))
2078 : llvm::Constant::getNullValue(Int8PtrTy),
2079 Builder.getInt32(PLoc.getLine()),
2080 Builder.getInt32(PLoc.getColumn())
2081 };
2082
2083 return llvm::ConstantStruct::getAnon(Data);
2084}
2085
2086void CodeGenFunction::EmitCheck(llvm::Value *Checked, StringRef CheckName,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002087 ArrayRef<llvm::Constant *> StaticArgs,
2088 ArrayRef<llvm::Value *> DynamicArgs,
Will Dietz88e02332012-12-02 19:50:33 +00002089 CheckRecoverableKind RecoverKind) {
Will Dietzf54319c2013-01-18 11:30:38 +00002090 assert(SanOpts != &SanitizerOptions::Disabled);
Chad Rosierae229d52013-01-29 23:31:22 +00002091
2092 if (CGM.getCodeGenOpts().SanitizeUndefinedTrapOnError) {
2093 assert (RecoverKind != CRK_AlwaysRecoverable &&
2094 "Runtime call required for AlwaysRecoverable kind!");
2095 return EmitTrapCheck(Checked);
2096 }
2097
Richard Smith4d1458e2012-09-08 02:08:36 +00002098 llvm::BasicBlock *Cont = createBasicBlock("cont");
2099
Richard Smithe30752c2012-10-09 19:52:38 +00002100 llvm::BasicBlock *Handler = createBasicBlock("handler." + CheckName);
Will Dietzddd282a2012-12-15 01:39:14 +00002101
2102 llvm::Instruction *Branch = Builder.CreateCondBr(Checked, Cont, Handler);
2103
2104 // Give hint that we very much don't expect to execute the handler
2105 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2106 llvm::MDBuilder MDHelper(getLLVMContext());
2107 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2108 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
2109
Richard Smithe30752c2012-10-09 19:52:38 +00002110 EmitBlock(Handler);
2111
2112 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2113 llvm::GlobalValue *InfoPtr =
Will Dietz450f1a12013-01-09 03:39:41 +00002114 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
Richard Smithe30752c2012-10-09 19:52:38 +00002115 llvm::GlobalVariable::PrivateLinkage, Info);
2116 InfoPtr->setUnnamedAddr(true);
2117
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002118 SmallVector<llvm::Value *, 4> Args;
2119 SmallVector<llvm::Type *, 4> ArgTypes;
Richard Smithe30752c2012-10-09 19:52:38 +00002120 Args.reserve(DynamicArgs.size() + 1);
2121 ArgTypes.reserve(DynamicArgs.size() + 1);
2122
2123 // Handler functions take an i8* pointing to the (handler-specific) static
2124 // information block, followed by a sequence of intptr_t arguments
2125 // representing operand values.
2126 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2127 ArgTypes.push_back(Int8PtrTy);
2128 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2129 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2130 ArgTypes.push_back(IntPtrTy);
2131 }
2132
Will Dietz88e02332012-12-02 19:50:33 +00002133 bool Recover = (RecoverKind == CRK_AlwaysRecoverable) ||
2134 ((RecoverKind == CRK_Recoverable) &&
2135 CGM.getCodeGenOpts().SanitizeRecover);
2136
Richard Smithe30752c2012-10-09 19:52:38 +00002137 llvm::FunctionType *FnType =
2138 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Bill Wendlinga514ebc2012-10-15 20:36:26 +00002139 llvm::AttrBuilder B;
Will Dietz88e02332012-12-02 19:50:33 +00002140 if (!Recover) {
Bill Wendling207f0532012-12-20 19:27:06 +00002141 B.addAttribute(llvm::Attribute::NoReturn)
2142 .addAttribute(llvm::Attribute::NoUnwind);
Richard Smith4d3110a2012-10-25 02:14:12 +00002143 }
Bill Wendling207f0532012-12-20 19:27:06 +00002144 B.addAttribute(llvm::Attribute::UWTable);
Will Dietz88e02332012-12-02 19:50:33 +00002145
2146 // Checks that have two variants use a suffix to differentiate them
2147 bool NeedsAbortSuffix = (RecoverKind != CRK_Unrecoverable) &&
2148 !CGM.getCodeGenOpts().SanitizeRecover;
Richard Smith78f6b032012-12-03 22:39:14 +00002149 std::string FunctionName = ("__ubsan_handle_" + CheckName +
2150 (NeedsAbortSuffix? "_abort" : "")).str();
2151 llvm::Value *Fn =
2152 CGM.CreateRuntimeFunction(FnType, FunctionName,
Bill Wendling8594fcb2013-01-31 00:30:05 +00002153 llvm::AttributeSet::get(getLLVMContext(),
2154 llvm::AttributeSet::FunctionIndex,
2155 B));
Richard Smithe30752c2012-10-09 19:52:38 +00002156 llvm::CallInst *HandlerCall = Builder.CreateCall(Fn, Args);
Will Dietz88e02332012-12-02 19:50:33 +00002157 if (Recover) {
Richard Smith4d3110a2012-10-25 02:14:12 +00002158 Builder.CreateBr(Cont);
2159 } else {
2160 HandlerCall->setDoesNotReturn();
2161 HandlerCall->setDoesNotThrow();
2162 Builder.CreateUnreachable();
2163 }
Richard Smithe30752c2012-10-09 19:52:38 +00002164
Richard Smith4d1458e2012-09-08 02:08:36 +00002165 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002166}
2167
Chad Rosierae229d52013-01-29 23:31:22 +00002168void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00002169 llvm::BasicBlock *Cont = createBasicBlock("cont");
2170
2171 // If we're optimizing, collapse all calls to trap down to just one per
2172 // function to save on code size.
2173 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2174 TrapBB = createBasicBlock("trap");
2175 Builder.CreateCondBr(Checked, Cont, TrapBB);
2176 EmitBlock(TrapBB);
2177 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap);
2178 llvm::CallInst *TrapCall = Builder.CreateCall(F);
2179 TrapCall->setDoesNotReturn();
2180 TrapCall->setDoesNotThrow();
2181 Builder.CreateUnreachable();
2182 } else {
2183 Builder.CreateCondBr(Checked, Cont, TrapBB);
2184 }
2185
2186 EmitBlock(Cont);
2187}
2188
Chris Lattner6c5abe82010-06-26 23:03:20 +00002189/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2190/// array to pointer, return the array subexpression.
2191static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2192 // If this isn't just an array->pointer decay, bail out.
2193 const CastExpr *CE = dyn_cast<CastExpr>(E);
John McCalle3027922010-08-25 11:45:40 +00002194 if (CE == 0 || CE->getCastKind() != CK_ArrayToPointerDecay)
Chris Lattner6c5abe82010-06-26 23:03:20 +00002195 return 0;
2196
2197 // If this is a decay from variable width array, bail out.
2198 const Expr *SubExpr = CE->getSubExpr();
2199 if (SubExpr->getType()->isVariableArrayType())
2200 return 0;
2201
2202 return SubExpr;
2203}
2204
Richard Smith539e4a72013-02-23 02:53:19 +00002205LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2206 bool Accessed) {
Ted Kremenekc81614d2007-08-20 16:18:38 +00002207 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner2da04b32007-08-24 05:35:26 +00002208 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Eli Friedman07bbeca2009-06-06 19:09:26 +00002209 QualType IdxTy = E->getIdx()->getType();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002210 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Eli Friedman07bbeca2009-06-06 19:09:26 +00002211
Richard Smith539e4a72013-02-23 02:53:19 +00002212 if (SanOpts->Bounds)
2213 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
2214
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002215 // If the base is a vector type, then we are forming a vector element lvalue
2216 // with this subscript.
Eli Friedman327944b2008-06-13 23:01:12 +00002217 if (E->getBase()->getType()->isVectorType()) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002218 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00002219 LValue LHS = EmitLValue(E->getBase());
Ted Kremenekc81614d2007-08-20 16:18:38 +00002220 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
John McCallad7c5c12011-02-08 08:22:06 +00002221 Idx = Builder.CreateIntCast(Idx, Int32Ty, IdxSigned, "vidx");
Eli Friedman327944b2008-06-13 23:01:12 +00002222 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
Eli Friedman610bb872012-03-22 22:36:39 +00002223 E->getBase()->getType(), LHS.getAlignment());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002224 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002225
Ted Kremenekc81614d2007-08-20 16:18:38 +00002226 // Extend or truncate the index type to 32 or 64-bits.
John McCalle3dc1702011-02-15 09:22:45 +00002227 if (Idx->getType() != IntPtrTy)
2228 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
Mike Stumpd9546382009-12-12 01:27:46 +00002229
Mike Stump4a3999f2009-09-09 13:00:44 +00002230 // We know that the pointer points to a type of the correct size, unless the
2231 // size is a VLA or Objective-C interface.
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002232 llvm::Value *Address = 0;
Eli Friedmana0544d62011-12-03 04:14:32 +00002233 CharUnits ArrayAlignment;
John McCall23c29fe2011-06-24 21:55:10 +00002234 if (const VariableArrayType *vla =
Anders Carlsson3d312f82008-12-21 00:11:23 +00002235 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00002236 // The base must be a pointer, which is not an aggregate. Emit
2237 // it. It needs to be emitted first in case it's what captures
2238 // the VLA bounds.
2239 Address = EmitScalarExpr(E->getBase());
Mike Stump4a3999f2009-09-09 13:00:44 +00002240
John McCall23c29fe2011-06-24 21:55:10 +00002241 // The element count here is the total number of non-VLA elements.
2242 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00002243
John McCall77527a82011-06-25 01:32:37 +00002244 // Effectively, the multiply by the VLA size is part of the GEP.
2245 // GEP indexes are signed, and scaling an index isn't permitted to
2246 // signed-overflow, so we use the same semantics for our explicit
2247 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002248 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00002249 Idx = Builder.CreateMul(Idx, numElements);
Chris Lattner2e72da942011-03-01 00:03:48 +00002250 Address = Builder.CreateGEP(Address, Idx, "arrayidx");
John McCall77527a82011-06-25 01:32:37 +00002251 } else {
2252 Idx = Builder.CreateNSWMul(Idx, numElements);
Chris Lattner2e72da942011-03-01 00:03:48 +00002253 Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
John McCall77527a82011-06-25 01:32:37 +00002254 }
Chris Lattner6c5abe82010-06-26 23:03:20 +00002255 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
2256 // Indexing over an interface, as in "NSString *P; P[4];"
Mike Stump4a3999f2009-09-09 13:00:44 +00002257 llvm::Value *InterfaceSize =
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002258 llvm::ConstantInt::get(Idx->getType(),
Ken Dyck40775002010-01-11 17:06:35 +00002259 getContext().getTypeSizeInChars(OIT).getQuantity());
Mike Stump4a3999f2009-09-09 13:00:44 +00002260
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002261 Idx = Builder.CreateMul(Idx, InterfaceSize);
2262
Chris Lattner6c5abe82010-06-26 23:03:20 +00002263 // The base must be a pointer, which is not an aggregate. Emit it.
2264 llvm::Value *Base = EmitScalarExpr(E->getBase());
John McCallad7c5c12011-02-08 08:22:06 +00002265 Address = EmitCastToVoidPtr(Base);
2266 Address = Builder.CreateGEP(Address, Idx, "arrayidx");
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002267 Address = Builder.CreateBitCast(Address, Base->getType());
Chris Lattner6c5abe82010-06-26 23:03:20 +00002268 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
2269 // If this is A[i] where A is an array, the frontend will have decayed the
2270 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
2271 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
2272 // "gep x, i" here. Emit one "gep A, 0, i".
2273 assert(Array->getType()->isArrayType() &&
2274 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00002275 LValue ArrayLV;
2276 // For simple multidimensional array indexing, set the 'accessed' flag for
2277 // better bounds-checking of the base expression.
2278 if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(Array))
2279 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
2280 else
2281 ArrayLV = EmitLValue(Array);
Daniel Dunbar82634272011-04-01 00:49:43 +00002282 llvm::Value *ArrayPtr = ArrayLV.getAddress();
Chris Lattner6c5abe82010-06-26 23:03:20 +00002283 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
2284 llvm::Value *Args[] = { Zero, Idx };
2285
Daniel Dunbar82634272011-04-01 00:49:43 +00002286 // Propagate the alignment from the array itself to the result.
2287 ArrayAlignment = ArrayLV.getAlignment();
2288
Richard Smith9c6890a2012-11-01 22:30:59 +00002289 if (getLangOpts().isSignedOverflowDefined())
Jay Foad040dd822011-07-22 08:16:57 +00002290 Address = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
Chris Lattner2e72da942011-03-01 00:03:48 +00002291 else
Jay Foad040dd822011-07-22 08:16:57 +00002292 Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002293 } else {
Chris Lattner6c5abe82010-06-26 23:03:20 +00002294 // The base must be a pointer, which is not an aggregate. Emit it.
2295 llvm::Value *Base = EmitScalarExpr(E->getBase());
Richard Smith9c6890a2012-11-01 22:30:59 +00002296 if (getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00002297 Address = Builder.CreateGEP(Base, Idx, "arrayidx");
2298 else
2299 Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
Anders Carlsson3d312f82008-12-21 00:11:23 +00002300 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002301
Steve Naroff7cae42b2009-07-10 23:34:53 +00002302 QualType T = E->getBase()->getType()->getPointeeType();
Mike Stump4a3999f2009-09-09 13:00:44 +00002303 assert(!T.isNull() &&
Steve Naroff7cae42b2009-07-10 23:34:53 +00002304 "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002305
Chris Lattner36bc4f42012-01-04 22:35:55 +00002306
Daniel Dunbar82634272011-04-01 00:49:43 +00002307 // Limit the alignment to that of the result type.
Chris Lattner36bc4f42012-01-04 22:35:55 +00002308 LValue LV;
Eli Friedmana0544d62011-12-03 04:14:32 +00002309 if (!ArrayAlignment.isZero()) {
2310 CharUnits Align = getContext().getTypeAlignInChars(T);
Daniel Dunbar82634272011-04-01 00:49:43 +00002311 ArrayAlignment = std::min(Align, ArrayAlignment);
Chris Lattner36bc4f42012-01-04 22:35:55 +00002312 LV = MakeAddrLValue(Address, T, ArrayAlignment);
2313 } else {
2314 LV = MakeNaturalAlignAddrLValue(Address, T);
Daniel Dunbar82634272011-04-01 00:49:43 +00002315 }
2316
Daniel Dunbarf166a522010-08-21 03:44:13 +00002317 LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002318
Richard Smith9c6890a2012-11-01 22:30:59 +00002319 if (getLangOpts().ObjC1 &&
2320 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00002321 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002322 setObjCGCLValueClass(getContext(), E, LV);
2323 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00002324 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00002325}
2326
Mike Stump4a3999f2009-09-09 13:00:44 +00002327static
NAKAMURA Takumiccca11a2012-01-25 08:58:21 +00002328llvm::Constant *GenerateConstantVector(CGBuilderTy &Builder,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002329 SmallVector<unsigned, 4> &Elts) {
2330 SmallVector<llvm::Constant*, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00002331 for (unsigned i = 0, e = Elts.size(); i != e; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002332 CElts.push_back(Builder.getInt32(Elts[i]));
Nate Begemand3862152008-05-13 21:03:02 +00002333
Chris Lattner91c08ad2011-02-15 00:14:06 +00002334 return llvm::ConstantVector::get(CElts);
Nate Begemand3862152008-05-13 21:03:02 +00002335}
2336
Chris Lattner9e751ca2007-08-02 23:37:31 +00002337LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002338EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00002339 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00002340 LValue Base;
2341
2342 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00002343 if (E->isArrow()) {
2344 // If it is a pointer to a vector, emit the address and form an lvalue with
2345 // it.
Chris Lattnerb8211f62009-02-16 22:14:05 +00002346 llvm::Value *Ptr = EmitScalarExpr(E->getBase());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002347 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
Daniel Dunbarf166a522010-08-21 03:44:13 +00002348 Base = MakeAddrLValue(Ptr, PT->getPointeeType());
2349 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00002350 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00002351 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
2352 // emit the base as an lvalue.
2353 assert(E->getBase()->getType()->isVectorType());
2354 Base = EmitLValue(E->getBase());
2355 } else {
2356 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00002357 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00002358 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00002359 llvm::Value *Vec = EmitScalarExpr(E->getBase());
2360
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00002361 // Store the vector to memory (because LValue wants an address).
Daniel Dunbara7566f12010-02-09 02:48:28 +00002362 llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002363 Builder.CreateStore(Vec, VecMem);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002364 Base = MakeAddrLValue(VecMem, E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002365 }
John McCall1553b192011-06-16 04:16:24 +00002366
2367 QualType type =
2368 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002369
Nate Begemand3862152008-05-13 21:03:02 +00002370 // Encode the element access list into a vector of unsigned indices.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002371 SmallVector<unsigned, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00002372 E->getEncodedElementAccess(Indices);
2373
2374 if (Base.isSimple()) {
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002375 llvm::Constant *CV = GenerateConstantVector(Builder, Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00002376 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
2377 Base.getAlignment());
Nate Begemand3862152008-05-13 21:03:02 +00002378 }
2379 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
2380
2381 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002382 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00002383
Chris Lattner595ba3a2012-01-30 06:20:36 +00002384 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
2385 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00002386 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
Eli Friedman610bb872012-03-22 22:36:39 +00002387 return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type,
2388 Base.getAlignment());
Chris Lattner9e751ca2007-08-02 23:37:31 +00002389}
2390
Devang Patel30efa2e2007-10-23 20:28:39 +00002391LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00002392 Expr *BaseExpr = E->getBase();
Eli Friedman327944b2008-06-13 23:01:12 +00002393
Chris Lattner4e4186b2007-12-02 18:52:07 +00002394 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
Eli Friedman7f1ff602012-04-16 03:54:45 +00002395 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00002396 if (E->isArrow()) {
2397 llvm::Value *Ptr = EmitScalarExpr(BaseExpr);
2398 QualType PtrTy = BaseExpr->getType()->getPointeeType();
Richard Smithe30752c2012-10-09 19:52:38 +00002399 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Ptr, PtrTy);
Richard Smith69d0d262012-08-24 00:54:33 +00002400 BaseLV = MakeNaturalAlignAddrLValue(Ptr, PtrTy);
2401 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00002402 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00002403
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002404 NamedDecl *ND = E->getMemberDecl();
2405 if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00002406 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002407 setObjCGCLValueClass(getContext(), E, LV);
2408 return LV;
2409 }
2410
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00002411 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
2412 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002413
2414 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
2415 return EmitFunctionDeclLValue(*this, E, FD);
2416
David Blaikie83d382b2011-09-23 05:06:16 +00002417 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00002418}
Devang Patel30efa2e2007-10-23 20:28:39 +00002419
Eli Friedman7f1ff602012-04-16 03:54:45 +00002420LValue CodeGenFunction::EmitLValueForField(LValue base,
2421 const FieldDecl *field) {
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00002422 if (field->isBitField()) {
2423 const CGRecordLayout &RL =
2424 CGM.getTypes().getCGRecordLayout(field->getParent());
2425 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002426 llvm::Value *Addr = base.getAddress();
2427 unsigned Idx = RL.getLLVMFieldNo(field);
2428 if (Idx != 0)
2429 // For structs, we GEP to the field that the record layout suggests.
2430 Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
2431 // Get the access type.
2432 llvm::Type *PtrTy = llvm::Type::getIntNPtrTy(
2433 getLLVMContext(), Info.StorageSize,
2434 CGM.getContext().getTargetAddressSpace(base.getType()));
2435 if (Addr->getType() != PtrTy)
2436 Addr = Builder.CreateBitCast(Addr, PtrTy);
2437
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00002438 QualType fieldType =
2439 field->getType().withCVRQualifiers(base.getVRQualifiers());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002440 return LValue::MakeBitfield(Addr, Info, fieldType, base.getAlignment());
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00002441 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002442
John McCall53fcbd22011-02-26 08:07:02 +00002443 const RecordDecl *rec = field->getParent();
2444 QualType type = field->getType();
Eli Friedmana0544d62011-12-03 04:14:32 +00002445 CharUnits alignment = getContext().getDeclAlign(field);
Eli Friedman133e8042008-05-29 11:33:25 +00002446
Eli Friedman7f1ff602012-04-16 03:54:45 +00002447 // FIXME: It should be impossible to have an LValue without alignment for a
2448 // complete type.
2449 if (!base.getAlignment().isZero())
2450 alignment = std::min(alignment, base.getAlignment());
2451
John McCall53fcbd22011-02-26 08:07:02 +00002452 bool mayAlias = rec->hasAttr<MayAliasAttr>();
2453
Eli Friedman7f1ff602012-04-16 03:54:45 +00002454 llvm::Value *addr = base.getAddress();
2455 unsigned cvr = base.getVRQualifiers();
John McCall53fcbd22011-02-26 08:07:02 +00002456 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00002457 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00002458 assert(!type->isReferenceType() && "union has reference member");
John McCall53fcbd22011-02-26 08:07:02 +00002459 } else {
2460 // For structs, we GEP to the field that the record layout suggests.
2461 unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
Chris Lattner13ee4f42011-07-10 05:34:54 +00002462 addr = Builder.CreateStructGEP(addr, idx, field->getName());
John McCall53fcbd22011-02-26 08:07:02 +00002463
2464 // If this is a reference field, load the reference right now.
2465 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
2466 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
2467 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
Eli Friedmana0544d62011-12-03 04:14:32 +00002468 load->setAlignment(alignment.getQuantity());
John McCall53fcbd22011-02-26 08:07:02 +00002469
2470 if (CGM.shouldUseTBAA()) {
2471 llvm::MDNode *tbaa;
2472 if (mayAlias)
2473 tbaa = CGM.getTBAAInfo(getContext().CharTy);
2474 else
2475 tbaa = CGM.getTBAAInfo(type);
2476 CGM.DecorateInstruction(load, tbaa);
2477 }
2478
2479 addr = load;
2480 mayAlias = false;
2481 type = refType->getPointeeType();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002482 if (type->isIncompleteType())
Eli Friedmana0544d62011-12-03 04:14:32 +00002483 alignment = CharUnits();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002484 else
Eli Friedmana0544d62011-12-03 04:14:32 +00002485 alignment = getContext().getTypeAlignInChars(type);
John McCall53fcbd22011-02-26 08:07:02 +00002486 cvr = 0; // qualifiers don't recursively apply to referencee
2487 }
Devang Pateled93c3c2007-10-26 19:42:18 +00002488 }
Chris Lattner13ee4f42011-07-10 05:34:54 +00002489
2490 // Make sure that the address is pointing to the right type. This is critical
2491 // for both unions and structs. A union needs a bitcast, a struct element
2492 // will need a bitcast if the LLVM type laid out doesn't match the desired
2493 // type.
Chandler Carruth4678f672011-07-12 08:58:26 +00002494 addr = EmitBitCastOfLValueToProperType(*this, addr,
Chris Lattner3f32d692011-07-12 06:52:18 +00002495 CGM.getTypes().ConvertTypeForMem(type),
2496 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00002497
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002498 if (field->hasAttr<AnnotateAttr>())
2499 addr = EmitFieldAnnotations(field, addr);
2500
John McCall53fcbd22011-02-26 08:07:02 +00002501 LValue LV = MakeAddrLValue(addr, type, alignment);
2502 LV.getQuals().addCVRQualifiers(cvr);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002503
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002504 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00002505 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
2506 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00002507
2508 // Fields of may_alias structs act like 'char' for TBAA purposes.
2509 // FIXME: this should get propagated down through anonymous structs
2510 // and unions.
2511 if (mayAlias && LV.getTBAAInfo())
2512 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
2513
Daniel Dunbarf166a522010-08-21 03:44:13 +00002514 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00002515}
2516
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002517LValue
Eli Friedman7f1ff602012-04-16 03:54:45 +00002518CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
2519 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002520 QualType FieldType = Field->getType();
2521
2522 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00002523 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002524
Daniel Dunbar034299e2010-03-31 01:09:11 +00002525 const CGRecordLayout &RL =
2526 CGM.getTypes().getCGRecordLayout(Field->getParent());
2527 unsigned idx = RL.getLLVMFieldNo(Field);
Eli Friedman7f1ff602012-04-16 03:54:45 +00002528 llvm::Value *V = Builder.CreateStructGEP(Base.getAddress(), idx);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002529 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
2530
Chris Lattnerd7c59352011-07-10 05:53:24 +00002531 // Make sure that the address is pointing to the right type. This is critical
2532 // for both unions and structs. A union needs a bitcast, a struct element
2533 // will need a bitcast if the LLVM type laid out doesn't match the desired
2534 // type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002535 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
Eli Friedman7f1ff602012-04-16 03:54:45 +00002536 V = EmitBitCastOfLValueToProperType(*this, V, llvmType, Field->getName());
2537
Eli Friedmana0544d62011-12-03 04:14:32 +00002538 CharUnits Alignment = getContext().getDeclAlign(Field);
Eli Friedman7f1ff602012-04-16 03:54:45 +00002539
2540 // FIXME: It should be impossible to have an LValue without alignment for a
2541 // complete type.
2542 if (!Base.getAlignment().isZero())
2543 Alignment = std::min(Alignment, Base.getAlignment());
2544
Daniel Dunbar5c816372010-08-21 04:20:22 +00002545 return MakeAddrLValue(V, FieldType, Alignment);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002546}
2547
Chris Lattnerf53c0962010-09-06 00:11:41 +00002548LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00002549 if (E->isFileScope()) {
2550 llvm::Value *GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
2551 return MakeAddrLValue(GlobalPtr, E->getType());
2552 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00002553 if (E->getType()->isVariablyModifiedType())
2554 // make sure to emit the VLA size.
2555 EmitVariablyModifiedType(E->getType());
Fariborz Jahanianbbc5bbf2012-06-07 17:07:15 +00002556
Daniel Dunbar27bacaf2010-02-16 19:43:39 +00002557 llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00002558 const Expr *InitExpr = E->getInitializer();
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002559 LValue Result = MakeAddrLValue(DeclPtr, E->getType());
Eli Friedman9fd8b682008-05-13 23:18:27 +00002560
Chad Rosier615ed1a2012-03-29 17:37:10 +00002561 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
2562 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00002563
2564 return Result;
2565}
2566
Richard Smithbb653bd2012-05-14 21:57:21 +00002567LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
2568 if (!E->isGLValue())
2569 // Initializing an aggregate temporary in C++11: T{...}.
2570 return EmitAggExprToLValue(E);
2571
2572 // An lvalue initializer list must be initializing a reference.
2573 assert(E->getNumInits() == 1 && "reference init with multiple values");
2574 return EmitLValue(E->getInit(0));
2575}
2576
John McCallc07a0c72011-02-17 10:25:35 +00002577LValue CodeGenFunction::
2578EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
2579 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00002580 // ?: here should be an aggregate.
John McCallc07a0c72011-02-17 10:25:35 +00002581 assert((hasAggregateLLVMType(expr->getType()) &&
2582 !expr->getType()->isAnyComplexType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00002583 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00002584 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00002585 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00002586
Eli Friedman59954892012-01-25 05:04:17 +00002587 OpaqueValueMapping binding(*this, expr);
2588
John McCallc07a0c72011-02-17 10:25:35 +00002589 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00002590 bool CondExprBool;
2591 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00002592 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00002593 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00002594
2595 if (!ContainsLabel(dead))
2596 return EmitLValue(live);
John McCall0a6bf2e2011-01-26 19:21:13 +00002597 }
2598
John McCallc07a0c72011-02-17 10:25:35 +00002599 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
2600 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
2601 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00002602
2603 ConditionalEvaluation eval(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002604 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002605
2606 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00002607 EmitBlock(lhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002608 eval.begin(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002609 LValue lhs = EmitLValue(expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00002610 eval.end(*this);
2611
John McCallc07a0c72011-02-17 10:25:35 +00002612 if (!lhs.isSimple())
2613 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00002614
John McCallc07a0c72011-02-17 10:25:35 +00002615 lhsBlock = Builder.GetInsertBlock();
2616 Builder.CreateBr(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002617
2618 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00002619 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002620 eval.begin(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002621 LValue rhs = EmitLValue(expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00002622 eval.end(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002623 if (!rhs.isSimple())
2624 return EmitUnsupportedLValue(expr, "conditional operator");
2625 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00002626
John McCallc07a0c72011-02-17 10:25:35 +00002627 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002628
Jay Foad20c0f022011-03-30 11:28:58 +00002629 llvm::PHINode *phi = Builder.CreatePHI(lhs.getAddress()->getType(), 2,
John McCall0a6bf2e2011-01-26 19:21:13 +00002630 "cond-lvalue");
John McCallc07a0c72011-02-17 10:25:35 +00002631 phi->addIncoming(lhs.getAddress(), lhsBlock);
2632 phi->addIncoming(rhs.getAddress(), rhsBlock);
2633 return MakeAddrLValue(phi, expr->getType());
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00002634}
2635
Richard Smithbb653bd2012-05-14 21:57:21 +00002636/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
2637/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00002638/// otherwise if a cast is needed by the code generator in an lvalue context,
2639/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00002640/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00002641/// are permitted with aggregate result, including noop aggregate casts, and
2642/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00002643LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00002644 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00002645 case CK_ToVoid:
Eli Friedman8c98dff2009-11-16 05:48:01 +00002646 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
John McCall8cb679e2010-11-15 09:13:47 +00002647
2648 case CK_Dependent:
2649 llvm_unreachable("dependent cast kind in IR gen!");
Eli Friedman34866c72012-08-31 00:14:07 +00002650
2651 case CK_BuiltinFnToFnPtr:
2652 llvm_unreachable("builtin functions are handled elsewhere");
2653
David Chisnallfa35df62012-01-16 17:27:18 +00002654 // These two casts are currently treated as no-ops, although they could
2655 // potentially be real operations depending on the target's ABI.
2656 case CK_NonAtomicToAtomic:
2657 case CK_AtomicToNonAtomic:
John McCall8cb679e2010-11-15 09:13:47 +00002658
John McCalle3027922010-08-25 11:45:40 +00002659 case CK_NoOp:
Douglas Gregor21d3fca2011-01-27 23:22:05 +00002660 case CK_LValueToRValue:
2661 if (!E->getSubExpr()->Classify(getContext()).isPRValue()
2662 || E->getType()->isRecordType())
John McCalle26a8722010-12-04 08:14:53 +00002663 return EmitLValue(E->getSubExpr());
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002664 // Fall through to synthesize a temporary.
John McCall8cb679e2010-11-15 09:13:47 +00002665
John McCalle3027922010-08-25 11:45:40 +00002666 case CK_BitCast:
2667 case CK_ArrayToPointerDecay:
2668 case CK_FunctionToPointerDecay:
2669 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00002670 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00002671 case CK_IntegralToPointer:
2672 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00002673 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00002674 case CK_VectorSplat:
2675 case CK_IntegralCast:
John McCall8cb679e2010-11-15 09:13:47 +00002676 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00002677 case CK_IntegralToFloating:
2678 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00002679 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00002680 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00002681 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00002682 case CK_FloatingComplexToReal:
2683 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00002684 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00002685 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00002686 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00002687 case CK_IntegralComplexToReal:
2688 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00002689 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00002690 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00002691 case CK_DerivedToBaseMemberPointer:
2692 case CK_BaseToDerivedMemberPointer:
2693 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00002694 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00002695 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00002696 case CK_ARCProduceObject:
2697 case CK_ARCConsumeObject:
2698 case CK_ARCReclaimReturnedObject:
Douglas Gregored90df32012-02-22 05:02:47 +00002699 case CK_ARCExtendBlockObject:
2700 case CK_CopyAndAutoreleaseBlockObject: {
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002701 // These casts only produce lvalues when we're binding a reference to a
2702 // temporary realized from a (converted) pure rvalue. Emit the expression
2703 // as a value, copy it into a temporary, and return an lvalue referring to
2704 // that temporary.
2705 llvm::Value *V = CreateMemTemp(E->getType(), "ref.temp");
Chad Rosier615ed1a2012-03-29 17:37:10 +00002706 EmitAnyExprToMem(E, V, E->getType().getQualifiers(), false);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002707 return MakeAddrLValue(V, E->getType());
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002708 }
Eli Friedman8c98dff2009-11-16 05:48:01 +00002709
Anders Carlsson8a01a752011-04-11 02:03:26 +00002710 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00002711 LValue LV = EmitLValue(E->getSubExpr());
2712 llvm::Value *V = LV.getAddress();
2713 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002714 return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00002715 }
2716
John McCalle3027922010-08-25 11:45:40 +00002717 case CK_ConstructorConversion:
2718 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00002719 case CK_CPointerToObjCPointerCast:
2720 case CK_BlockPointerToObjCPointerCast:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00002721 return EmitLValue(E->getSubExpr());
Anders Carlssond95f9602009-09-12 16:16:49 +00002722
John McCalle3027922010-08-25 11:45:40 +00002723 case CK_UncheckedDerivedToBase:
2724 case CK_DerivedToBase: {
Anders Carlssond95f9602009-09-12 16:16:49 +00002725 const RecordType *DerivedClassTy =
2726 E->getSubExpr()->getType()->getAs<RecordType>();
2727 CXXRecordDecl *DerivedClassDecl =
2728 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Anders Carlssond95f9602009-09-12 16:16:49 +00002729
2730 LValue LV = EmitLValue(E->getSubExpr());
John McCalle26a8722010-12-04 08:14:53 +00002731 llvm::Value *This = LV.getAddress();
Anders Carlssond95f9602009-09-12 16:16:49 +00002732
2733 // Perform the derived-to-base conversion
2734 llvm::Value *Base =
Fariborz Jahanian64cda8b2010-06-17 23:00:29 +00002735 GetAddressOfBaseClass(This, DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00002736 E->path_begin(), E->path_end(),
2737 /*NullCheckValue=*/false);
Anders Carlssond95f9602009-09-12 16:16:49 +00002738
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002739 return MakeAddrLValue(Base, E->getType());
Anders Carlssond95f9602009-09-12 16:16:49 +00002740 }
John McCalle3027922010-08-25 11:45:40 +00002741 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00002742 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00002743 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00002744 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
2745 CXXRecordDecl *DerivedClassDecl =
2746 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
2747
2748 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00002749
2750 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
2751 // performed and the object is not of the derived type.
2752 if (SanitizePerformTypeCheck)
2753 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
2754 LV.getAddress(), E->getType());
2755
Anders Carlsson8c793172009-11-23 17:57:54 +00002756 // Perform the base-to-derived conversion
2757 llvm::Value *Derived =
Anders Carlsson8a64c1c2010-04-24 21:23:59 +00002758 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00002759 E->path_begin(), E->path_end(),
2760 /*NullCheckValue=*/false);
Anders Carlsson8c793172009-11-23 17:57:54 +00002761
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002762 return MakeAddrLValue(Derived, E->getType());
Eli Friedman8c98dff2009-11-16 05:48:01 +00002763 }
John McCalle3027922010-08-25 11:45:40 +00002764 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00002765 // This must be a reinterpret_cast (or c-style equivalent).
2766 const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E);
Anders Carlsson50cb3212009-11-14 21:21:42 +00002767
2768 LValue LV = EmitLValue(E->getSubExpr());
2769 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2770 ConvertType(CE->getTypeAsWritten()));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002771 return MakeAddrLValue(V, E->getType());
Anders Carlsson50cb3212009-11-14 21:21:42 +00002772 }
John McCalle3027922010-08-25 11:45:40 +00002773 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002774 LValue LV = EmitLValue(E->getSubExpr());
2775 QualType ToType = getContext().getLValueReferenceType(E->getType());
2776 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2777 ConvertType(ToType));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002778 return MakeAddrLValue(V, E->getType());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002779 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002780 case CK_ZeroToOCLEvent:
2781 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00002782 }
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002783
2784 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00002785}
2786
Fariborz Jahaniane4d94ce2009-10-20 23:29:04 +00002787LValue CodeGenFunction::EmitNullInitializationLValue(
Douglas Gregor747eb782010-07-08 06:14:04 +00002788 const CXXScalarValueInitExpr *E) {
Fariborz Jahaniane4d94ce2009-10-20 23:29:04 +00002789 QualType Ty = E->getType();
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002790 LValue LV = MakeAddrLValue(CreateMemTemp(Ty), Ty);
Anders Carlssonc0964b62010-05-22 17:35:42 +00002791 EmitNullInitialization(LV.getAddress(), Ty);
Daniel Dunbara7566f12010-02-09 02:48:28 +00002792 return LV;
Fariborz Jahaniane4d94ce2009-10-20 23:29:04 +00002793}
2794
John McCall1bf58462011-02-16 08:02:54 +00002795LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00002796 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00002797 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00002798}
2799
Douglas Gregorfe314812011-06-21 17:03:29 +00002800LValue CodeGenFunction::EmitMaterializeTemporaryExpr(
2801 const MaterializeTemporaryExpr *E) {
John McCall17054bd62011-08-26 21:08:13 +00002802 RValue RV = EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
Douglas Gregord410c082011-06-21 18:20:46 +00002803 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Douglas Gregorfe314812011-06-21 17:03:29 +00002804}
2805
Eli Friedman7f1ff602012-04-16 03:54:45 +00002806RValue CodeGenFunction::EmitRValueForField(LValue LV,
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002807 const FieldDecl *FD) {
2808 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00002809 LValue FieldLV = EmitLValueForField(LV, FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002810 if (FT->isAnyComplexType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00002811 return RValue::getComplex(
2812 LoadComplexFromAddr(FieldLV.getAddress(),
2813 FieldLV.isVolatileQualified()));
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002814 else if (CodeGenFunction::hasAggregateLLVMType(FT))
Eli Friedman7f1ff602012-04-16 03:54:45 +00002815 return FieldLV.asAggregateRValue();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002816
Eli Friedman7f1ff602012-04-16 03:54:45 +00002817 return EmitLoadOfLValue(FieldLV);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002818}
Douglas Gregorfe314812011-06-21 17:03:29 +00002819
Chris Lattnere47e4402007-06-01 18:02:12 +00002820//===--------------------------------------------------------------------===//
2821// Expression Emission
2822//===--------------------------------------------------------------------===//
2823
Anders Carlsson17490832009-12-24 20:40:36 +00002824RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
2825 ReturnValueSlot ReturnValue) {
Eric Christopher7cdf9482011-10-13 21:45:18 +00002826 if (CGDebugInfo *DI = getDebugInfo())
2827 DI->EmitLocation(Builder, E->getLocStart());
Devang Pateld3a6b0f2011-03-04 18:54:42 +00002828
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002829 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00002830 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00002831 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00002832
Anders Carlssone5fd6f22009-04-03 22:50:24 +00002833 if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00002834 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00002835
Peter Collingbournefe883422011-10-06 18:29:37 +00002836 if (const CUDAKernelCallExpr *CE = dyn_cast<CUDAKernelCallExpr>(E))
2837 return EmitCUDAKernelCallExpr(CE, ReturnValue);
2838
Douglas Gregore0e96302011-09-06 21:41:04 +00002839 const Decl *TargetDecl = E->getCalleeDecl();
2840 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
2841 if (unsigned builtinID = FD->getBuiltinID())
2842 return EmitBuiltinExpr(FD, builtinID, E);
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002843 }
2844
Chris Lattner4ca97c32009-06-13 00:26:38 +00002845 if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E))
Anders Carlsson4034a952009-05-27 04:18:27 +00002846 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
Anders Carlssonbfb36712009-12-24 21:13:40 +00002847 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00002848
John McCall31168b02011-06-15 23:02:42 +00002849 if (const CXXPseudoDestructorExpr *PseudoDtor
2850 = dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
2851 QualType DestroyedType = PseudoDtor->getDestroyedType();
Richard Smith9c6890a2012-11-01 22:30:59 +00002852 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002853 DestroyedType->isObjCLifetimeType() &&
2854 (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong ||
2855 DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) {
Benjamin Kramerdd19c012011-06-18 10:34:00 +00002856 // Automatic Reference Counting:
2857 // If the pseudo-expression names a retainable object with weak or
2858 // strong lifetime, the object shall be released.
John McCall31168b02011-06-15 23:02:42 +00002859 Expr *BaseExpr = PseudoDtor->getBase();
2860 llvm::Value *BaseValue = NULL;
2861 Qualifiers BaseQuals;
2862
Benjamin Kramerdd19c012011-06-18 10:34:00 +00002863 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
John McCall31168b02011-06-15 23:02:42 +00002864 if (PseudoDtor->isArrow()) {
2865 BaseValue = EmitScalarExpr(BaseExpr);
2866 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
2867 BaseQuals = PTy->getPointeeType().getQualifiers();
2868 } else {
2869 LValue BaseLV = EmitLValue(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00002870 BaseValue = BaseLV.getAddress();
2871 QualType BaseTy = BaseExpr->getType();
2872 BaseQuals = BaseTy.getQualifiers();
2873 }
2874
2875 switch (PseudoDtor->getDestroyedType().getObjCLifetime()) {
2876 case Qualifiers::OCL_None:
2877 case Qualifiers::OCL_ExplicitNone:
2878 case Qualifiers::OCL_Autoreleasing:
2879 break;
2880
2881 case Qualifiers::OCL_Strong:
2882 EmitARCRelease(Builder.CreateLoad(BaseValue,
Benjamin Kramerdd19c012011-06-18 10:34:00 +00002883 PseudoDtor->getDestroyedType().isVolatileQualified()),
John McCall31168b02011-06-15 23:02:42 +00002884 /*precise*/ true);
2885 break;
2886
2887 case Qualifiers::OCL_Weak:
2888 EmitARCDestroyWeak(BaseValue);
2889 break;
2890 }
2891 } else {
2892 // C++ [expr.pseudo]p1:
2893 // The result shall only be used as the operand for the function call
2894 // operator (), and the result of such a call has type void. The only
2895 // effect is the evaluation of the postfix-expression before the dot or
2896 // arrow.
2897 EmitScalarExpr(E->getCallee());
2898 }
2899
Douglas Gregorad8a3362009-09-04 17:36:40 +00002900 return RValue::get(0);
2901 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002902
Chris Lattner2da04b32007-08-24 05:35:26 +00002903 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Anders Carlsson17490832009-12-24 20:40:36 +00002904 return EmitCall(E->getCallee()->getType(), Callee, ReturnValue,
Anders Carlsson3a9463b2009-05-27 01:22:39 +00002905 E->arg_begin(), E->arg_end(), TargetDecl);
Chris Lattner9e47ead2007-08-31 04:44:06 +00002906}
2907
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00002908LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00002909 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00002910 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00002911 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00002912 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00002913 return EmitLValue(E->getRHS());
2914 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002915
John McCalle3027922010-08-25 11:45:40 +00002916 if (E->getOpcode() == BO_PtrMemD ||
2917 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00002918 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00002919
John McCalla2342eb2010-12-05 02:00:02 +00002920 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00002921
2922 // Note that in all of these cases, __block variables need the RHS
2923 // evaluated first just in case the variable gets moved by the RHS.
John McCall4f29b492010-11-16 23:07:28 +00002924
Anders Carlsson0999aaf2009-10-19 18:28:22 +00002925 if (!hasAggregateLLVMType(E->getType())) {
John McCall31168b02011-06-15 23:02:42 +00002926 switch (E->getLHS()->getType().getObjCLifetime()) {
2927 case Qualifiers::OCL_Strong:
2928 return EmitARCStoreStrong(E, /*ignored*/ false).first;
2929
2930 case Qualifiers::OCL_Autoreleasing:
2931 return EmitARCStoreAutoreleasing(E).first;
2932
2933 // No reason to do any of these differently.
2934 case Qualifiers::OCL_None:
2935 case Qualifiers::OCL_ExplicitNone:
2936 case Qualifiers::OCL_Weak:
2937 break;
2938 }
2939
John McCalld0a30012010-12-06 06:10:02 +00002940 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00002941 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
John McCall55e1fbc2011-06-25 02:11:03 +00002942 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00002943 return LV;
2944 }
John McCall4f29b492010-11-16 23:07:28 +00002945
2946 if (E->getType()->isAnyComplexType())
2947 return EmitComplexAssignmentLValue(E);
2948
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00002949 return EmitAggExprToLValue(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00002950}
2951
Christopher Lambd91c3d42007-12-29 05:02:41 +00002952LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00002953 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00002954
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002955 if (!RV.isScalar())
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002956 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002957
2958 assert(E->getCallReturnType()->isReferenceType() &&
2959 "Can't have a scalar return unless the return type is a "
2960 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00002961
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002962 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00002963}
2964
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00002965LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
2966 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00002967 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00002968}
2969
Anders Carlsson3be22e22009-05-30 23:23:33 +00002970LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00002971 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
2972 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002973 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00002974 EmitCXXConstructExpr(E, Slot);
2975 return MakeAddrLValue(Slot.getAddr(), E->getType());
Anders Carlsson3be22e22009-05-30 23:23:33 +00002976}
2977
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00002978LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00002979CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002980 return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00002981}
2982
Nico Webercf4ff5862012-10-11 10:13:44 +00002983llvm::Value *CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
2984 return CGM.GetAddrOfUuidDescriptor(E);
2985}
2986
2987LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
2988 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType());
2989}
2990
Mike Stumpc9b231c2009-11-15 08:09:41 +00002991LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00002992CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00002993 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00002994 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00002995 EmitAggExpr(E->getSubExpr(), Slot);
Peter Collingbourne702b2842011-11-27 22:09:22 +00002996 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddr());
John McCall8ea46b62010-09-18 00:58:34 +00002997 return MakeAddrLValue(Slot.getAddr(), E->getType());
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00002998}
2999
Eli Friedman5bc17122012-02-08 05:34:55 +00003000LValue
3001CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00003002 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00003003 EmitLambdaExpr(E, Slot);
Eli Friedman5bc17122012-02-08 05:34:55 +00003004 return MakeAddrLValue(Slot.getAddr(), E->getType());
3005}
3006
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003007LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003008 RValue RV = EmitObjCMessageExpr(E);
Anders Carlsson280e61f12010-06-21 20:59:55 +00003009
3010 if (!RV.isScalar())
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00003011 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Anders Carlsson280e61f12010-06-21 20:59:55 +00003012
3013 assert(E->getMethodDecl()->getResultType()->isReferenceType() &&
3014 "Can't have a scalar return unless the return type is a "
3015 "reference type!");
3016
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00003017 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003018}
3019
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003020LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
3021 llvm::Value *V =
3022 CGM.getObjCRuntime().GetSelector(Builder, E->getSelector(), true);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00003023 return MakeAddrLValue(V, E->getType());
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003024}
3025
Daniel Dunbar722f4242009-04-22 05:08:15 +00003026llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003027 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00003028 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003029}
3030
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003031LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
3032 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003033 const ObjCIvarDecl *Ivar,
3034 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00003035 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00003036 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003037}
3038
3039LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003040 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
3041 llvm::Value *BaseValue = 0;
3042 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00003043 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003044 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003045 if (E->isArrow()) {
3046 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003047 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00003048 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003049 } else {
3050 LValue BaseLV = EmitLValue(BaseExpr);
3051 // FIXME: this isn't right for bitfields.
3052 BaseValue = BaseLV.getAddress();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003053 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00003054 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003055 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003056
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00003057 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00003058 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
3059 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00003060 setObjCGCLValueClass(getContext(), E, LV);
3061 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00003062}
3063
Chris Lattnera4185c52009-04-25 19:35:26 +00003064LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00003065 // Can only get l-value for message expression returning aggregate type
3066 RValue RV = EmitAnyExprToTemp(E);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00003067 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Chris Lattnera4185c52009-04-25 19:35:26 +00003068}
3069
Anders Carlsson0435ed52009-12-24 19:08:58 +00003070RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
Anders Carlsson17490832009-12-24 20:40:36 +00003071 ReturnValueSlot ReturnValue,
Anders Carlsson3a9463b2009-05-27 01:22:39 +00003072 CallExpr::const_arg_iterator ArgBeg,
3073 CallExpr::const_arg_iterator ArgEnd,
3074 const Decl *TargetDecl) {
Mike Stump4a3999f2009-09-09 13:00:44 +00003075 // Get the actual function type. The callee type will always be a pointer to
3076 // function type or a block pointer type.
3077 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00003078 "Call must have function pointer type!");
3079
John McCall6fd4c232009-10-23 08:22:42 +00003080 CalleeType = getContext().getCanonicalType(CalleeType);
3081
John McCallab26cfa2010-02-05 21:31:56 +00003082 const FunctionType *FnType
3083 = cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00003084
3085 CallArgList Args;
John McCall6fd4c232009-10-23 08:22:42 +00003086 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd);
Daniel Dunbarc722b852008-08-30 03:02:31 +00003087
John McCalla729c622012-02-17 03:33:10 +00003088 const CGFunctionInfo &FnInfo =
John McCall8dda7b22012-07-07 06:41:13 +00003089 CGM.getTypes().arrangeFreeFunctionCall(Args, FnType);
John McCallcbc038a2011-09-21 08:08:30 +00003090
3091 // C99 6.5.2.2p6:
3092 // If the expression that denotes the called function has a type
3093 // that does not include a prototype, [the default argument
3094 // promotions are performed]. If the number of arguments does not
3095 // equal the number of parameters, the behavior is undefined. If
3096 // the function is defined with a type that includes a prototype,
3097 // and either the prototype ends with an ellipsis (, ...) or the
3098 // types of the arguments after promotion are not compatible with
3099 // the types of the parameters, the behavior is undefined. If the
3100 // function is defined with a type that does not include a
3101 // prototype, and the types of the arguments after promotion are
3102 // not compatible with those of the parameters after promotion,
3103 // the behavior is undefined [except in some trivial cases].
3104 // That is, in the general case, we should assume that a call
3105 // through an unprototyped function type works like a *non-variadic*
3106 // call. The way we make this work is to cast to the exact type
3107 // of the promoted arguments.
John McCallc818bbb2012-12-07 07:03:17 +00003108 if (isa<FunctionNoProtoType>(FnType)) {
John McCalla729c622012-02-17 03:33:10 +00003109 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00003110 CalleeTy = CalleeTy->getPointerTo();
3111 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
3112 }
3113
3114 return EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00003115}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003116
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003117LValue CodeGenFunction::
3118EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
Eli Friedman928a5672009-11-18 05:01:17 +00003119 llvm::Value *BaseV;
John McCalle3027922010-08-25 11:45:40 +00003120 if (E->getOpcode() == BO_PtrMemI)
Eli Friedman928a5672009-11-18 05:01:17 +00003121 BaseV = EmitScalarExpr(E->getLHS());
3122 else
3123 BaseV = EmitLValue(E->getLHS()).getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003124
John McCallc134eb52010-08-31 21:07:20 +00003125 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
3126
3127 const MemberPointerType *MPT
3128 = E->getRHS()->getType()->getAs<MemberPointerType>();
3129
3130 llvm::Value *AddV =
3131 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, BaseV, OffsetV, MPT);
3132
3133 return MakeAddrLValue(AddV, MPT->getPointeeType());
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003134}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003135
3136static void
3137EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, llvm::Value *Dest,
3138 llvm::Value *Ptr, llvm::Value *Val1, llvm::Value *Val2,
3139 uint64_t Size, unsigned Align, llvm::AtomicOrdering Order) {
Richard Smithfeea8832012-04-12 05:08:17 +00003140 llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add;
3141 llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
3142
3143 switch (E->getOp()) {
3144 case AtomicExpr::AO__c11_atomic_init:
3145 llvm_unreachable("Already handled!");
3146
3147 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3148 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3149 case AtomicExpr::AO__atomic_compare_exchange:
3150 case AtomicExpr::AO__atomic_compare_exchange_n: {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003151 // Note that cmpxchg only supports specifying one ordering and
3152 // doesn't support weak cmpxchg, at least at the moment.
3153 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
3154 LoadVal1->setAlignment(Align);
3155 llvm::LoadInst *LoadVal2 = CGF.Builder.CreateLoad(Val2);
3156 LoadVal2->setAlignment(Align);
3157 llvm::AtomicCmpXchgInst *CXI =
3158 CGF.Builder.CreateAtomicCmpXchg(Ptr, LoadVal1, LoadVal2, Order);
3159 CXI->setVolatile(E->isVolatile());
3160 llvm::StoreInst *StoreVal1 = CGF.Builder.CreateStore(CXI, Val1);
3161 StoreVal1->setAlignment(Align);
3162 llvm::Value *Cmp = CGF.Builder.CreateICmpEQ(CXI, LoadVal1);
3163 CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType()));
3164 return;
3165 }
3166
Richard Smithfeea8832012-04-12 05:08:17 +00003167 case AtomicExpr::AO__c11_atomic_load:
3168 case AtomicExpr::AO__atomic_load_n:
3169 case AtomicExpr::AO__atomic_load: {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003170 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
3171 Load->setAtomic(Order);
3172 Load->setAlignment(Size);
3173 Load->setVolatile(E->isVolatile());
3174 llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Load, Dest);
3175 StoreDest->setAlignment(Align);
3176 return;
3177 }
3178
Richard Smithfeea8832012-04-12 05:08:17 +00003179 case AtomicExpr::AO__c11_atomic_store:
3180 case AtomicExpr::AO__atomic_store:
3181 case AtomicExpr::AO__atomic_store_n: {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003182 assert(!Dest && "Store does not return a value");
3183 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
3184 LoadVal1->setAlignment(Align);
3185 llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr);
3186 Store->setAtomic(Order);
3187 Store->setAlignment(Size);
3188 Store->setVolatile(E->isVolatile());
3189 return;
3190 }
3191
Richard Smithfeea8832012-04-12 05:08:17 +00003192 case AtomicExpr::AO__c11_atomic_exchange:
3193 case AtomicExpr::AO__atomic_exchange_n:
3194 case AtomicExpr::AO__atomic_exchange:
3195 Op = llvm::AtomicRMWInst::Xchg;
3196 break;
3197
3198 case AtomicExpr::AO__atomic_add_fetch:
3199 PostOp = llvm::Instruction::Add;
3200 // Fall through.
3201 case AtomicExpr::AO__c11_atomic_fetch_add:
3202 case AtomicExpr::AO__atomic_fetch_add:
3203 Op = llvm::AtomicRMWInst::Add;
3204 break;
3205
3206 case AtomicExpr::AO__atomic_sub_fetch:
3207 PostOp = llvm::Instruction::Sub;
3208 // Fall through.
3209 case AtomicExpr::AO__c11_atomic_fetch_sub:
3210 case AtomicExpr::AO__atomic_fetch_sub:
3211 Op = llvm::AtomicRMWInst::Sub;
3212 break;
3213
3214 case AtomicExpr::AO__atomic_and_fetch:
3215 PostOp = llvm::Instruction::And;
3216 // Fall through.
3217 case AtomicExpr::AO__c11_atomic_fetch_and:
3218 case AtomicExpr::AO__atomic_fetch_and:
3219 Op = llvm::AtomicRMWInst::And;
3220 break;
3221
3222 case AtomicExpr::AO__atomic_or_fetch:
3223 PostOp = llvm::Instruction::Or;
3224 // Fall through.
3225 case AtomicExpr::AO__c11_atomic_fetch_or:
3226 case AtomicExpr::AO__atomic_fetch_or:
3227 Op = llvm::AtomicRMWInst::Or;
3228 break;
3229
3230 case AtomicExpr::AO__atomic_xor_fetch:
3231 PostOp = llvm::Instruction::Xor;
3232 // Fall through.
3233 case AtomicExpr::AO__c11_atomic_fetch_xor:
3234 case AtomicExpr::AO__atomic_fetch_xor:
3235 Op = llvm::AtomicRMWInst::Xor;
3236 break;
Richard Smithd65cee92012-04-13 06:31:38 +00003237
3238 case AtomicExpr::AO__atomic_nand_fetch:
3239 PostOp = llvm::Instruction::And;
3240 // Fall through.
3241 case AtomicExpr::AO__atomic_fetch_nand:
3242 Op = llvm::AtomicRMWInst::Nand;
3243 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003244 }
Richard Smithfeea8832012-04-12 05:08:17 +00003245
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003246 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
3247 LoadVal1->setAlignment(Align);
3248 llvm::AtomicRMWInst *RMWI =
3249 CGF.Builder.CreateAtomicRMW(Op, Ptr, LoadVal1, Order);
3250 RMWI->setVolatile(E->isVolatile());
Richard Smithfeea8832012-04-12 05:08:17 +00003251
3252 // For __atomic_*_fetch operations, perform the operation again to
3253 // determine the value which was written.
3254 llvm::Value *Result = RMWI;
3255 if (PostOp)
3256 Result = CGF.Builder.CreateBinOp(PostOp, RMWI, LoadVal1);
Richard Smithd65cee92012-04-13 06:31:38 +00003257 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
3258 Result = CGF.Builder.CreateNot(Result);
Richard Smithfeea8832012-04-12 05:08:17 +00003259 llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Result, Dest);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003260 StoreDest->setAlignment(Align);
3261}
3262
3263// This function emits any expression (scalar, complex, or aggregate)
3264// into a temporary alloca.
3265static llvm::Value *
3266EmitValToTemp(CodeGenFunction &CGF, Expr *E) {
3267 llvm::Value *DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp");
Chad Rosier615ed1a2012-03-29 17:37:10 +00003268 CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(),
3269 /*Init*/ true);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003270 return DeclPtr;
3271}
3272
3273static RValue ConvertTempToRValue(CodeGenFunction &CGF, QualType Ty,
3274 llvm::Value *Dest) {
3275 if (Ty->isAnyComplexType())
3276 return RValue::getComplex(CGF.LoadComplexFromAddr(Dest, false));
3277 if (CGF.hasAggregateLLVMType(Ty))
3278 return RValue::getAggregate(Dest);
3279 return RValue::get(CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(Dest, Ty)));
3280}
3281
3282RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest) {
3283 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
Richard Smithfeea8832012-04-12 05:08:17 +00003284 QualType MemTy = AtomicTy;
3285 if (const AtomicType *AT = AtomicTy->getAs<AtomicType>())
3286 MemTy = AT->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003287 CharUnits sizeChars = getContext().getTypeSizeInChars(AtomicTy);
3288 uint64_t Size = sizeChars.getQuantity();
3289 CharUnits alignChars = getContext().getTypeAlignInChars(AtomicTy);
3290 unsigned Align = alignChars.getQuantity();
Benjamin Kramer37196de2012-11-17 17:30:55 +00003291 unsigned MaxInlineWidthInBits =
3292 getContext().getTargetInfo().getMaxAtomicInlineWidth();
3293 bool UseLibcall = (Size != Align ||
3294 getContext().toBits(sizeChars) > MaxInlineWidthInBits);
David Chisnallfa35df62012-01-16 17:27:18 +00003295
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003296 llvm::Value *Ptr, *Order, *OrderFail = 0, *Val1 = 0, *Val2 = 0;
3297 Ptr = EmitScalarExpr(E->getPtr());
David Chisnallfa35df62012-01-16 17:27:18 +00003298
Richard Smithfeea8832012-04-12 05:08:17 +00003299 if (E->getOp() == AtomicExpr::AO__c11_atomic_init) {
David Chisnallfa35df62012-01-16 17:27:18 +00003300 assert(!Dest && "Init does not return a value");
David Chisnalleb9496e2012-04-11 17:24:05 +00003301 if (!hasAggregateLLVMType(E->getVal1()->getType())) {
Douglas Gregor298f43d2012-04-12 20:42:30 +00003302 QualType PointeeType
3303 = E->getPtr()->getType()->getAs<PointerType>()->getPointeeType();
3304 EmitScalarInit(EmitScalarExpr(E->getVal1()),
3305 LValue::MakeAddr(Ptr, PointeeType, alignChars,
3306 getContext()));
David Chisnalleb9496e2012-04-11 17:24:05 +00003307 } else if (E->getType()->isAnyComplexType()) {
3308 EmitComplexExprIntoAddr(E->getVal1(), Ptr, E->isVolatile());
3309 } else {
3310 AggValueSlot Slot = AggValueSlot::forAddr(Ptr, alignChars,
3311 AtomicTy.getQualifiers(),
3312 AggValueSlot::IsNotDestructed,
3313 AggValueSlot::DoesNotNeedGCBarriers,
3314 AggValueSlot::IsNotAliased);
3315 EmitAggExpr(E->getVal1(), Slot);
3316 }
David Chisnallfa35df62012-01-16 17:27:18 +00003317 return RValue::get(0);
3318 }
3319
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003320 Order = EmitScalarExpr(E->getOrder());
Richard Smithfeea8832012-04-12 05:08:17 +00003321
3322 switch (E->getOp()) {
3323 case AtomicExpr::AO__c11_atomic_init:
3324 llvm_unreachable("Already handled!");
3325
3326 case AtomicExpr::AO__c11_atomic_load:
3327 case AtomicExpr::AO__atomic_load_n:
3328 break;
3329
3330 case AtomicExpr::AO__atomic_load:
3331 Dest = EmitScalarExpr(E->getVal1());
3332 break;
3333
3334 case AtomicExpr::AO__atomic_store:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003335 Val1 = EmitScalarExpr(E->getVal1());
Richard Smithfeea8832012-04-12 05:08:17 +00003336 break;
3337
3338 case AtomicExpr::AO__atomic_exchange:
3339 Val1 = EmitScalarExpr(E->getVal1());
3340 Dest = EmitScalarExpr(E->getVal2());
3341 break;
3342
3343 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3344 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3345 case AtomicExpr::AO__atomic_compare_exchange_n:
3346 case AtomicExpr::AO__atomic_compare_exchange:
3347 Val1 = EmitScalarExpr(E->getVal1());
3348 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
3349 Val2 = EmitScalarExpr(E->getVal2());
3350 else
3351 Val2 = EmitValToTemp(*this, E->getVal2());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003352 OrderFail = EmitScalarExpr(E->getOrderFail());
Richard Smithfeea8832012-04-12 05:08:17 +00003353 // Evaluate and discard the 'weak' argument.
3354 if (E->getNumSubExprs() == 6)
3355 EmitScalarExpr(E->getWeak());
3356 break;
3357
3358 case AtomicExpr::AO__c11_atomic_fetch_add:
3359 case AtomicExpr::AO__c11_atomic_fetch_sub:
Richard Smithfeea8832012-04-12 05:08:17 +00003360 if (MemTy->isPointerType()) {
3361 // For pointer arithmetic, we're required to do a bit of math:
3362 // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
Richard Smith01ba47d2012-04-13 00:45:38 +00003363 // ... but only for the C11 builtins. The GNU builtins expect the
3364 // user to multiply by sizeof(T).
Richard Smithfeea8832012-04-12 05:08:17 +00003365 QualType Val1Ty = E->getVal1()->getType();
3366 llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
3367 CharUnits PointeeIncAmt =
3368 getContext().getTypeSizeInChars(MemTy->getPointeeType());
3369 Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
3370 Val1 = CreateMemTemp(Val1Ty, ".atomictmp");
3371 EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Val1, Val1Ty));
3372 break;
3373 }
3374 // Fall through.
Richard Smith01ba47d2012-04-13 00:45:38 +00003375 case AtomicExpr::AO__atomic_fetch_add:
3376 case AtomicExpr::AO__atomic_fetch_sub:
3377 case AtomicExpr::AO__atomic_add_fetch:
3378 case AtomicExpr::AO__atomic_sub_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003379 case AtomicExpr::AO__c11_atomic_store:
3380 case AtomicExpr::AO__c11_atomic_exchange:
3381 case AtomicExpr::AO__atomic_store_n:
3382 case AtomicExpr::AO__atomic_exchange_n:
3383 case AtomicExpr::AO__c11_atomic_fetch_and:
3384 case AtomicExpr::AO__c11_atomic_fetch_or:
3385 case AtomicExpr::AO__c11_atomic_fetch_xor:
3386 case AtomicExpr::AO__atomic_fetch_and:
3387 case AtomicExpr::AO__atomic_fetch_or:
3388 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003389 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003390 case AtomicExpr::AO__atomic_and_fetch:
3391 case AtomicExpr::AO__atomic_or_fetch:
3392 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003393 case AtomicExpr::AO__atomic_nand_fetch:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003394 Val1 = EmitValToTemp(*this, E->getVal1());
Richard Smithfeea8832012-04-12 05:08:17 +00003395 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003396 }
3397
Richard Smithfeea8832012-04-12 05:08:17 +00003398 if (!E->getType()->isVoidType() && !Dest)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003399 Dest = CreateMemTemp(E->getType(), ".atomicdst");
3400
David Chisnalldb365f32012-03-29 18:01:11 +00003401 // Use a library call. See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003402 if (UseLibcall) {
David Chisnalldb365f32012-03-29 18:01:11 +00003403
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003404 SmallVector<QualType, 5> Params;
David Chisnalldb365f32012-03-29 18:01:11 +00003405 CallArgList Args;
3406 // Size is always the first parameter
3407 Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
3408 getContext().getSizeType());
3409 // Atomic address is always the second parameter
3410 Args.add(RValue::get(EmitCastToVoidPtr(Ptr)),
3411 getContext().VoidPtrTy);
3412
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003413 const char* LibCallName;
David Chisnalldb365f32012-03-29 18:01:11 +00003414 QualType RetTy = getContext().VoidTy;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003415 switch (E->getOp()) {
David Chisnalldb365f32012-03-29 18:01:11 +00003416 // There is only one libcall for compare an exchange, because there is no
3417 // optimisation benefit possible from a libcall version of a weak compare
3418 // and exchange.
3419 // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
Richard Smithfeea8832012-04-12 05:08:17 +00003420 // void *desired, int success, int failure)
3421 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3422 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3423 case AtomicExpr::AO__atomic_compare_exchange:
3424 case AtomicExpr::AO__atomic_compare_exchange_n:
David Chisnalldb365f32012-03-29 18:01:11 +00003425 LibCallName = "__atomic_compare_exchange";
3426 RetTy = getContext().BoolTy;
3427 Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3428 getContext().VoidPtrTy);
3429 Args.add(RValue::get(EmitCastToVoidPtr(Val2)),
3430 getContext().VoidPtrTy);
3431 Args.add(RValue::get(Order),
3432 getContext().IntTy);
3433 Order = OrderFail;
3434 break;
3435 // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
3436 // int order)
Richard Smithfeea8832012-04-12 05:08:17 +00003437 case AtomicExpr::AO__c11_atomic_exchange:
3438 case AtomicExpr::AO__atomic_exchange_n:
3439 case AtomicExpr::AO__atomic_exchange:
David Chisnalldb365f32012-03-29 18:01:11 +00003440 LibCallName = "__atomic_exchange";
3441 Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3442 getContext().VoidPtrTy);
3443 Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
3444 getContext().VoidPtrTy);
3445 break;
3446 // void __atomic_store(size_t size, void *mem, void *val, int order)
Richard Smithfeea8832012-04-12 05:08:17 +00003447 case AtomicExpr::AO__c11_atomic_store:
3448 case AtomicExpr::AO__atomic_store:
3449 case AtomicExpr::AO__atomic_store_n:
David Chisnalldb365f32012-03-29 18:01:11 +00003450 LibCallName = "__atomic_store";
3451 Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3452 getContext().VoidPtrTy);
3453 break;
3454 // void __atomic_load(size_t size, void *mem, void *return, int order)
Richard Smithfeea8832012-04-12 05:08:17 +00003455 case AtomicExpr::AO__c11_atomic_load:
3456 case AtomicExpr::AO__atomic_load:
3457 case AtomicExpr::AO__atomic_load_n:
David Chisnalldb365f32012-03-29 18:01:11 +00003458 LibCallName = "__atomic_load";
3459 Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
3460 getContext().VoidPtrTy);
3461 break;
3462#if 0
3463 // These are only defined for 1-16 byte integers. It is not clear what
3464 // their semantics would be on anything else...
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003465 case AtomicExpr::Add: LibCallName = "__atomic_fetch_add_generic"; break;
3466 case AtomicExpr::Sub: LibCallName = "__atomic_fetch_sub_generic"; break;
3467 case AtomicExpr::And: LibCallName = "__atomic_fetch_and_generic"; break;
3468 case AtomicExpr::Or: LibCallName = "__atomic_fetch_or_generic"; break;
3469 case AtomicExpr::Xor: LibCallName = "__atomic_fetch_xor_generic"; break;
David Chisnalldb365f32012-03-29 18:01:11 +00003470#endif
3471 default: return EmitUnsupportedRValue(E, "atomic library call");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003472 }
David Chisnalldb365f32012-03-29 18:01:11 +00003473 // order is always the last parameter
3474 Args.add(RValue::get(Order),
3475 getContext().IntTy);
3476
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003477 const CGFunctionInfo &FuncInfo =
John McCall8dda7b22012-07-07 06:41:13 +00003478 CGM.getTypes().arrangeFreeFunctionCall(RetTy, Args,
David Chisnalldb365f32012-03-29 18:01:11 +00003479 FunctionType::ExtInfo(), RequiredArgs::All);
3480 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FuncInfo);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003481 llvm::Constant *Func = CGM.CreateRuntimeFunction(FTy, LibCallName);
3482 RValue Res = EmitCall(FuncInfo, Func, ReturnValueSlot(), Args);
3483 if (E->isCmpXChg())
3484 return Res;
Richard Smithfeea8832012-04-12 05:08:17 +00003485 if (E->getType()->isVoidType())
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003486 return RValue::get(0);
3487 return ConvertTempToRValue(*this, E->getType(), Dest);
3488 }
David Chisnalldb365f32012-03-29 18:01:11 +00003489
Eli Friedmanfb9c49e2012-10-30 01:15:28 +00003490 bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
3491 E->getOp() == AtomicExpr::AO__atomic_store ||
3492 E->getOp() == AtomicExpr::AO__atomic_store_n;
3493 bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
3494 E->getOp() == AtomicExpr::AO__atomic_load ||
3495 E->getOp() == AtomicExpr::AO__atomic_load_n;
3496
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003497 llvm::Type *IPtrTy =
3498 llvm::IntegerType::get(getLLVMContext(), Size * 8)->getPointerTo();
3499 llvm::Value *OrigDest = Dest;
3500 Ptr = Builder.CreateBitCast(Ptr, IPtrTy);
3501 if (Val1) Val1 = Builder.CreateBitCast(Val1, IPtrTy);
3502 if (Val2) Val2 = Builder.CreateBitCast(Val2, IPtrTy);
3503 if (Dest && !E->isCmpXChg()) Dest = Builder.CreateBitCast(Dest, IPtrTy);
3504
3505 if (isa<llvm::ConstantInt>(Order)) {
3506 int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
3507 switch (ord) {
3508 case 0: // memory_order_relaxed
3509 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3510 llvm::Monotonic);
3511 break;
3512 case 1: // memory_order_consume
3513 case 2: // memory_order_acquire
Eli Friedmanfb9c49e2012-10-30 01:15:28 +00003514 if (IsStore)
3515 break; // Avoid crashing on code with undefined behavior
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003516 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3517 llvm::Acquire);
3518 break;
3519 case 3: // memory_order_release
Eli Friedmanfb9c49e2012-10-30 01:15:28 +00003520 if (IsLoad)
3521 break; // Avoid crashing on code with undefined behavior
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003522 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3523 llvm::Release);
3524 break;
3525 case 4: // memory_order_acq_rel
Eli Friedmanfb9c49e2012-10-30 01:15:28 +00003526 if (IsLoad || IsStore)
3527 break; // Avoid crashing on code with undefined behavior
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003528 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3529 llvm::AcquireRelease);
3530 break;
3531 case 5: // memory_order_seq_cst
3532 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3533 llvm::SequentiallyConsistent);
3534 break;
3535 default: // invalid order
3536 // We should not ever get here normally, but it's hard to
3537 // enforce that in general.
Richard Smithfeea8832012-04-12 05:08:17 +00003538 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003539 }
Richard Smithfeea8832012-04-12 05:08:17 +00003540 if (E->getType()->isVoidType())
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003541 return RValue::get(0);
3542 return ConvertTempToRValue(*this, E->getType(), OrigDest);
3543 }
3544
3545 // Long case, when Order isn't obviously constant.
3546
3547 // Create all the relevant BB's
Eli Friedmanc2025562011-10-11 20:00:47 +00003548 llvm::BasicBlock *MonotonicBB = 0, *AcquireBB = 0, *ReleaseBB = 0,
3549 *AcqRelBB = 0, *SeqCstBB = 0;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003550 MonotonicBB = createBasicBlock("monotonic", CurFn);
Richard Smithfeea8832012-04-12 05:08:17 +00003551 if (!IsStore)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003552 AcquireBB = createBasicBlock("acquire", CurFn);
Richard Smithfeea8832012-04-12 05:08:17 +00003553 if (!IsLoad)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003554 ReleaseBB = createBasicBlock("release", CurFn);
Richard Smithfeea8832012-04-12 05:08:17 +00003555 if (!IsLoad && !IsStore)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003556 AcqRelBB = createBasicBlock("acqrel", CurFn);
3557 SeqCstBB = createBasicBlock("seqcst", CurFn);
3558 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
3559
3560 // Create the switch for the split
3561 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
3562 // doesn't matter unless someone is crazy enough to use something that
3563 // doesn't fold to a constant for the ordering.
3564 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
3565 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
3566
3567 // Emit all the different atomics
3568 Builder.SetInsertPoint(MonotonicBB);
3569 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3570 llvm::Monotonic);
3571 Builder.CreateBr(ContBB);
Richard Smithfeea8832012-04-12 05:08:17 +00003572 if (!IsStore) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003573 Builder.SetInsertPoint(AcquireBB);
3574 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3575 llvm::Acquire);
3576 Builder.CreateBr(ContBB);
3577 SI->addCase(Builder.getInt32(1), AcquireBB);
3578 SI->addCase(Builder.getInt32(2), AcquireBB);
3579 }
Richard Smithfeea8832012-04-12 05:08:17 +00003580 if (!IsLoad) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003581 Builder.SetInsertPoint(ReleaseBB);
3582 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3583 llvm::Release);
3584 Builder.CreateBr(ContBB);
3585 SI->addCase(Builder.getInt32(3), ReleaseBB);
3586 }
Richard Smithfeea8832012-04-12 05:08:17 +00003587 if (!IsLoad && !IsStore) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003588 Builder.SetInsertPoint(AcqRelBB);
3589 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3590 llvm::AcquireRelease);
3591 Builder.CreateBr(ContBB);
3592 SI->addCase(Builder.getInt32(4), AcqRelBB);
3593 }
3594 Builder.SetInsertPoint(SeqCstBB);
3595 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3596 llvm::SequentiallyConsistent);
3597 Builder.CreateBr(ContBB);
3598 SI->addCase(Builder.getInt32(5), SeqCstBB);
3599
3600 // Cleanup and return
3601 Builder.SetInsertPoint(ContBB);
Richard Smithfeea8832012-04-12 05:08:17 +00003602 if (E->getType()->isVoidType())
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003603 return RValue::get(0);
3604 return ConvertTempToRValue(*this, E->getType(), OrigDest);
3605}
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003606
Duncan Sandse81111c2012-04-10 08:23:07 +00003607void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003608 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00003609 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003610 return;
3611
Duncan Sands65229ed2012-04-16 16:29:47 +00003612 llvm::MDBuilder MDHelper(getLLVMContext());
3613 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003614
Duncan Sands6fc46192012-04-14 12:37:26 +00003615 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003616}
John McCallfe96e0b2011-11-06 09:01:30 +00003617
3618namespace {
3619 struct LValueOrRValue {
3620 LValue LV;
3621 RValue RV;
3622 };
3623}
3624
3625static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
3626 const PseudoObjectExpr *E,
3627 bool forLValue,
3628 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003629 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00003630
3631 // Find the result expression, if any.
3632 const Expr *resultExpr = E->getResultExpr();
3633 LValueOrRValue result;
3634
3635 for (PseudoObjectExpr::const_semantics_iterator
3636 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3637 const Expr *semantic = *i;
3638
3639 // If this semantic expression is an opaque value, bind it
3640 // to the result of its source expression.
3641 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
3642
3643 // If this is the result expression, we may need to evaluate
3644 // directly into the slot.
3645 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
3646 OVMA opaqueData;
3647 if (ov == resultExpr && ov->isRValue() && !forLValue &&
3648 CodeGenFunction::hasAggregateLLVMType(ov->getType()) &&
3649 !ov->getType()->isAnyComplexType()) {
3650 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
3651
3652 LValue LV = CGF.MakeAddrLValue(slot.getAddr(), ov->getType());
3653 opaqueData = OVMA::bind(CGF, ov, LV);
3654 result.RV = slot.asRValue();
3655
3656 // Otherwise, emit as normal.
3657 } else {
3658 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
3659
3660 // If this is the result, also evaluate the result now.
3661 if (ov == resultExpr) {
3662 if (forLValue)
3663 result.LV = CGF.EmitLValue(ov);
3664 else
3665 result.RV = CGF.EmitAnyExpr(ov, slot);
3666 }
3667 }
3668
3669 opaques.push_back(opaqueData);
3670
3671 // Otherwise, if the expression is the result, evaluate it
3672 // and remember the result.
3673 } else if (semantic == resultExpr) {
3674 if (forLValue)
3675 result.LV = CGF.EmitLValue(semantic);
3676 else
3677 result.RV = CGF.EmitAnyExpr(semantic, slot);
3678
3679 // Otherwise, evaluate the expression in an ignored context.
3680 } else {
3681 CGF.EmitIgnoredExpr(semantic);
3682 }
3683 }
3684
3685 // Unbind all the opaques now.
3686 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
3687 opaques[i].unbind(CGF);
3688
3689 return result;
3690}
3691
3692RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
3693 AggValueSlot slot) {
3694 return emitPseudoObjectExpr(*this, E, false, slot).RV;
3695}
3696
3697LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
3698 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
3699}