blob: 94bc81c8f4a5bc8566a9583e0169b581b288cb94 [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"
Nico Weber3a691a32012-06-23 02:07:59 +000024#include "clang/Basic/ConvertUTF.h"
Chandler Carruth85098242010-06-15 23:19:56 +000025#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "llvm/ADT/Hashing.h"
27#include "llvm/DataLayout.h"
Nick Lewycky7c6c6cc2011-07-07 03:54:51 +000028#include "llvm/Intrinsics.h"
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +000029#include "llvm/LLVMContext.h"
Chandler Carruthcc8f2a62012-07-15 23:28:01 +000030#include "llvm/MDBuilder.h"
Chris Lattnere47e4402007-06-01 18:02:12 +000031using namespace clang;
32using namespace CodeGen;
33
Chris Lattnerd7f58862007-06-02 05:24:33 +000034//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000035// Miscellaneous Helper Methods
36//===--------------------------------------------------------------------===//
37
John McCallad7c5c12011-02-08 08:22:06 +000038llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
39 unsigned addressSpace =
40 cast<llvm::PointerType>(value->getType())->getAddressSpace();
41
Chris Lattner2192fe52011-07-18 04:24:23 +000042 llvm::PointerType *destType = Int8PtrTy;
John McCallad7c5c12011-02-08 08:22:06 +000043 if (addressSpace)
44 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
45
46 if (value->getType() == destType) return value;
47 return Builder.CreateBitCast(value, destType);
48}
49
Chris Lattnere9a64532007-06-22 21:44:33 +000050/// CreateTempAlloca - This creates a alloca and inserts it into the entry
51/// block.
Chris Lattner2192fe52011-07-18 04:24:23 +000052llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000053 const Twine &Name) {
Chris Lattner47640222009-03-22 00:24:14 +000054 if (!Builder.isNamePreserving())
Daniel Dunbarb5aacc22009-10-19 01:21:05 +000055 return new llvm::AllocaInst(Ty, 0, "", AllocaInsertPt);
Devang Pateldac79de2009-10-12 22:29:02 +000056 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +000057}
Chris Lattner8394d792007-06-05 20:53:16 +000058
John McCall2e6567a2010-04-22 01:10:34 +000059void CodeGenFunction::InitTempAlloca(llvm::AllocaInst *Var,
60 llvm::Value *Init) {
61 llvm::StoreInst *Store = new llvm::StoreInst(Init, Var);
62 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
63 Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
64}
65
Chris Lattnerc401de92010-07-05 20:21:00 +000066llvm::AllocaInst *CodeGenFunction::CreateIRTemp(QualType Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000067 const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +000068 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertType(Ty), Name);
69 // FIXME: Should we prefer the preferred type alignment here?
70 CharUnits Align = getContext().getTypeAlignInChars(Ty);
71 Alloc->setAlignment(Align.getQuantity());
72 return Alloc;
73}
74
Chris Lattnerc401de92010-07-05 20:21:00 +000075llvm::AllocaInst *CodeGenFunction::CreateMemTemp(QualType Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000076 const Twine &Name) {
Daniel Dunbara7566f12010-02-09 02:48:28 +000077 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), Name);
78 // FIXME: Should we prefer the preferred type alignment here?
79 CharUnits Align = getContext().getTypeAlignInChars(Ty);
80 Alloc->setAlignment(Align.getQuantity());
81 return Alloc;
82}
83
Chris Lattner8394d792007-06-05 20:53:16 +000084/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
85/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +000086llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
John McCall7a9aac22010-08-23 01:21:21 +000087 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +000088 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +000089 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +000090 }
John McCall7a9aac22010-08-23 01:21:21 +000091
92 QualType BoolTy = getContext().BoolTy;
Chris Lattnerf3bc75a2008-04-04 16:54:41 +000093 if (!E->getType()->isAnyComplexType())
Chris Lattner268fcce2007-08-26 16:46:58 +000094 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy);
Chris Lattner8394d792007-06-05 20:53:16 +000095
Chris Lattner268fcce2007-08-26 16:46:58 +000096 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(),BoolTy);
Chris Lattnerf0106d22007-06-02 19:33:17 +000097}
98
John McCalla2342eb2010-12-05 02:00:02 +000099/// EmitIgnoredExpr - Emit code to compute the specified expression,
100/// ignoring the result.
101void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
102 if (E->isRValue())
103 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
104
105 // Just emit it as an l-value and drop the result.
106 EmitLValue(E);
107}
108
John McCall7a626f62010-09-15 10:14:12 +0000109/// EmitAnyExpr - Emit code to compute the specified expression which
110/// can have any type. The result is returned as an RValue struct.
111/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000112/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000113RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
114 AggValueSlot aggSlot,
115 bool ignoreResult) {
Chris Lattner4647a212007-08-31 22:49:20 +0000116 if (!hasAggregateLLVMType(E->getType()))
John McCall4e8ca4f2012-07-02 23:58:38 +0000117 return RValue::get(EmitScalarExpr(E, ignoreResult));
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000118 else if (E->getType()->isAnyComplexType())
John McCall4e8ca4f2012-07-02 23:58:38 +0000119 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
Mike Stump4a3999f2009-09-09 13:00:44 +0000120
John McCall4e8ca4f2012-07-02 23:58:38 +0000121 if (!ignoreResult && aggSlot.isIgnored())
122 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
123 EmitAggExpr(E, aggSlot);
124 return aggSlot.asRValue();
Chris Lattner4647a212007-08-31 22:49:20 +0000125}
126
Mike Stump4a3999f2009-09-09 13:00:44 +0000127/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
128/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000129RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
130 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000131
132 if (hasAggregateLLVMType(E->getType()) &&
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000133 !E->getType()->isAnyComplexType())
John McCall7a626f62010-09-15 10:14:12 +0000134 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
135 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000136}
137
John McCall21886962010-04-21 10:05:39 +0000138/// EmitAnyExprToMem - Evaluate an expression into a given memory
139/// location.
140void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
141 llvm::Value *Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000142 Qualifiers Quals,
143 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000144 // FIXME: This function should take an LValue as an argument.
145 if (E->getType()->isAnyComplexType()) {
John McCall31168b02011-06-15 23:02:42 +0000146 EmitComplexExprIntoAddr(E, Location, Quals.hasVolatile());
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000147 } else if (hasAggregateLLVMType(E->getType())) {
Eli Friedman38cd36d2011-12-03 02:13:40 +0000148 CharUnits Alignment = getContext().getTypeAlignInChars(E->getType());
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000149 EmitAggExpr(E, AggValueSlot::forAddr(Location, Alignment, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000150 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000151 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000152 AggValueSlot::IsAliased_t(!IsInit)));
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000153 } else {
John McCall21886962010-04-21 10:05:39 +0000154 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000155 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000156 EmitStoreThroughLValue(RV, LV);
John McCall21886962010-04-21 10:05:39 +0000157 }
158}
159
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000160static llvm::Value *
Chris Lattner24516962011-07-20 04:59:57 +0000161CreateReferenceTemporary(CodeGenFunction &CGF, QualType Type,
Anders Carlsson18c205e2010-06-27 17:23:46 +0000162 const NamedDecl *InitializedDecl) {
163 if (const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
164 if (VD->hasGlobalStorage()) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000165 SmallString<256> Name;
Rafael Espindola3968cd02011-02-11 02:52:17 +0000166 llvm::raw_svector_ostream Out(Name);
167 CGF.CGM.getCXXABI().getMangleContext().mangleReferenceTemporary(VD, Out);
168 Out.flush();
169
Chris Lattner2192fe52011-07-18 04:24:23 +0000170 llvm::Type *RefTempTy = CGF.ConvertTypeForMem(Type);
Anders Carlsson18c205e2010-06-27 17:23:46 +0000171
172 // Create the reference temporary.
173 llvm::GlobalValue *RefTemp =
174 new llvm::GlobalVariable(CGF.CGM.getModule(),
175 RefTempTy, /*isConstant=*/false,
176 llvm::GlobalValue::InternalLinkage,
177 llvm::Constant::getNullValue(RefTempTy),
178 Name.str());
179 return RefTemp;
180 }
181 }
182
183 return CGF.CreateMemTemp(Type, "ref.tmp");
184}
185
186static llvm::Value *
Chris Lattnerf53c0962010-09-06 00:11:41 +0000187EmitExprForReferenceBinding(CodeGenFunction &CGF, const Expr *E,
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000188 llvm::Value *&ReferenceTemporary,
189 const CXXDestructorDecl *&ReferenceTemporaryDtor,
John McCall31168b02011-06-15 23:02:42 +0000190 QualType &ObjCARCReferenceLifetimeType,
Anders Carlsson18c205e2010-06-27 17:23:46 +0000191 const NamedDecl *InitializedDecl) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000192 const MaterializeTemporaryExpr *M = NULL;
Rafael Espindola9c006de2012-10-27 01:03:43 +0000193 E = E->findMaterializedTemporary(M);
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000194 // Objective-C++ ARC:
195 // If we are binding a reference to a temporary that has ownership, we
196 // need to perform retain/release operations on the temporary.
Richard Smith9c6890a2012-11-01 22:30:59 +0000197 if (M && CGF.getLangOpts().ObjCAutoRefCount &&
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000198 M->getType()->isObjCLifetimeType() &&
199 (M->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
200 M->getType().getObjCLifetime() == Qualifiers::OCL_Weak ||
201 M->getType().getObjCLifetime() == Qualifiers::OCL_Autoreleasing))
202 ObjCARCReferenceLifetimeType = M->getType();
Sebastian Redl29526f02011-11-27 16:50:07 +0000203
John McCall08ef4662011-11-10 08:15:53 +0000204 if (const ExprWithCleanups *EWC = dyn_cast<ExprWithCleanups>(E)) {
205 CGF.enterFullExpression(EWC);
John McCallbd309292010-07-06 01:34:17 +0000206 CodeGenFunction::RunCleanupsScope Scope(CGF);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000207
John McCall08ef4662011-11-10 08:15:53 +0000208 return EmitExprForReferenceBinding(CGF, EWC->getSubExpr(),
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000209 ReferenceTemporary,
210 ReferenceTemporaryDtor,
John McCall31168b02011-06-15 23:02:42 +0000211 ObjCARCReferenceLifetimeType,
Anders Carlsson18c205e2010-06-27 17:23:46 +0000212 InitializedDecl);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000213 }
214
215 RValue RV;
Douglas Gregor9c399a22011-01-22 02:44:21 +0000216 if (E->isGLValue()) {
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000217 // Emit the expression as an lvalue.
218 LValue LV = CGF.EmitLValue(E);
Chris Lattner13ee4f42011-07-10 05:34:54 +0000219
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000220 if (LV.isSimple())
221 return LV.getAddress();
Anders Carlsson824e0612010-02-04 17:32:58 +0000222
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000223 // We have to load the lvalue.
John McCall55e1fbc2011-06-25 02:11:03 +0000224 RV = CGF.EmitLoadOfLValue(LV);
Eli Friedmanc21cb442009-05-20 02:31:19 +0000225 } else {
Douglas Gregor58df5092011-06-22 16:12:01 +0000226 if (!ObjCARCReferenceLifetimeType.isNull()) {
227 ReferenceTemporary = CreateReferenceTemporary(CGF,
228 ObjCARCReferenceLifetimeType,
229 InitializedDecl);
230
231
232 LValue RefTempDst = CGF.MakeAddrLValue(ReferenceTemporary,
233 ObjCARCReferenceLifetimeType);
234
235 CGF.EmitScalarInit(E, dyn_cast_or_null<ValueDecl>(InitializedDecl),
236 RefTempDst, false);
237
238 bool ExtendsLifeOfTemporary = false;
239 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
240 if (Var->extendsLifetimeOfTemporary())
241 ExtendsLifeOfTemporary = true;
242 } else if (InitializedDecl && isa<FieldDecl>(InitializedDecl)) {
243 ExtendsLifeOfTemporary = true;
244 }
245
246 if (!ExtendsLifeOfTemporary) {
247 // Since the lifetime of this temporary isn't going to be extended,
248 // we need to clean it up ourselves at the end of the full expression.
249 switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
250 case Qualifiers::OCL_None:
251 case Qualifiers::OCL_ExplicitNone:
252 case Qualifiers::OCL_Autoreleasing:
253 break;
254
John McCall4bd0fb12011-07-12 16:41:08 +0000255 case Qualifiers::OCL_Strong: {
256 assert(!ObjCARCReferenceLifetimeType->isArrayType());
257 CleanupKind cleanupKind = CGF.getARCCleanupKind();
258 CGF.pushDestroy(cleanupKind,
259 ReferenceTemporary,
260 ObjCARCReferenceLifetimeType,
261 CodeGenFunction::destroyARCStrongImprecise,
262 cleanupKind & EHCleanup);
Douglas Gregor58df5092011-06-22 16:12:01 +0000263 break;
John McCall4bd0fb12011-07-12 16:41:08 +0000264 }
Douglas Gregor58df5092011-06-22 16:12:01 +0000265
266 case Qualifiers::OCL_Weak:
John McCall4bd0fb12011-07-12 16:41:08 +0000267 assert(!ObjCARCReferenceLifetimeType->isArrayType());
268 CGF.pushDestroy(NormalAndEHCleanup,
269 ReferenceTemporary,
270 ObjCARCReferenceLifetimeType,
271 CodeGenFunction::destroyARCWeak,
272 /*useEHCleanupForArray*/ true);
Douglas Gregor58df5092011-06-22 16:12:01 +0000273 break;
274 }
275
276 ObjCARCReferenceLifetimeType = QualType();
277 }
278
279 return ReferenceTemporary;
280 }
Rafael Espindolab4136762012-10-27 00:40:06 +0000281
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000282 SmallVector<SubobjectAdjustment, 2> Adjustments;
Rafael Espindola9c006de2012-10-27 01:03:43 +0000283 E = E->skipRValueSubobjectAdjustments(Adjustments);
Rafael Espindolab4136762012-10-27 00:40:06 +0000284 if (const OpaqueValueExpr *opaque = dyn_cast<OpaqueValueExpr>(E))
285 if (opaque->getType()->isRecordType())
286 return CGF.EmitOpaqueValueLValue(opaque).getAddress();
Douglas Gregoraae38d62010-05-22 05:17:18 +0000287
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000288 // Create a reference temporary if necessary.
John McCall7a626f62010-09-15 10:14:12 +0000289 AggValueSlot AggSlot = AggValueSlot::ignored();
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000290 if (CGF.hasAggregateLLVMType(E->getType()) &&
John McCall7a626f62010-09-15 10:14:12 +0000291 !E->getType()->isAnyComplexType()) {
Anders Carlsson18c205e2010-06-27 17:23:46 +0000292 ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
293 InitializedDecl);
Eli Friedman38cd36d2011-12-03 02:13:40 +0000294 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(E->getType());
John McCall8d6fc952011-08-25 20:40:09 +0000295 AggValueSlot::IsDestructed_t isDestructed
296 = AggValueSlot::IsDestructed_t(InitializedDecl != 0);
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000297 AggSlot = AggValueSlot::forAddr(ReferenceTemporary, Alignment,
298 Qualifiers(), isDestructed,
John McCalla5efa732011-08-25 23:04:34 +0000299 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000300 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000301 }
John McCall31168b02011-06-15 23:02:42 +0000302
Anders Carlsson18c205e2010-06-27 17:23:46 +0000303 if (InitializedDecl) {
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000304 // Get the destructor for the reference temporary.
305 if (const RecordType *RT = E->getType()->getAs<RecordType>()) {
306 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
307 if (!ClassDecl->hasTrivialDestructor())
Douglas Gregorbac74902010-07-01 14:13:13 +0000308 ReferenceTemporaryDtor = ClassDecl->getDestructor();
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000309 }
310 }
311
John McCall31168b02011-06-15 23:02:42 +0000312 RV = CGF.EmitAnyExpr(E, AggSlot);
313
Douglas Gregor7c38f152010-05-20 08:36:28 +0000314 // Check if need to perform derived-to-base casts and/or field accesses, to
315 // get from the temporary object we created (and, potentially, for which we
316 // extended the lifetime) to the subobject we're binding the reference to.
317 if (!Adjustments.empty()) {
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000318 llvm::Value *Object = RV.getAggregateAddr();
Douglas Gregor7c38f152010-05-20 08:36:28 +0000319 for (unsigned I = Adjustments.size(); I != 0; --I) {
320 SubobjectAdjustment &Adjustment = Adjustments[I-1];
321 switch (Adjustment.Kind) {
322 case SubobjectAdjustment::DerivedToBaseAdjustment:
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000323 Object =
324 CGF.GetAddressOfBaseClass(Object,
325 Adjustment.DerivedToBase.DerivedClass,
John McCallcf142162010-08-07 06:22:56 +0000326 Adjustment.DerivedToBase.BasePath->path_begin(),
327 Adjustment.DerivedToBase.BasePath->path_end(),
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000328 /*NullCheckValue=*/false);
Douglas Gregor7c38f152010-05-20 08:36:28 +0000329 break;
330
331 case SubobjectAdjustment::FieldAdjustment: {
Eli Friedman7f1ff602012-04-16 03:54:45 +0000332 LValue LV = CGF.MakeAddrLValue(Object, E->getType());
333 LV = CGF.EmitLValueForField(LV, Adjustment.Field);
Douglas Gregor7c38f152010-05-20 08:36:28 +0000334 if (LV.isSimple()) {
335 Object = LV.getAddress();
336 break;
337 }
338
339 // For non-simple lvalues, we actually have to create a copy of
340 // the object we're binding to.
Daniel Dunbare8b6cda2010-08-21 03:37:02 +0000341 QualType T = Adjustment.Field->getType().getNonReferenceType()
342 .getUnqualifiedType();
Anders Carlsson3f48c602010-06-27 17:52:15 +0000343 Object = CreateReferenceTemporary(CGF, T, InitializedDecl);
Daniel Dunbare8b6cda2010-08-21 03:37:02 +0000344 LValue TempLV = CGF.MakeAddrLValue(Object,
345 Adjustment.Field->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000346 CGF.EmitStoreThroughLValue(CGF.EmitLoadOfLValue(LV), TempLV);
Douglas Gregor7c38f152010-05-20 08:36:28 +0000347 break;
348 }
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000349
Eli Friedman13ffdd82012-06-15 23:51:06 +0000350 case SubobjectAdjustment::MemberPointerAdjustment: {
Rafael Espindolae7b11f52012-10-27 00:36:38 +0000351 llvm::Value *Ptr = CGF.EmitScalarExpr(Adjustment.Ptr.RHS);
Eli Friedman13ffdd82012-06-15 23:51:06 +0000352 Object = CGF.CGM.getCXXABI().EmitMemberDataPointerAddress(
Rafael Espindolae7b11f52012-10-27 00:36:38 +0000353 CGF, Object, Ptr, Adjustment.Ptr.MPT);
Eli Friedman13ffdd82012-06-15 23:51:06 +0000354 break;
355 }
Douglas Gregor7c38f152010-05-20 08:36:28 +0000356 }
357 }
Eli Friedmanb6069252011-03-16 22:34:09 +0000358
359 return Object;
Anders Carlsson66413c22009-10-15 00:51:46 +0000360 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000361 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000362
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000363 if (RV.isAggregate())
364 return RV.getAggregateAddr();
Eli Friedmanc21cb442009-05-20 02:31:19 +0000365
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000366 // Create a temporary variable that we can bind the reference to.
Anders Carlsson18c205e2010-06-27 17:23:46 +0000367 ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
368 InitializedDecl);
369
Daniel Dunbar03816342010-08-21 02:24:36 +0000370
371 unsigned Alignment =
372 CGF.getContext().getTypeAlignInChars(E->getType()).getQuantity();
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000373 if (RV.isScalar())
374 CGF.EmitStoreOfScalar(RV.getScalarVal(), ReferenceTemporary,
Daniel Dunbar03816342010-08-21 02:24:36 +0000375 /*Volatile=*/false, Alignment, E->getType());
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000376 else
377 CGF.StoreComplexToAddr(RV.getComplexVal(), ReferenceTemporary,
378 /*Volatile=*/false);
379 return ReferenceTemporary;
380}
381
382RValue
Chris Lattnerf53c0962010-09-06 00:11:41 +0000383CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E,
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000384 const NamedDecl *InitializedDecl) {
385 llvm::Value *ReferenceTemporary = 0;
386 const CXXDestructorDecl *ReferenceTemporaryDtor = 0;
John McCall31168b02011-06-15 23:02:42 +0000387 QualType ObjCARCReferenceLifetimeType;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000388 llvm::Value *Value = EmitExprForReferenceBinding(*this, E, ReferenceTemporary,
389 ReferenceTemporaryDtor,
John McCall31168b02011-06-15 23:02:42 +0000390 ObjCARCReferenceLifetimeType,
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000391 InitializedDecl);
Richard Smithb1b0ab42012-11-05 22:21:05 +0000392 if (SanitizePerformTypeCheck && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000393 // C++11 [dcl.ref]p5 (as amended by core issue 453):
394 // If a glvalue to which a reference is directly bound designates neither
395 // an existing object or function of an appropriate type nor a region of
396 // storage of suitable size and alignment to contain an object of the
397 // reference's type, the behavior is undefined.
398 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000399 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000400 }
John McCall31168b02011-06-15 23:02:42 +0000401 if (!ReferenceTemporaryDtor && ObjCARCReferenceLifetimeType.isNull())
Anders Carlsson3f48c602010-06-27 17:52:15 +0000402 return RValue::get(Value);
403
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000404 // Make sure to call the destructor for the reference temporary.
John McCall31168b02011-06-15 23:02:42 +0000405 const VarDecl *VD = dyn_cast_or_null<VarDecl>(InitializedDecl);
406 if (VD && VD->hasGlobalStorage()) {
407 if (ReferenceTemporaryDtor) {
Anders Carlsson3f48c602010-06-27 17:52:15 +0000408 llvm::Constant *DtorFn =
409 CGM.GetAddrOfCXXDestructor(ReferenceTemporaryDtor, Dtor_Complete);
John McCallc84ed6a2012-05-01 06:13:13 +0000410 CGM.getCXXABI().registerGlobalDtor(*this, DtorFn,
John McCallad7c5c12011-02-08 08:22:06 +0000411 cast<llvm::Constant>(ReferenceTemporary));
John McCall31168b02011-06-15 23:02:42 +0000412 } else {
413 assert(!ObjCARCReferenceLifetimeType.isNull());
414 // Note: We intentionally do not register a global "destructor" to
415 // release the object.
Anders Carlsson3f48c602010-06-27 17:52:15 +0000416 }
John McCall31168b02011-06-15 23:02:42 +0000417
418 return RValue::get(Value);
Anders Carlsson3f48c602010-06-27 17:52:15 +0000419 }
John McCall8680f872010-07-21 06:29:51 +0000420
John McCall31168b02011-06-15 23:02:42 +0000421 if (ReferenceTemporaryDtor)
422 PushDestructorCleanup(ReferenceTemporaryDtor, ReferenceTemporary);
423 else {
424 switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
425 case Qualifiers::OCL_None:
David Blaikie83d382b2011-09-23 05:06:16 +0000426 llvm_unreachable(
427 "Not a reference temporary that needs to be deallocated");
John McCall31168b02011-06-15 23:02:42 +0000428 case Qualifiers::OCL_ExplicitNone:
429 case Qualifiers::OCL_Autoreleasing:
430 // Nothing to do.
431 break;
432
John McCall4bd0fb12011-07-12 16:41:08 +0000433 case Qualifiers::OCL_Strong: {
434 bool precise = VD && VD->hasAttr<ObjCPreciseLifetimeAttr>();
435 CleanupKind cleanupKind = getARCCleanupKind();
Benjamin Kramerae2d3442011-07-12 18:37:23 +0000436 pushDestroy(cleanupKind, ReferenceTemporary, ObjCARCReferenceLifetimeType,
Peter Collingbourne1425b452012-01-26 03:33:36 +0000437 precise ? destroyARCStrongPrecise : destroyARCStrongImprecise,
438 cleanupKind & EHCleanup);
John McCall31168b02011-06-15 23:02:42 +0000439 break;
John McCall4bd0fb12011-07-12 16:41:08 +0000440 }
John McCall31168b02011-06-15 23:02:42 +0000441
Benjamin Kramerae2d3442011-07-12 18:37:23 +0000442 case Qualifiers::OCL_Weak: {
John McCall31168b02011-06-15 23:02:42 +0000443 // __weak objects always get EH cleanups; otherwise, exceptions
444 // could cause really nasty crashes instead of mere leaks.
John McCall4bd0fb12011-07-12 16:41:08 +0000445 pushDestroy(NormalAndEHCleanup, ReferenceTemporary,
Peter Collingbourne1425b452012-01-26 03:33:36 +0000446 ObjCARCReferenceLifetimeType, destroyARCWeak, true);
John McCall31168b02011-06-15 23:02:42 +0000447 break;
448 }
Benjamin Kramerae2d3442011-07-12 18:37:23 +0000449 }
John McCall31168b02011-06-15 23:02:42 +0000450 }
451
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000452 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000453}
454
455
Mike Stump4a3999f2009-09-09 13:00:44 +0000456/// getAccessedFieldNo - Given an encoded value and a result number, return the
457/// input field number being accessed.
458unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000459 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000460 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
461 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000462}
463
Richard Smith4d3110a2012-10-25 02:14:12 +0000464/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
465static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
466 llvm::Value *High) {
467 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
468 llvm::Value *K47 = Builder.getInt64(47);
469 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
470 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
471 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
472 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
473 return Builder.CreateMul(B1, KMul);
474}
475
Richard Smithe30752c2012-10-09 19:52:38 +0000476void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
477 llvm::Value *Address,
Richard Smith4d1458e2012-09-08 02:08:36 +0000478 QualType Ty, CharUnits Alignment) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000479 if (!SanitizePerformTypeCheck)
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000480 return;
481
Richard Smith2d8b2942012-11-01 07:22:08 +0000482 // Don't check pointers outside the default address space. The null check
483 // isn't correct, the object-size check isn't supported by LLVM, and we can't
484 // communicate the addresses to the runtime handler for the vptr check.
485 if (Address->getType()->getPointerAddressSpace())
486 return;
487
Richard Smith69d0d262012-08-24 00:54:33 +0000488 llvm::Value *Cond = 0;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000489
Richard Smithb1b0ab42012-11-05 22:21:05 +0000490 if (getLangOpts().SanitizeNull) {
491 // The glvalue must not be an empty glvalue.
492 Cond = Builder.CreateICmpNE(
493 Address, llvm::Constant::getNullValue(Address->getType()));
494 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000495
Richard Smithb1b0ab42012-11-05 22:21:05 +0000496 if (getLangOpts().SanitizeObjectSize && !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000497 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000498
Richard Smith69d0d262012-08-24 00:54:33 +0000499 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000500 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000501 // to check this.
502 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, IntPtrTy);
503 llvm::Value *Min = Builder.getFalse();
Richard Smith2d8b2942012-11-01 07:22:08 +0000504 llvm::Value *CastAddr = Builder.CreateBitCast(Address, Int8PtrTy);
Richard Smith69d0d262012-08-24 00:54:33 +0000505 llvm::Value *LargeEnough =
Richard Smith2d8b2942012-11-01 07:22:08 +0000506 Builder.CreateICmpUGE(Builder.CreateCall2(F, CastAddr, Min),
Richard Smith69d0d262012-08-24 00:54:33 +0000507 llvm::ConstantInt::get(IntPtrTy, Size));
508 Cond = Cond ? Builder.CreateAnd(Cond, LargeEnough) : LargeEnough;
Richard Smithe30752c2012-10-09 19:52:38 +0000509 }
Richard Smith69d0d262012-08-24 00:54:33 +0000510
Richard Smithb1b0ab42012-11-05 22:21:05 +0000511 uint64_t AlignVal = 0;
512
513 if (getLangOpts().SanitizeAlignment) {
514 AlignVal = Alignment.getQuantity();
515 if (!Ty->isIncompleteType() && !AlignVal)
516 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
517
Richard Smith69d0d262012-08-24 00:54:33 +0000518 // The glvalue must be suitably aligned.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000519 if (AlignVal) {
520 llvm::Value *Align =
521 Builder.CreateAnd(Builder.CreatePtrToInt(Address, IntPtrTy),
522 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
523 llvm::Value *Aligned =
524 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
525 Cond = Cond ? Builder.CreateAnd(Cond, Aligned) : Aligned;
526 }
Richard Smith69d0d262012-08-24 00:54:33 +0000527 }
528
Richard Smithe30752c2012-10-09 19:52:38 +0000529 if (Cond) {
530 llvm::Constant *StaticData[] = {
531 EmitCheckSourceLocation(Loc),
532 EmitCheckTypeDescriptor(Ty),
533 llvm::ConstantInt::get(SizeTy, AlignVal),
534 llvm::ConstantInt::get(Int8Ty, TCK)
535 };
Will Dietz88e02332012-12-02 19:50:33 +0000536 EmitCheck(Cond, "type_mismatch", StaticData, Address, CRK_Recoverable);
Richard Smithe30752c2012-10-09 19:52:38 +0000537 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000538
Richard Smithb1b0ab42012-11-05 22:21:05 +0000539 // If possible, check that the vptr indicates that there is a subobject of
540 // type Ty at offset zero within this object.
Richard Smith4d3110a2012-10-25 02:14:12 +0000541 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Richard Smithb1b0ab42012-11-05 22:21:05 +0000542 if (getLangOpts().SanitizeVptr && TCK != TCK_ConstructorCall &&
Richard Smith4d3110a2012-10-25 02:14:12 +0000543 RD && RD->hasDefinition() && RD->isDynamicClass()) {
Richard Smith4d3110a2012-10-25 02:14:12 +0000544 // Compute a hash of the mangled name of the type.
545 //
546 // FIXME: This is not guaranteed to be deterministic! Move to a
547 // fingerprinting mechanism once LLVM provides one. For the time
548 // being the implementation happens to be deterministic.
549 llvm::SmallString<64> MangledName;
550 llvm::raw_svector_ostream Out(MangledName);
551 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
552 Out);
553 llvm::hash_code TypeHash = hash_value(Out.str());
554
555 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
556 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
557 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
558 llvm::Value *VPtrAddr = Builder.CreateBitCast(Address, VPtrTy);
559 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
560 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
561
562 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
563 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
564
565 // Look the hash up in our cache.
566 const int CacheSize = 128;
567 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
568 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
569 "__ubsan_vptr_type_cache");
570 llvm::Value *Slot = Builder.CreateAnd(Hash,
571 llvm::ConstantInt::get(IntPtrTy,
572 CacheSize-1));
573 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
574 llvm::Value *CacheVal =
575 Builder.CreateLoad(Builder.CreateInBoundsGEP(Cache, Indices));
576
577 // If the hash isn't in the cache, call a runtime handler to perform the
578 // hard work of checking whether the vptr is for an object of the right
579 // type. This will either fill in the cache and return, or produce a
580 // diagnostic.
581 llvm::Constant *StaticData[] = {
582 EmitCheckSourceLocation(Loc),
583 EmitCheckTypeDescriptor(Ty),
584 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
585 llvm::ConstantInt::get(Int8Ty, TCK)
586 };
587 llvm::Value *DynamicData[] = { Address, Hash };
588 EmitCheck(Builder.CreateICmpEQ(CacheVal, Hash),
Will Dietz88e02332012-12-02 19:50:33 +0000589 "dynamic_type_cache_miss", StaticData, DynamicData,
590 CRK_AlwaysRecoverable);
Richard Smith4d3110a2012-10-25 02:14:12 +0000591 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000592}
Chris Lattner4647a212007-08-31 22:49:20 +0000593
Chris Lattner116ce8f2010-01-09 21:40:03 +0000594
Chris Lattner116ce8f2010-01-09 21:40:03 +0000595CodeGenFunction::ComplexPairTy CodeGenFunction::
596EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
597 bool isInc, bool isPre) {
598 ComplexPairTy InVal = LoadComplexFromAddr(LV.getAddress(),
599 LV.isVolatileQualified());
600
601 llvm::Value *NextVal;
602 if (isa<llvm::IntegerType>(InVal.first->getType())) {
603 uint64_t AmountVal = isInc ? 1 : -1;
604 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
605
606 // Add the inc/dec to the real part.
607 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
608 } else {
609 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
610 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
611 if (!isInc)
612 FVal.changeSign();
613 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
614
615 // Add the inc/dec to the real part.
616 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
617 }
618
619 ComplexPairTy IncVal(NextVal, InVal.second);
620
621 // Store the updated result through the lvalue.
622 StoreComplexToAddr(IncVal, LV.getAddress(), LV.isVolatileQualified());
623
624 // If this is a postinc, return the value read from memory, otherwise use the
625 // updated value.
626 return isPre ? IncVal : InVal;
627}
628
629
Chris Lattnera45c5af2007-06-02 19:47:04 +0000630//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000631// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000632//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000633
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000634RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000635 if (Ty->isVoidType())
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000636 return RValue::get(0);
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000637
638 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000639 llvm::Type *EltTy = ConvertType(CTy->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +0000640 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000641 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000642 }
643
Chris Lattner65526f02010-08-23 05:26:13 +0000644 // If this is a use of an undefined aggregate type, the aggregate must have an
645 // identifiable address. Just because the contents of the value are undefined
646 // doesn't mean that the address can't be taken and compared.
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000647 if (hasAggregateLLVMType(Ty)) {
Chris Lattner65526f02010-08-23 05:26:13 +0000648 llvm::Value *DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
649 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000650 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000651
652 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
Daniel Dunbarbb197e42009-01-09 16:50:52 +0000653}
654
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000655RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
656 const char *Name) {
657 ErrorUnsupported(E, Name);
658 return GetUndefRValue(E->getType());
659}
660
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000661LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
662 const char *Name) {
663 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000664 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000665 return MakeAddrLValue(llvm::UndefValue::get(Ty), E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000666}
667
Richard Smith4d1458e2012-09-08 02:08:36 +0000668LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000669 LValue LV = EmitLValue(E);
Daniel Dunbardc406b82010-04-05 21:36:35 +0000670 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
Richard Smithe30752c2012-10-09 19:52:38 +0000671 EmitTypeCheck(TCK, E->getExprLoc(), LV.getAddress(),
672 E->getType(), LV.getAlignment());
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000673 return LV;
674}
675
Chris Lattner8394d792007-06-05 20:53:16 +0000676/// EmitLValue - Emit code to compute a designator that specifies the location
677/// of the expression.
678///
Mike Stump4a3999f2009-09-09 13:00:44 +0000679/// This can return one of two things: a simple address or a bitfield reference.
680/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
681/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +0000682///
Mike Stump4a3999f2009-09-09 13:00:44 +0000683/// If this returns a bitfield reference, nothing about the pointee type of the
684/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +0000685///
Mike Stump4a3999f2009-09-09 13:00:44 +0000686/// If this returns a normal address, and if the lvalue's C type is fixed size,
687/// this method guarantees that the returned pointer type will point to an LLVM
688/// type of the same size of the lvalue's type. If the lvalue has a variable
689/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +0000690///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000691LValue CodeGenFunction::EmitLValue(const Expr *E) {
692 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000693 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000694
John McCallc109a252011-11-07 03:59:57 +0000695 case Expr::ObjCPropertyRefExprClass:
696 llvm_unreachable("cannot emit a property reference directly");
697
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000698 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +0000699 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000700 case Expr::ObjCIsaExprClass:
701 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000702 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +0000703 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
Douglas Gregor914af212010-04-23 04:16:32 +0000704 case Expr::CompoundAssignOperatorClass:
John McCalla2342eb2010-12-05 02:00:02 +0000705 if (!E->getType()->isAnyComplexType())
706 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
707 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000708 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +0000709 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000710 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +0000711 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000712 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +0000713 case Expr::VAArgExprClass:
714 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000715 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000716 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +0000717 case Expr::ParenExprClass:
718 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +0000719 case Expr::GenericSelectionExprClass:
720 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +0000721 case Expr::PredefinedExprClass:
722 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +0000723 case Expr::StringLiteralClass:
724 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +0000725 case Expr::ObjCEncodeExprClass:
726 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +0000727 case Expr::PseudoObjectExprClass:
728 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +0000729 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +0000730 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +0000731 case Expr::CXXTemporaryObjectExprClass:
732 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +0000733 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
734 case Expr::CXXBindTemporaryExprClass:
735 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +0000736 case Expr::CXXUuidofExprClass:
737 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +0000738 case Expr::LambdaExprClass:
739 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +0000740
741 case Expr::ExprWithCleanupsClass: {
742 const ExprWithCleanups *cleanups = cast<ExprWithCleanups>(E);
743 enterFullExpression(cleanups);
744 RunCleanupsScope Scope(*this);
745 return EmitLValue(cleanups->getSubExpr());
746 }
747
Douglas Gregor747eb782010-07-08 06:14:04 +0000748 case Expr::CXXScalarValueInitExprClass:
749 return EmitNullInitializationLValue(cast<CXXScalarValueInitExpr>(E));
Anders Carlsson52ce3bb2009-11-14 01:51:50 +0000750 case Expr::CXXDefaultArgExprClass:
751 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Mike Stumpc9b231c2009-11-15 08:09:41 +0000752 case Expr::CXXTypeidExprClass:
753 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +0000754
Daniel Dunbarc8317a42008-08-23 10:51:21 +0000755 case Expr::ObjCMessageExprClass:
756 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000757 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +0000758 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +0000759 case Expr::StmtExprClass:
760 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000761 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +0000762 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000763 case Expr::ArraySubscriptExprClass:
764 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +0000765 case Expr::ExtVectorElementExprClass:
766 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000767 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +0000768 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +0000769 case Expr::CompoundLiteralExprClass:
770 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +0000771 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +0000772 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +0000773 case Expr::BinaryConditionalOperatorClass:
774 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +0000775 case Expr::ChooseExprClass:
Eli Friedmane0a5b8b2009-03-04 05:52:32 +0000776 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr(getContext()));
John McCall1bf58462011-02-16 08:02:54 +0000777 case Expr::OpaqueValueExprClass:
778 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +0000779 case Expr::SubstNonTypeTemplateParmExprClass:
780 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +0000781 case Expr::ImplicitCastExprClass:
782 case Expr::CStyleCastExprClass:
783 case Expr::CXXFunctionalCastExprClass:
784 case Expr::CXXStaticCastExprClass:
785 case Expr::CXXDynamicCastExprClass:
786 case Expr::CXXReinterpretCastExprClass:
787 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +0000788 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +0000789 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +0000790
Douglas Gregorfe314812011-06-21 17:03:29 +0000791 case Expr::MaterializeTemporaryExprClass:
792 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000793 }
794}
795
John McCall71335052012-03-10 03:05:10 +0000796/// Given an object of the given canonical type, can we safely copy a
797/// value out of it based on its initializer?
798static bool isConstantEmittableObjectType(QualType type) {
799 assert(type.isCanonical());
800 assert(!type->isReferenceType());
801
802 // Must be const-qualified but non-volatile.
803 Qualifiers qs = type.getLocalQualifiers();
804 if (!qs.hasConst() || qs.hasVolatile()) return false;
805
806 // Otherwise, all object types satisfy this except C++ classes with
807 // mutable subobjects or non-trivial copy/destroy behavior.
808 if (const RecordType *RT = dyn_cast<RecordType>(type))
809 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
810 if (RD->hasMutableFields() || !RD->isTrivial())
811 return false;
812
813 return true;
814}
815
816/// Can we constant-emit a load of a reference to a variable of the
817/// given type? This is different from predicates like
818/// Decl::isUsableInConstantExpressions because we do want it to apply
819/// in situations that don't necessarily satisfy the language's rules
820/// for this (e.g. C++'s ODR-use rules). For example, we want to able
821/// to do this with const float variables even if those variables
822/// aren't marked 'constexpr'.
823enum ConstantEmissionKind {
824 CEK_None,
825 CEK_AsReferenceOnly,
826 CEK_AsValueOrReference,
827 CEK_AsValueOnly
828};
829static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
830 type = type.getCanonicalType();
831 if (const ReferenceType *ref = dyn_cast<ReferenceType>(type)) {
832 if (isConstantEmittableObjectType(ref->getPointeeType()))
833 return CEK_AsValueOrReference;
834 return CEK_AsReferenceOnly;
835 }
836 if (isConstantEmittableObjectType(type))
837 return CEK_AsValueOnly;
838 return CEK_None;
839}
840
841/// Try to emit a reference to the given value without producing it as
842/// an l-value. This is actually more than an optimization: we can't
843/// produce an l-value for variables that we never actually captured
844/// in a block or lambda, which means const int variables or constexpr
845/// literals or similar.
846CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +0000847CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
848 ValueDecl *value = refExpr->getDecl();
849
John McCall71335052012-03-10 03:05:10 +0000850 // The value needs to be an enum constant or a constant variable.
851 ConstantEmissionKind CEK;
852 if (isa<ParmVarDecl>(value)) {
853 CEK = CEK_None;
854 } else if (VarDecl *var = dyn_cast<VarDecl>(value)) {
855 CEK = checkVarTypeForConstantEmission(var->getType());
856 } else if (isa<EnumConstantDecl>(value)) {
857 CEK = CEK_AsValueOnly;
858 } else {
859 CEK = CEK_None;
860 }
861 if (CEK == CEK_None) return ConstantEmission();
862
John McCall71335052012-03-10 03:05:10 +0000863 Expr::EvalResult result;
864 bool resultIsReference;
865 QualType resultType;
866
867 // It's best to evaluate all the way as an r-value if that's permitted.
868 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +0000869 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +0000870 resultIsReference = false;
871 resultType = refExpr->getType();
872
873 // Otherwise, try to evaluate as an l-value.
874 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +0000875 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +0000876 resultIsReference = true;
877 resultType = value->getType();
878
879 // Failure.
880 } else {
881 return ConstantEmission();
882 }
883
884 // In any case, if the initializer has side-effects, abandon ship.
885 if (result.HasSideEffects)
886 return ConstantEmission();
887
888 // Emit as a constant.
889 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
890
891 // Make sure we emit a debug reference to the global variable.
892 // This should probably fire even for
893 if (isa<VarDecl>(value)) {
894 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
John McCall113bee02012-03-10 09:33:50 +0000895 EmitDeclRefExprDbgValue(refExpr, C);
John McCall71335052012-03-10 03:05:10 +0000896 } else {
897 assert(isa<EnumConstantDecl>(value));
John McCall113bee02012-03-10 09:33:50 +0000898 EmitDeclRefExprDbgValue(refExpr, C);
John McCall71335052012-03-10 03:05:10 +0000899 }
900
901 // If we emitted a reference constant, we need to dereference that.
902 if (resultIsReference)
903 return ConstantEmission::forReference(C);
904
905 return ConstantEmission::forValue(C);
906}
907
John McCall1553b192011-06-16 04:16:24 +0000908llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue) {
909 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
Eli Friedmana0544d62011-12-03 04:14:32 +0000910 lvalue.getAlignment().getQuantity(),
911 lvalue.getType(), lvalue.getTBAAInfo());
John McCall1553b192011-06-16 04:16:24 +0000912}
913
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000914static bool hasBooleanRepresentation(QualType Ty) {
915 if (Ty->isBooleanType())
916 return true;
917
918 if (const EnumType *ET = Ty->getAs<EnumType>())
919 return ET->getDecl()->getIntegerType()->isBooleanType();
920
Douglas Gregor298f43d2012-04-12 20:42:30 +0000921 if (const AtomicType *AT = Ty->getAs<AtomicType>())
922 return hasBooleanRepresentation(AT->getValueType());
923
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000924 return false;
925}
926
927llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
928 const EnumType *ET = Ty->getAs<EnumType>();
Chandler Carruth8b4140d2012-03-27 23:58:37 +0000929 bool IsRegularCPlusPlusEnum = (getLangOpts().CPlusPlus && ET &&
930 CGM.getCodeGenOpts().StrictEnums &&
931 !ET->getDecl()->isFixed());
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000932 bool IsBool = hasBooleanRepresentation(Ty);
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000933 if (!IsBool && !IsRegularCPlusPlusEnum)
934 return NULL;
935
936 llvm::APInt Min;
937 llvm::APInt End;
938 if (IsBool) {
Eli Friedmanb369f442012-11-13 02:05:15 +0000939 Min = llvm::APInt(getContext().getTypeSize(Ty), 0);
940 End = llvm::APInt(getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000941 } else {
942 const EnumDecl *ED = ET->getDecl();
Ted Kremenekdb74d0b2012-05-01 17:56:53 +0000943 llvm::Type *LTy = ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000944 unsigned Bitwidth = LTy->getScalarSizeInBits();
945 unsigned NumNegativeBits = ED->getNumNegativeBits();
946 unsigned NumPositiveBits = ED->getNumPositiveBits();
947
948 if (NumNegativeBits) {
949 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
950 assert(NumBits <= Bitwidth);
951 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
952 Min = -End;
953 } else {
954 assert(NumPositiveBits <= Bitwidth);
955 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
956 Min = llvm::APInt(Bitwidth, 0);
957 }
958 }
959
Duncan Sandsc720e782012-04-15 18:04:54 +0000960 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +0000961 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +0000962}
963
Daniel Dunbar1d425462009-02-10 00:57:50 +0000964llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
Dan Gohman947c9af2010-10-14 23:06:10 +0000965 unsigned Alignment, QualType Ty,
966 llvm::MDNode *TBAAInfo) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +0000967
968 // For better performance, handle vector loads differently.
969 if (Ty->isVectorType()) {
970 llvm::Value *V;
971 const llvm::Type *EltTy =
972 cast<llvm::PointerType>(Addr->getType())->getElementType();
973
974 const llvm::VectorType *VTy = cast<llvm::VectorType>(EltTy);
975
976 // Handle vectors of size 3, like size 4 for better performance.
977 if (VTy->getNumElements() == 3) {
978
979 // Bitcast to vec4 type.
980 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
981 4);
982 llvm::PointerType *ptVec4Ty =
983 llvm::PointerType::get(vec4Ty,
984 (cast<llvm::PointerType>(
985 Addr->getType()))->getAddressSpace());
986 llvm::Value *Cast = Builder.CreateBitCast(Addr, ptVec4Ty,
987 "castToVec4");
988 // Now load value.
989 llvm::Value *LoadVal = Builder.CreateLoad(Cast, Volatile, "loadVec4");
990
991 // Shuffle vector to get vec3.
992 llvm::SmallVector<llvm::Constant*, 3> Mask;
993 Mask.push_back(llvm::ConstantInt::get(
994 llvm::Type::getInt32Ty(getLLVMContext()),
995 0));
996 Mask.push_back(llvm::ConstantInt::get(
997 llvm::Type::getInt32Ty(getLLVMContext()),
998 1));
999 Mask.push_back(llvm::ConstantInt::get(
1000 llvm::Type::getInt32Ty(getLLVMContext()),
1001 2));
1002
1003 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1004 V = Builder.CreateShuffleVector(LoadVal,
1005 llvm::UndefValue::get(vec4Ty),
1006 MaskV, "extractVec");
1007 return EmitFromMemory(V, Ty);
1008 }
1009 }
1010
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001011 llvm::LoadInst *Load = Builder.CreateLoad(Addr);
Daniel Dunbarc76493a2009-11-29 21:23:36 +00001012 if (Volatile)
1013 Load->setVolatile(true);
Daniel Dunbar03816342010-08-21 02:24:36 +00001014 if (Alignment)
1015 Load->setAlignment(Alignment);
Dan Gohman947c9af2010-10-14 23:06:10 +00001016 if (TBAAInfo)
1017 CGM.DecorateInstruction(Load, TBAAInfo);
David Chisnallfa35df62012-01-16 17:27:18 +00001018 // If this is an atomic type, all normal reads must be atomic
1019 if (Ty->isAtomicType())
1020 Load->setAtomic(llvm::SequentiallyConsistent);
Daniel Dunbar1d425462009-02-10 00:57:50 +00001021
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001022 if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1023 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1024 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001025
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001026 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001027}
1028
John McCall3a7f6922010-10-27 20:58:56 +00001029llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1030 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001031 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001032 // This should really always be an i1, but sometimes it's already
1033 // an i8, and it's awkward to track those cases down.
1034 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001035 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1036 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1037 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001038 }
1039
1040 return Value;
1041}
1042
1043llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1044 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001045 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001046 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1047 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001048 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1049 }
1050
1051 return Value;
1052}
1053
Daniel Dunbar1d425462009-02-10 00:57:50 +00001054void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
Daniel Dunbar03816342010-08-21 02:24:36 +00001055 bool Volatile, unsigned Alignment,
Dan Gohman947c9af2010-10-14 23:06:10 +00001056 QualType Ty,
David Chisnallfa35df62012-01-16 17:27:18 +00001057 llvm::MDNode *TBAAInfo,
1058 bool isInit) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001059
1060 // Handle vectors differently to get better performance.
1061 if (Ty->isVectorType()) {
1062 llvm::Type *SrcTy = Value->getType();
1063 llvm::VectorType *VecTy = cast<llvm::VectorType>(SrcTy);
1064 // Handle vec3 special.
1065 if (VecTy->getNumElements() == 3) {
1066 llvm::LLVMContext &VMContext = getLLVMContext();
1067
1068 // Our source is a vec3, do a shuffle vector to make it a vec4.
1069 llvm::SmallVector<llvm::Constant*, 4> Mask;
1070 Mask.push_back(llvm::ConstantInt::get(
1071 llvm::Type::getInt32Ty(VMContext),
1072 0));
1073 Mask.push_back(llvm::ConstantInt::get(
1074 llvm::Type::getInt32Ty(VMContext),
1075 1));
1076 Mask.push_back(llvm::ConstantInt::get(
1077 llvm::Type::getInt32Ty(VMContext),
1078 2));
1079 Mask.push_back(llvm::UndefValue::get(llvm::Type::getInt32Ty(VMContext)));
1080
1081 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1082 Value = Builder.CreateShuffleVector(Value,
1083 llvm::UndefValue::get(VecTy),
1084 MaskV, "extractVec");
1085 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1086 }
1087 llvm::PointerType *DstPtr = cast<llvm::PointerType>(Addr->getType());
1088 if (DstPtr->getElementType() != SrcTy) {
1089 llvm::Type *MemTy =
1090 llvm::PointerType::get(SrcTy, DstPtr->getAddressSpace());
1091 Addr = Builder.CreateBitCast(Addr, MemTy, "storetmp");
1092 }
1093 }
1094
John McCall3a7f6922010-10-27 20:58:56 +00001095 Value = EmitToMemory(Value, Ty);
Chris Lattner1a5f8972011-07-10 03:38:35 +00001096
Daniel Dunbar03816342010-08-21 02:24:36 +00001097 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1098 if (Alignment)
1099 Store->setAlignment(Alignment);
Dan Gohman947c9af2010-10-14 23:06:10 +00001100 if (TBAAInfo)
1101 CGM.DecorateInstruction(Store, TBAAInfo);
David Chisnallfa35df62012-01-16 17:27:18 +00001102 if (!isInit && Ty->isAtomicType())
1103 Store->setAtomic(llvm::SequentiallyConsistent);
Daniel Dunbar1d425462009-02-10 00:57:50 +00001104}
1105
David Chisnallfa35df62012-01-16 17:27:18 +00001106void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1107 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001108 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
Eli Friedmana0544d62011-12-03 04:14:32 +00001109 lvalue.getAlignment().getQuantity(), lvalue.getType(),
David Chisnallfa35df62012-01-16 17:27:18 +00001110 lvalue.getTBAAInfo(), isInit);
John McCall1553b192011-06-16 04:16:24 +00001111}
1112
Mike Stump4a3999f2009-09-09 13:00:44 +00001113/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1114/// method emits the address of the lvalue, then loads the result as an rvalue,
1115/// returning the rvalue.
John McCall55e1fbc2011-06-25 02:11:03 +00001116RValue CodeGenFunction::EmitLoadOfLValue(LValue LV) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001117 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001118 // load of a __weak object.
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001119 llvm::Value *AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001120 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1121 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001122 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001123 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1124 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1125 Object = EmitObjCConsumeObject(LV.getType(), Object);
1126 return RValue::get(Object);
1127 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001128
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001129 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001130 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001131
John McCalla1dee5302010-08-22 10:59:02 +00001132 // Everything needs a load.
John McCall55e1fbc2011-06-25 02:11:03 +00001133 return RValue::get(EmitLoadOfScalar(LV));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001134 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001135
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001136 if (LV.isVectorElt()) {
Eli Friedman610bb872012-03-22 22:36:39 +00001137 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddr(),
1138 LV.isVolatileQualified());
1139 Load->setAlignment(LV.getAlignment().getQuantity());
1140 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001141 "vecext"));
1142 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001143
1144 // If this is a reference to a subset of the elements of a vector, either
1145 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001146 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001147 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001148
John McCallc109a252011-11-07 03:59:57 +00001149 assert(LV.isBitField() && "Unknown LValue type!");
1150 return EmitLoadOfBitfieldLValue(LV);
Chris Lattner8394d792007-06-05 20:53:16 +00001151}
1152
John McCall55e1fbc2011-06-25 02:11:03 +00001153RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001154 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001155
Daniel Dunbar3447a022010-04-13 23:34:15 +00001156 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001157 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001158
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001159 llvm::Value *Ptr = LV.getBitFieldAddr();
1160 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(),
1161 "bf.load");
1162 cast<llvm::LoadInst>(Val)->setAlignment(Info.StorageAlignment);
Mike Stump4a3999f2009-09-09 13:00:44 +00001163
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001164 if (Info.IsSigned) {
1165 assert((Info.Offset + Info.Size) <= Info.StorageSize);
1166 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1167 if (HighBits)
1168 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1169 if (Info.Offset + HighBits)
1170 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1171 } else {
1172 if (Info.Offset)
1173 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
1174 if (Info.Offset + Info.Size < Info.StorageSize)
1175 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1176 Info.Size),
1177 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001178 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001179 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001180
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001181 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001182}
1183
Nate Begemanb699c9b2009-01-18 06:42:49 +00001184// If this is a reference to a subset of the elements of a vector, create an
1185// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001186RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
Eli Friedman610bb872012-03-22 22:36:39 +00001187 llvm::LoadInst *Load = Builder.CreateLoad(LV.getExtVectorAddr(),
1188 LV.isVolatileQualified());
1189 Load->setAlignment(LV.getAlignment().getQuantity());
1190 llvm::Value *Vec = Load;
Mike Stump4a3999f2009-09-09 13:00:44 +00001191
Nate Begemanf322eab2008-05-09 06:41:27 +00001192 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001193
1194 // If the result of the expression is a non-vector type, we must be extracting
1195 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001196 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001197 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001198 unsigned InIdx = getAccessedFieldNo(0, Elts);
Chris Lattner5e016ae2010-06-27 07:15:29 +00001199 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001200 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001201 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001202
1203 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001204 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001205
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001206 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001207 for (unsigned i = 0; i != NumResultElts; ++i)
1208 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001209
Chris Lattner91c08ad2011-02-15 00:14:06 +00001210 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1211 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001212 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001213 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001214}
1215
1216
Chris Lattner9369a562007-06-29 16:31:29 +00001217
Chris Lattner8394d792007-06-05 20:53:16 +00001218/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1219/// lvalue, where both are guaranteed to the have the same type, and that type
1220/// is 'Ty'.
David Chisnallfa35df62012-01-16 17:27:18 +00001221void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001222 if (!Dst.isSimple()) {
1223 if (Dst.isVectorElt()) {
1224 // Read/modify/write the vector, inserting the new element.
Eli Friedman610bb872012-03-22 22:36:39 +00001225 llvm::LoadInst *Load = Builder.CreateLoad(Dst.getVectorAddr(),
1226 Dst.isVolatileQualified());
1227 Load->setAlignment(Dst.getAlignment().getQuantity());
1228 llvm::Value *Vec = Load;
Chris Lattner4647a212007-08-31 22:49:20 +00001229 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001230 Dst.getVectorIdx(), "vecins");
Eli Friedman610bb872012-03-22 22:36:39 +00001231 llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getVectorAddr(),
1232 Dst.isVolatileQualified());
1233 Store->setAlignment(Dst.getAlignment().getQuantity());
Chris Lattner41d480e2007-08-03 16:28:33 +00001234 return;
1235 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001236
Nate Begemance4d7fc2008-04-18 23:10:10 +00001237 // If this is an update of extended vector elements, insert them as
1238 // appropriate.
1239 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001240 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001241
John McCallc109a252011-11-07 03:59:57 +00001242 assert(Dst.isBitField() && "Unknown LValue type");
1243 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001244 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001245
John McCall31168b02011-06-15 23:02:42 +00001246 // There's special magic for assigning into an ARC-qualified l-value.
1247 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1248 switch (Lifetime) {
1249 case Qualifiers::OCL_None:
1250 llvm_unreachable("present but none");
1251
1252 case Qualifiers::OCL_ExplicitNone:
1253 // nothing special
1254 break;
1255
1256 case Qualifiers::OCL_Strong:
John McCall55e1fbc2011-06-25 02:11:03 +00001257 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001258 return;
1259
1260 case Qualifiers::OCL_Weak:
1261 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1262 return;
1263
1264 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001265 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1266 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001267 // fall into the normal path
1268 break;
1269 }
1270 }
1271
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001272 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001273 // load of a __weak object.
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001274 llvm::Value *LvalueDst = Dst.getAddress();
1275 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001276 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001277 return;
1278 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001279
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001280 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001281 // load of a __strong object.
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001282 llvm::Value *LvalueDst = Dst.getAddress();
1283 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001284 if (Dst.isObjCIvar()) {
1285 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
Chris Lattner2192fe52011-07-18 04:24:23 +00001286 llvm::Type *ResultType = ConvertType(getContext().LongTy);
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001287 llvm::Value *RHS = EmitScalarExpr(Dst.getBaseIvarExp());
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001288 llvm::Value *dst = RHS;
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001289 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1290 llvm::Value *LHS =
1291 Builder.CreatePtrToInt(LvalueDst, ResultType, "sub.ptr.lhs.cast");
1292 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001293 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001294 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001295 } else if (Dst.isGlobalObjCRef()) {
1296 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1297 Dst.isThreadLocalRef());
1298 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001299 else
1300 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001301 return;
1302 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001303
Chris Lattner6278e6a2007-08-11 00:04:45 +00001304 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001305 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001306}
1307
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001308void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001309 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001310 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001311 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001312 llvm::Value *Ptr = Dst.getBitFieldAddr();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001313
Daniel Dunbar67aba792010-04-15 03:47:33 +00001314 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001315 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001316
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001317 // Cast the source to the storage type and shift it into place.
1318 SrcVal = Builder.CreateIntCast(SrcVal,
1319 Ptr->getType()->getPointerElementType(),
1320 /*IsSigned=*/false);
1321 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001322
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001323 // See if there are other bits in the bitfield's storage we'll need to load
1324 // and mask together with source before storing.
1325 if (Info.StorageSize != Info.Size) {
1326 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
1327 llvm::Value *Val = Builder.CreateLoad(Ptr, Dst.isVolatileQualified(),
1328 "bf.load");
1329 cast<llvm::LoadInst>(Val)->setAlignment(Info.StorageAlignment);
1330
1331 // Mask the source value as needed.
1332 if (!hasBooleanRepresentation(Dst.getType()))
1333 SrcVal = Builder.CreateAnd(SrcVal,
1334 llvm::APInt::getLowBitsSet(Info.StorageSize,
1335 Info.Size),
1336 "bf.value");
1337 MaskedVal = SrcVal;
1338 if (Info.Offset)
1339 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1340
1341 // Mask out the original value.
1342 Val = Builder.CreateAnd(Val,
1343 ~llvm::APInt::getBitsSet(Info.StorageSize,
1344 Info.Offset,
1345 Info.Offset + Info.Size),
1346 "bf.clear");
1347
1348 // Or together the unchanged values and the source value.
1349 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1350 } else {
1351 assert(Info.Offset == 0);
1352 }
1353
1354 // Write the new value back out.
1355 llvm::StoreInst *Store = Builder.CreateStore(SrcVal, Ptr,
1356 Dst.isVolatileQualified());
1357 Store->setAlignment(Info.StorageAlignment);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001358
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001359 // Return the new value of the bit-field, if requested.
1360 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001361 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001362
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001363 // Sign extend the value if needed.
1364 if (Info.IsSigned) {
1365 assert(Info.Size <= Info.StorageSize);
1366 unsigned HighBits = Info.StorageSize - Info.Size;
1367 if (HighBits) {
1368 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1369 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1370 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001371 }
1372
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001373 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1374 "bf.result.cast");
1375 *Result = ResultVal;
Daniel Dunbaread7c912008-08-06 05:08:45 +00001376 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001377}
1378
Nate Begemance4d7fc2008-04-18 23:10:10 +00001379void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001380 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001381 // This access turns into a read/modify/write of the vector. Load the input
1382 // value now.
Eli Friedman610bb872012-03-22 22:36:39 +00001383 llvm::LoadInst *Load = Builder.CreateLoad(Dst.getExtVectorAddr(),
1384 Dst.isVolatileQualified());
1385 Load->setAlignment(Dst.getAlignment().getQuantity());
1386 llvm::Value *Vec = Load;
Nate Begemanf322eab2008-05-09 06:41:27 +00001387 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001388
Chris Lattner4647a212007-08-31 22:49:20 +00001389 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001390
John McCall55e1fbc2011-06-25 02:11:03 +00001391 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001392 unsigned NumSrcElts = VTy->getNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001393 unsigned NumDstElts =
1394 cast<llvm::VectorType>(Vec->getType())->getNumElements();
1395 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001396 // Use shuffle vector is the src and destination are the same number of
1397 // elements and restore the vector mask since it is on the side it will be
1398 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001399 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001400 for (unsigned i = 0; i != NumSrcElts; ++i)
1401 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001402
Chris Lattner91c08ad2011-02-15 00:14:06 +00001403 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001404 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001405 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001406 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001407 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001408 // Extended the source vector to the same length and then shuffle it
1409 // into the destination.
1410 // FIXME: since we're shuffling with undef, can we just use the indices
1411 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001412 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001413 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001414 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001415 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001416 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001417 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001418 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001419 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001420 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001421 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001422 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001423 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001424 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001425
Nate Begemanb699c9b2009-01-18 06:42:49 +00001426 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001427 for (unsigned i = 0; i != NumSrcElts; ++i)
1428 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001429 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001430 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001431 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001432 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001433 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001434 }
1435 } else {
1436 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001437 unsigned InIdx = getAccessedFieldNo(0, Elts);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001438 llvm::Value *Elt = llvm::ConstantInt::get(Int32Ty, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001439 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001440 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001441
Eli Friedman610bb872012-03-22 22:36:39 +00001442 llvm::StoreInst *Store = Builder.CreateStore(Vec, Dst.getExtVectorAddr(),
1443 Dst.isVolatileQualified());
1444 Store->setAlignment(Dst.getAlignment().getQuantity());
Chris Lattner41d480e2007-08-03 16:28:33 +00001445}
1446
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001447// setObjCGCLValueClass - sets class of he lvalue for the purpose of
1448// generating write-barries API. It is currently a global, ivar,
1449// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001450static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001451 LValue &LV,
1452 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001453 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001454 return;
1455
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001456 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001457 QualType ExpTy = E->getType();
1458 if (IsMemberAccess && ExpTy->isPointerType()) {
1459 // If ivar is a structure pointer, assigning to field of
1460 // this struct follows gcc's behavior and makes it a non-ivar
1461 // writer-barrier conservatively.
1462 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1463 if (ExpTy->isRecordType()) {
1464 LV.setObjCIvar(false);
1465 return;
1466 }
1467 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001468 LV.setObjCIvar(true);
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001469 ObjCIvarRefExpr *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr*>(E));
1470 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001471 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001472 return;
1473 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001474
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001475 if (const DeclRefExpr *Exp = dyn_cast<DeclRefExpr>(E)) {
1476 if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001477 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001478 LV.setGlobalObjCRef(true);
1479 LV.setThreadLocalRef(VD->isThreadSpecified());
Fariborz Jahanian217af242010-07-20 20:30:03 +00001480 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001481 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001482 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001483 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001484 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001485
1486 if (const UnaryOperator *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001487 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001488 return;
1489 }
1490
1491 if (const ParenExpr *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001492 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001493 if (LV.isObjCIvar()) {
1494 // If cast is to a structure pointer, follow gcc's behavior and make it
1495 // a non-ivar write-barrier.
1496 QualType ExpTy = E->getType();
1497 if (ExpTy->isPointerType())
1498 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1499 if (ExpTy->isRecordType())
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001500 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001501 }
1502 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001503 }
Peter Collingbourne91147592011-04-15 00:35:48 +00001504
1505 if (const GenericSelectionExpr *Exp = dyn_cast<GenericSelectionExpr>(E)) {
1506 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1507 return;
1508 }
1509
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001510 if (const ImplicitCastExpr *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001511 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001512 return;
1513 }
1514
1515 if (const CStyleCastExpr *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001516 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001517 return;
1518 }
John McCall31168b02011-06-15 23:02:42 +00001519
1520 if (const ObjCBridgedCastExpr *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001521 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00001522 return;
1523 }
1524
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001525 if (const ArraySubscriptExpr *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001526 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001527 if (LV.isObjCIvar() && !LV.isObjCArray())
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001528 // Using array syntax to assigning to what an ivar points to is not
1529 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001530 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001531 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
1532 // Using array syntax to assigning to what global points to is not
1533 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001534 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001535 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001536 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001537
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001538 if (const MemberExpr *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001539 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001540 // We don't know if member is an 'ivar', but this flag is looked at
1541 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001542 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001543 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001544 }
1545}
1546
Chris Lattner3f32d692011-07-12 06:52:18 +00001547static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00001548EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00001549 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001550 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00001551 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00001552 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00001553}
1554
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001555static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1556 const Expr *E, const VarDecl *VD) {
Daniel Dunbar7e215ea2009-11-08 09:46:46 +00001557 assert((VD->hasExternalStorage() || VD->isFileVarDecl()) &&
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001558 "Var decl must have external storage or be a file var decl!");
1559
1560 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001561 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
1562 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00001563 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001564 QualType T = E->getType();
1565 LValue LV;
1566 if (VD->getType()->isReferenceType()) {
1567 llvm::LoadInst *LI = CGF.Builder.CreateLoad(V);
Eli Friedmana0544d62011-12-03 04:14:32 +00001568 LI->setAlignment(Alignment.getQuantity());
Eli Friedmand20adbd2011-11-16 00:42:57 +00001569 V = LI;
1570 LV = CGF.MakeNaturalAlignAddrLValue(V, T);
1571 } else {
1572 LV = CGF.MakeAddrLValue(V, E->getType(), Alignment);
1573 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001574 setObjCGCLValueClass(CGF.getContext(), E, LV);
1575 return LV;
1576}
1577
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001578static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
Chris Lattner13ee4f42011-07-10 05:34:54 +00001579 const Expr *E, const FunctionDecl *FD) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00001580 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001581 if (!FD->hasPrototype()) {
1582 if (const FunctionProtoType *Proto =
1583 FD->getType()->getAs<FunctionProtoType>()) {
1584 // Ugly case: for a K&R-style definition, the type of the definition
1585 // isn't the same as the type of a use. Correct for this with a
1586 // bitcast.
1587 QualType NoProtoType =
1588 CGF.getContext().getFunctionNoProtoType(Proto->getResultType());
1589 NoProtoType = CGF.getContext().getPointerType(NoProtoType);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001590 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001591 }
1592 }
Eli Friedmana0544d62011-12-03 04:14:32 +00001593 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
Daniel Dunbar5c816372010-08-21 04:20:22 +00001594 return CGF.MakeAddrLValue(V, E->getType(), Alignment);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001595}
1596
Chris Lattnerd7f58862007-06-02 05:24:33 +00001597LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00001598 const NamedDecl *ND = E->getDecl();
Eli Friedmana0544d62011-12-03 04:14:32 +00001599 CharUnits Alignment = getContext().getDeclAlign(ND);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001600 QualType T = E->getType();
Mike Stump4a3999f2009-09-09 13:00:44 +00001601
Richard Smith5a1104b2012-10-20 01:38:33 +00001602 // A DeclRefExpr for a reference initialized by a constant expression can
1603 // appear without being odr-used. Directly emit the constant initializer.
1604 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1605 const Expr *Init = VD->getAnyInitializer(VD);
1606 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
1607 VD->isUsableInConstantExpressions(getContext()) &&
1608 VD->checkInitIsICE()) {
1609 llvm::Constant *Val =
1610 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
1611 assert(Val && "failed to emit reference constant expression");
1612 // FIXME: Eventually we will want to emit vector element references.
1613 return MakeAddrLValue(Val, T, Alignment);
1614 }
1615 }
1616
Eli Friedman5720e342012-01-21 04:52:58 +00001617 // FIXME: We should be able to assert this for FunctionDecls as well!
1618 // FIXME: We should be able to assert this for all DeclRefExprs, not just
1619 // those with a valid source location.
1620 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
1621 !E->getLocation().isValid()) &&
1622 "Should not use decl without marking it used!");
1623
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001624 if (ND->hasAttr<WeakRefAttr>()) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00001625 const ValueDecl *VD = cast<ValueDecl>(ND);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001626 llvm::Constant *Aliasee = CGM.GetWeakRefReference(VD);
Richard Smith5a1104b2012-10-20 01:38:33 +00001627 return MakeAddrLValue(Aliasee, T, Alignment);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00001628 }
1629
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00001630 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00001631 // Check if this is a global variable.
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001632 if (VD->hasExternalStorage() || VD->isFileVarDecl())
1633 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00001634
John McCall113bee02012-03-10 09:33:50 +00001635 bool isBlockVariable = VD->hasAttr<BlocksAttr>();
1636
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00001637 bool NonGCable = VD->hasLocalStorage() &&
1638 !VD->getType()->isReferenceType() &&
John McCall113bee02012-03-10 09:33:50 +00001639 !isBlockVariable;
Anders Carlsson6eee9722009-11-07 22:46:42 +00001640
1641 llvm::Value *V = LocalDeclMap[VD];
Fariborz Jahanian366a9482010-09-07 23:26:17 +00001642 if (!V && VD->isStaticLocal())
Fariborz Jahanian4d55b2d2010-04-19 18:15:02 +00001643 V = CGM.getStaticLocalDeclAddress(VD);
Eli Friedman9fbeba02012-02-11 02:57:39 +00001644
1645 // Use special handling for lambdas.
John McCall113bee02012-03-10 09:33:50 +00001646 if (!V) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00001647 if (FieldDecl *FD = LambdaCaptureFields.lookup(VD)) {
1648 QualType LambdaTagType = getContext().getTagDeclType(FD->getParent());
1649 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue,
1650 LambdaTagType);
1651 return EmitLValueForField(LambdaLV, FD);
1652 }
Eli Friedman9fbeba02012-02-11 02:57:39 +00001653
John McCall113bee02012-03-10 09:33:50 +00001654 assert(isa<BlockDecl>(CurCodeDecl) && E->refersToEnclosingLocal());
John McCall113bee02012-03-10 09:33:50 +00001655 return MakeAddrLValue(GetAddrOfBlockDecl(VD, isBlockVariable),
Richard Smith5a1104b2012-10-20 01:38:33 +00001656 T, Alignment);
John McCall113bee02012-03-10 09:33:50 +00001657 }
1658
Anders Carlsson6eee9722009-11-07 22:46:42 +00001659 assert(V && "DeclRefExpr not entered in LocalDeclMap?");
1660
John McCall113bee02012-03-10 09:33:50 +00001661 if (isBlockVariable)
Fariborz Jahanian2f2fa722011-01-26 23:08:27 +00001662 V = BuildBlockByrefAddress(V, VD);
Daniel Dunbarf166a522010-08-21 03:44:13 +00001663
Eli Friedmand20adbd2011-11-16 00:42:57 +00001664 LValue LV;
1665 if (VD->getType()->isReferenceType()) {
1666 llvm::LoadInst *LI = Builder.CreateLoad(V);
Eli Friedmana0544d62011-12-03 04:14:32 +00001667 LI->setAlignment(Alignment.getQuantity());
Eli Friedmand20adbd2011-11-16 00:42:57 +00001668 V = LI;
1669 LV = MakeNaturalAlignAddrLValue(V, T);
1670 } else {
1671 LV = MakeAddrLValue(V, T, Alignment);
1672 }
Chris Lattner3f32d692011-07-12 06:52:18 +00001673
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00001674 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00001675 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00001676 LV.setNonGC(true);
1677 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001678 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00001679 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001680 }
John McCallf3a88602011-02-03 08:15:49 +00001681
1682 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(ND))
1683 return EmitFunctionDeclLValue(*this, E, fn);
1684
David Blaikie83d382b2011-09-23 05:06:16 +00001685 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00001686}
Chris Lattnere47e4402007-06-01 18:02:12 +00001687
Chris Lattner8394d792007-06-05 20:53:16 +00001688LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
1689 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00001690 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00001691 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00001692
Chris Lattner0f398c42008-07-26 22:37:01 +00001693 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00001694 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00001695 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00001696 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001697 QualType T = E->getSubExpr()->getType()->getPointeeType();
1698 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00001699
Chris Lattner2415357a2011-12-19 21:16:08 +00001700 LValue LV = MakeNaturalAlignAddrLValue(EmitScalarExpr(E->getSubExpr()), T);
Daniel Dunbarf166a522010-08-21 03:44:13 +00001701 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00001702
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001703 // We should not generate __weak write barrier on indirect reference
1704 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
1705 // But, we continue to generate __strong write barrier on indirect write
1706 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00001707 if (getLangOpts().ObjC1 &&
1708 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001709 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00001710 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001711 return LV;
1712 }
John McCalle3027922010-08-25 11:45:40 +00001713 case UO_Real:
1714 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00001715 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00001716 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
1717 llvm::Value *Addr = LV.getAddress();
1718
Richard Smith0b6b8e42012-02-18 20:53:32 +00001719 // __real is valid on scalars. This is a faster way of testing that.
1720 // __imag can only produce an rvalue on scalars.
1721 if (E->getOpcode() == UO_Real &&
1722 !cast<llvm::PointerType>(Addr->getType())
John McCalla2342eb2010-12-05 02:00:02 +00001723 ->getElementType()->isStructTy()) {
1724 assert(E->getSubExpr()->getType()->isArithmeticType());
1725 return LV;
1726 }
1727
1728 assert(E->getSubExpr()->getType()->isAnyComplexType());
1729
John McCalle3027922010-08-25 11:45:40 +00001730 unsigned Idx = E->getOpcode() == UO_Imag;
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00001731 return MakeAddrLValue(Builder.CreateStructGEP(LV.getAddress(),
John McCalla2342eb2010-12-05 02:00:02 +00001732 Idx, "idx"),
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00001733 ExprTy);
Chris Lattner595db862007-10-30 22:53:42 +00001734 }
John McCalle3027922010-08-25 11:45:40 +00001735 case UO_PreInc:
1736 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00001737 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00001738 bool isInc = E->getOpcode() == UO_PreInc;
Chris Lattnerbb8976e2010-01-09 21:44:40 +00001739
1740 if (E->getType()->isAnyComplexType())
1741 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
1742 else
1743 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
1744 return LV;
1745 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00001746 }
Chris Lattner8394d792007-06-05 20:53:16 +00001747}
1748
Chris Lattner4347e3692007-06-06 04:54:52 +00001749LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001750 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
1751 E->getType());
Chris Lattner4347e3692007-06-06 04:54:52 +00001752}
1753
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001754LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001755 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
1756 E->getType());
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001757}
1758
Nico Weber3a691a32012-06-23 02:07:59 +00001759static llvm::Constant*
1760GetAddrOfConstantWideString(StringRef Str,
1761 const char *GlobalName,
1762 ASTContext &Context,
1763 QualType Ty, SourceLocation Loc,
1764 CodeGenModule &CGM) {
1765
1766 StringLiteral *SL = StringLiteral::Create(Context,
1767 Str,
1768 StringLiteral::Wide,
1769 /*Pascal = */false,
1770 Ty, Loc);
1771 llvm::Constant *C = CGM.GetConstantArrayFromStringLiteral(SL);
1772 llvm::GlobalVariable *GV =
1773 new llvm::GlobalVariable(CGM.getModule(), C->getType(),
1774 !CGM.getLangOpts().WritableStrings,
1775 llvm::GlobalValue::PrivateLinkage,
1776 C, GlobalName);
1777 const unsigned WideAlignment =
1778 Context.getTypeAlignInChars(Ty).getQuantity();
1779 GV->setAlignment(WideAlignment);
1780 return GV;
1781}
1782
Nico Weber3a691a32012-06-23 02:07:59 +00001783static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
1784 SmallString<32>& Target) {
1785 Target.resize(CharByteWidth * (Source.size() + 1));
Richard Smith639b8d02012-09-08 07:16:20 +00001786 char *ResultPtr = &Target[0];
1787 const UTF8 *ErrorPtr;
1788 bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
Matt Beaumont-Gay36af16af2012-07-03 03:55:58 +00001789 (void)success;
Nico Weber4b18c3f2012-07-03 02:24:52 +00001790 assert(success);
Nico Weber3a691a32012-06-23 02:07:59 +00001791 Target.resize(ResultPtr - &Target[0]);
1792}
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001793
Mike Stump4a3999f2009-09-09 13:00:44 +00001794LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Daniel Dunbarb3517472008-10-17 21:58:32 +00001795 switch (E->getIdentType()) {
1796 default:
1797 return EmitUnsupportedLValue(E, "predefined expression");
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001798
Daniel Dunbarb3517472008-10-17 21:58:32 +00001799 case PredefinedExpr::Func:
1800 case PredefinedExpr::Function:
Nico Weber3a691a32012-06-23 02:07:59 +00001801 case PredefinedExpr::LFunction:
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001802 case PredefinedExpr::PrettyFunction: {
Nico Weber3a691a32012-06-23 02:07:59 +00001803 unsigned IdentType = E->getIdentType();
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001804 std::string GlobalVarName;
1805
Nico Weber3a691a32012-06-23 02:07:59 +00001806 switch (IdentType) {
David Blaikie83d382b2011-09-23 05:06:16 +00001807 default: llvm_unreachable("Invalid type");
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001808 case PredefinedExpr::Func:
1809 GlobalVarName = "__func__.";
1810 break;
1811 case PredefinedExpr::Function:
1812 GlobalVarName = "__FUNCTION__.";
1813 break;
Nico Weber3a691a32012-06-23 02:07:59 +00001814 case PredefinedExpr::LFunction:
1815 GlobalVarName = "L__FUNCTION__.";
1816 break;
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001817 case PredefinedExpr::PrettyFunction:
1818 GlobalVarName = "__PRETTY_FUNCTION__.";
1819 break;
1820 }
1821
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001822 StringRef FnName = CurFn->getName();
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001823 if (FnName.startswith("\01"))
1824 FnName = FnName.substr(1);
1825 GlobalVarName += FnName;
1826
1827 const Decl *CurDecl = CurCodeDecl;
1828 if (CurDecl == 0)
1829 CurDecl = getContext().getTranslationUnitDecl();
1830
1831 std::string FunctionName =
John McCall351762c2011-02-07 10:33:21 +00001832 (isa<BlockDecl>(CurDecl)
1833 ? FnName.str()
Nico Weber3a691a32012-06-23 02:07:59 +00001834 : PredefinedExpr::ComputeName((PredefinedExpr::IdentType)IdentType,
1835 CurDecl));
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001836
Nico Weber3a691a32012-06-23 02:07:59 +00001837 const Type* ElemType = E->getType()->getArrayElementTypeNoTypeQual();
1838 llvm::Constant *C;
1839 if (ElemType->isWideCharType()) {
1840 SmallString<32> RawChars;
1841 ConvertUTF8ToWideString(
1842 getContext().getTypeSizeInChars(ElemType).getQuantity(),
1843 FunctionName, RawChars);
1844 C = GetAddrOfConstantWideString(RawChars,
1845 GlobalVarName.c_str(),
1846 getContext(),
1847 E->getType(),
1848 E->getLocation(),
1849 CGM);
1850 } else {
1851 C = CGM.GetAddrOfConstantCString(FunctionName,
1852 GlobalVarName.c_str(),
1853 1);
1854 }
Daniel Dunbar2e442a02010-08-21 03:15:20 +00001855 return MakeAddrLValue(C, E->getType());
Daniel Dunbarb1d94a92010-08-21 03:01:12 +00001856 }
Daniel Dunbarb3517472008-10-17 21:58:32 +00001857 }
Anders Carlsson625bfc82007-07-21 05:21:51 +00001858}
1859
Richard Smithe30752c2012-10-09 19:52:38 +00001860/// Emit a type description suitable for use by a runtime sanitizer library. The
1861/// format of a type descriptor is
1862///
1863/// \code
Richard Smith683398a2012-10-09 23:55:19 +00001864/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00001865/// \endcode
1866///
Richard Smith683398a2012-10-09 23:55:19 +00001867/// followed by an array of i8 containing the type name. TypeKind is 0 for an
1868/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00001869llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
1870 // FIXME: Only emit each type's descriptor once.
1871 uint16_t TypeKind = -1;
1872 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00001873
Richard Smithe30752c2012-10-09 19:52:38 +00001874 if (T->isIntegerType()) {
1875 TypeKind = 0;
1876 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00001877 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00001878 } else if (T->isFloatingType()) {
1879 TypeKind = 1;
1880 TypeInfo = getContext().getTypeSize(T);
1881 }
1882
1883 // Format the type name as if for a diagnostic, including quotes and
1884 // optionally an 'aka'.
1885 llvm::SmallString<32> Buffer;
1886 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
1887 (intptr_t)T.getAsOpaquePtr(),
1888 0, 0, 0, 0, 0, 0, Buffer,
1889 ArrayRef<intptr_t>());
1890
1891 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00001892 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
1893 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00001894 };
1895 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
1896
1897 llvm::GlobalVariable *GV =
1898 new llvm::GlobalVariable(CGM.getModule(), Descriptor->getType(),
1899 /*isConstant=*/true,
1900 llvm::GlobalVariable::PrivateLinkage,
1901 Descriptor);
1902 GV->setUnnamedAddr(true);
1903 return GV;
1904}
1905
1906llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
1907 llvm::Type *TargetTy = IntPtrTy;
1908
1909 // Integers which fit in intptr_t are zero-extended and passed directly.
1910 if (V->getType()->isIntegerTy() &&
1911 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
1912 return Builder.CreateZExt(V, TargetTy);
1913
1914 // Pointers are passed directly, everything else is passed by address.
1915 if (!V->getType()->isPointerTy()) {
1916 llvm::Value *Ptr = Builder.CreateAlloca(V->getType());
1917 Builder.CreateStore(V, Ptr);
1918 V = Ptr;
1919 }
1920 return Builder.CreatePtrToInt(V, TargetTy);
1921}
1922
1923/// \brief Emit a representation of a SourceLocation for passing to a handler
1924/// in a sanitizer runtime library. The format for this data is:
1925/// \code
1926/// struct SourceLocation {
1927/// const char *Filename;
1928/// int32_t Line, Column;
1929/// };
1930/// \endcode
1931/// For an invalid SourceLocation, the Filename pointer is null.
1932llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
1933 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
1934
1935 llvm::Constant *Data[] = {
1936 // FIXME: Only emit each file name once.
1937 PLoc.isValid() ? cast<llvm::Constant>(
1938 Builder.CreateGlobalStringPtr(PLoc.getFilename()))
1939 : llvm::Constant::getNullValue(Int8PtrTy),
1940 Builder.getInt32(PLoc.getLine()),
1941 Builder.getInt32(PLoc.getColumn())
1942 };
1943
1944 return llvm::ConstantStruct::getAnon(Data);
1945}
1946
1947void CodeGenFunction::EmitCheck(llvm::Value *Checked, StringRef CheckName,
1948 llvm::ArrayRef<llvm::Constant *> StaticArgs,
Richard Smith4d3110a2012-10-25 02:14:12 +00001949 llvm::ArrayRef<llvm::Value *> DynamicArgs,
Will Dietz88e02332012-12-02 19:50:33 +00001950 CheckRecoverableKind RecoverKind) {
Richard Smith4d1458e2012-09-08 02:08:36 +00001951 llvm::BasicBlock *Cont = createBasicBlock("cont");
1952
Richard Smithe30752c2012-10-09 19:52:38 +00001953 llvm::BasicBlock *Handler = createBasicBlock("handler." + CheckName);
1954 Builder.CreateCondBr(Checked, Cont, Handler);
1955 EmitBlock(Handler);
1956
1957 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
1958 llvm::GlobalValue *InfoPtr =
1959 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), true,
1960 llvm::GlobalVariable::PrivateLinkage, Info);
1961 InfoPtr->setUnnamedAddr(true);
1962
1963 llvm::SmallVector<llvm::Value *, 4> Args;
1964 llvm::SmallVector<llvm::Type *, 4> ArgTypes;
1965 Args.reserve(DynamicArgs.size() + 1);
1966 ArgTypes.reserve(DynamicArgs.size() + 1);
1967
1968 // Handler functions take an i8* pointing to the (handler-specific) static
1969 // information block, followed by a sequence of intptr_t arguments
1970 // representing operand values.
1971 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
1972 ArgTypes.push_back(Int8PtrTy);
1973 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
1974 Args.push_back(EmitCheckValue(DynamicArgs[i]));
1975 ArgTypes.push_back(IntPtrTy);
1976 }
1977
Will Dietz88e02332012-12-02 19:50:33 +00001978 bool Recover = (RecoverKind == CRK_AlwaysRecoverable) ||
1979 ((RecoverKind == CRK_Recoverable) &&
1980 CGM.getCodeGenOpts().SanitizeRecover);
1981
Richard Smithe30752c2012-10-09 19:52:38 +00001982 llvm::FunctionType *FnType =
1983 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001984 llvm::AttrBuilder B;
Will Dietz88e02332012-12-02 19:50:33 +00001985 if (!Recover) {
Richard Smith4d3110a2012-10-25 02:14:12 +00001986 B.addAttribute(llvm::Attributes::NoReturn)
1987 .addAttribute(llvm::Attributes::NoUnwind);
1988 }
1989 B.addAttribute(llvm::Attributes::UWTable);
Will Dietz88e02332012-12-02 19:50:33 +00001990
1991 // Checks that have two variants use a suffix to differentiate them
1992 bool NeedsAbortSuffix = (RecoverKind != CRK_Unrecoverable) &&
1993 !CGM.getCodeGenOpts().SanitizeRecover;
Richard Smith78f6b032012-12-03 22:39:14 +00001994 std::string FunctionName = ("__ubsan_handle_" + CheckName +
1995 (NeedsAbortSuffix? "_abort" : "")).str();
1996 llvm::Value *Fn =
1997 CGM.CreateRuntimeFunction(FnType, FunctionName,
1998 llvm::Attributes::get(getLLVMContext(), B));
Richard Smithe30752c2012-10-09 19:52:38 +00001999 llvm::CallInst *HandlerCall = Builder.CreateCall(Fn, Args);
Will Dietz88e02332012-12-02 19:50:33 +00002000 if (Recover) {
Richard Smith4d3110a2012-10-25 02:14:12 +00002001 Builder.CreateBr(Cont);
2002 } else {
2003 HandlerCall->setDoesNotReturn();
2004 HandlerCall->setDoesNotThrow();
2005 Builder.CreateUnreachable();
2006 }
Richard Smithe30752c2012-10-09 19:52:38 +00002007
Richard Smith4d1458e2012-09-08 02:08:36 +00002008 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002009}
2010
Richard Smithde670682012-11-01 22:15:34 +00002011void CodeGenFunction::EmitTrapvCheck(llvm::Value *Checked) {
2012 llvm::BasicBlock *Cont = createBasicBlock("cont");
2013
2014 // If we're optimizing, collapse all calls to trap down to just one per
2015 // function to save on code size.
2016 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2017 TrapBB = createBasicBlock("trap");
2018 Builder.CreateCondBr(Checked, Cont, TrapBB);
2019 EmitBlock(TrapBB);
2020 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::trap);
2021 llvm::CallInst *TrapCall = Builder.CreateCall(F);
2022 TrapCall->setDoesNotReturn();
2023 TrapCall->setDoesNotThrow();
2024 Builder.CreateUnreachable();
2025 } else {
2026 Builder.CreateCondBr(Checked, Cont, TrapBB);
2027 }
2028
2029 EmitBlock(Cont);
2030}
2031
Chris Lattner6c5abe82010-06-26 23:03:20 +00002032/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2033/// array to pointer, return the array subexpression.
2034static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2035 // If this isn't just an array->pointer decay, bail out.
2036 const CastExpr *CE = dyn_cast<CastExpr>(E);
John McCalle3027922010-08-25 11:45:40 +00002037 if (CE == 0 || CE->getCastKind() != CK_ArrayToPointerDecay)
Chris Lattner6c5abe82010-06-26 23:03:20 +00002038 return 0;
2039
2040 // If this is a decay from variable width array, bail out.
2041 const Expr *SubExpr = CE->getSubExpr();
2042 if (SubExpr->getType()->isVariableArrayType())
2043 return 0;
2044
2045 return SubExpr;
2046}
2047
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00002048LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Ted Kremenekc81614d2007-08-20 16:18:38 +00002049 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner2da04b32007-08-24 05:35:26 +00002050 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Eli Friedman07bbeca2009-06-06 19:09:26 +00002051 QualType IdxTy = E->getIdx()->getType();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002052 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Eli Friedman07bbeca2009-06-06 19:09:26 +00002053
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002054 // If the base is a vector type, then we are forming a vector element lvalue
2055 // with this subscript.
Eli Friedman327944b2008-06-13 23:01:12 +00002056 if (E->getBase()->getType()->isVectorType()) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002057 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00002058 LValue LHS = EmitLValue(E->getBase());
Ted Kremenekc81614d2007-08-20 16:18:38 +00002059 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
John McCallad7c5c12011-02-08 08:22:06 +00002060 Idx = Builder.CreateIntCast(Idx, Int32Ty, IdxSigned, "vidx");
Eli Friedman327944b2008-06-13 23:01:12 +00002061 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
Eli Friedman610bb872012-03-22 22:36:39 +00002062 E->getBase()->getType(), LHS.getAlignment());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002063 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002064
Ted Kremenekc81614d2007-08-20 16:18:38 +00002065 // Extend or truncate the index type to 32 or 64-bits.
John McCalle3dc1702011-02-15 09:22:45 +00002066 if (Idx->getType() != IntPtrTy)
2067 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
Mike Stumpd9546382009-12-12 01:27:46 +00002068
Mike Stump4a3999f2009-09-09 13:00:44 +00002069 // We know that the pointer points to a type of the correct size, unless the
2070 // size is a VLA or Objective-C interface.
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002071 llvm::Value *Address = 0;
Eli Friedmana0544d62011-12-03 04:14:32 +00002072 CharUnits ArrayAlignment;
John McCall23c29fe2011-06-24 21:55:10 +00002073 if (const VariableArrayType *vla =
Anders Carlsson3d312f82008-12-21 00:11:23 +00002074 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00002075 // The base must be a pointer, which is not an aggregate. Emit
2076 // it. It needs to be emitted first in case it's what captures
2077 // the VLA bounds.
2078 Address = EmitScalarExpr(E->getBase());
Mike Stump4a3999f2009-09-09 13:00:44 +00002079
John McCall23c29fe2011-06-24 21:55:10 +00002080 // The element count here is the total number of non-VLA elements.
2081 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00002082
John McCall77527a82011-06-25 01:32:37 +00002083 // Effectively, the multiply by the VLA size is part of the GEP.
2084 // GEP indexes are signed, and scaling an index isn't permitted to
2085 // signed-overflow, so we use the same semantics for our explicit
2086 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002087 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00002088 Idx = Builder.CreateMul(Idx, numElements);
Chris Lattner2e72da942011-03-01 00:03:48 +00002089 Address = Builder.CreateGEP(Address, Idx, "arrayidx");
John McCall77527a82011-06-25 01:32:37 +00002090 } else {
2091 Idx = Builder.CreateNSWMul(Idx, numElements);
Chris Lattner2e72da942011-03-01 00:03:48 +00002092 Address = Builder.CreateInBoundsGEP(Address, Idx, "arrayidx");
John McCall77527a82011-06-25 01:32:37 +00002093 }
Chris Lattner6c5abe82010-06-26 23:03:20 +00002094 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
2095 // Indexing over an interface, as in "NSString *P; P[4];"
Mike Stump4a3999f2009-09-09 13:00:44 +00002096 llvm::Value *InterfaceSize =
Owen Andersonb7a2fe62009-07-24 23:12:58 +00002097 llvm::ConstantInt::get(Idx->getType(),
Ken Dyck40775002010-01-11 17:06:35 +00002098 getContext().getTypeSizeInChars(OIT).getQuantity());
Mike Stump4a3999f2009-09-09 13:00:44 +00002099
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002100 Idx = Builder.CreateMul(Idx, InterfaceSize);
2101
Chris Lattner6c5abe82010-06-26 23:03:20 +00002102 // The base must be a pointer, which is not an aggregate. Emit it.
2103 llvm::Value *Base = EmitScalarExpr(E->getBase());
John McCallad7c5c12011-02-08 08:22:06 +00002104 Address = EmitCastToVoidPtr(Base);
2105 Address = Builder.CreateGEP(Address, Idx, "arrayidx");
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002106 Address = Builder.CreateBitCast(Address, Base->getType());
Chris Lattner6c5abe82010-06-26 23:03:20 +00002107 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
2108 // If this is A[i] where A is an array, the frontend will have decayed the
2109 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
2110 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
2111 // "gep x, i" here. Emit one "gep A, 0, i".
2112 assert(Array->getType()->isArrayType() &&
2113 "Array to pointer decay must have array source type!");
Daniel Dunbar82634272011-04-01 00:49:43 +00002114 LValue ArrayLV = EmitLValue(Array);
2115 llvm::Value *ArrayPtr = ArrayLV.getAddress();
Chris Lattner6c5abe82010-06-26 23:03:20 +00002116 llvm::Value *Zero = llvm::ConstantInt::get(Int32Ty, 0);
2117 llvm::Value *Args[] = { Zero, Idx };
2118
Daniel Dunbar82634272011-04-01 00:49:43 +00002119 // Propagate the alignment from the array itself to the result.
2120 ArrayAlignment = ArrayLV.getAlignment();
2121
Richard Smith9c6890a2012-11-01 22:30:59 +00002122 if (getLangOpts().isSignedOverflowDefined())
Jay Foad040dd822011-07-22 08:16:57 +00002123 Address = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
Chris Lattner2e72da942011-03-01 00:03:48 +00002124 else
Jay Foad040dd822011-07-22 08:16:57 +00002125 Address = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002126 } else {
Chris Lattner6c5abe82010-06-26 23:03:20 +00002127 // The base must be a pointer, which is not an aggregate. Emit it.
2128 llvm::Value *Base = EmitScalarExpr(E->getBase());
Richard Smith9c6890a2012-11-01 22:30:59 +00002129 if (getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00002130 Address = Builder.CreateGEP(Base, Idx, "arrayidx");
2131 else
2132 Address = Builder.CreateInBoundsGEP(Base, Idx, "arrayidx");
Anders Carlsson3d312f82008-12-21 00:11:23 +00002133 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002134
Steve Naroff7cae42b2009-07-10 23:34:53 +00002135 QualType T = E->getBase()->getType()->getPointeeType();
Mike Stump4a3999f2009-09-09 13:00:44 +00002136 assert(!T.isNull() &&
Steve Naroff7cae42b2009-07-10 23:34:53 +00002137 "CodeGenFunction::EmitArraySubscriptExpr(): Illegal base type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002138
Chris Lattner36bc4f42012-01-04 22:35:55 +00002139
Daniel Dunbar82634272011-04-01 00:49:43 +00002140 // Limit the alignment to that of the result type.
Chris Lattner36bc4f42012-01-04 22:35:55 +00002141 LValue LV;
Eli Friedmana0544d62011-12-03 04:14:32 +00002142 if (!ArrayAlignment.isZero()) {
2143 CharUnits Align = getContext().getTypeAlignInChars(T);
Daniel Dunbar82634272011-04-01 00:49:43 +00002144 ArrayAlignment = std::min(Align, ArrayAlignment);
Chris Lattner36bc4f42012-01-04 22:35:55 +00002145 LV = MakeAddrLValue(Address, T, ArrayAlignment);
2146 } else {
2147 LV = MakeNaturalAlignAddrLValue(Address, T);
Daniel Dunbar82634272011-04-01 00:49:43 +00002148 }
2149
Daniel Dunbarf166a522010-08-21 03:44:13 +00002150 LV.getQuals().setAddressSpace(E->getBase()->getType().getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002151
Richard Smith9c6890a2012-11-01 22:30:59 +00002152 if (getLangOpts().ObjC1 &&
2153 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00002154 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002155 setObjCGCLValueClass(getContext(), E, LV);
2156 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00002157 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00002158}
2159
Mike Stump4a3999f2009-09-09 13:00:44 +00002160static
NAKAMURA Takumiccca11a2012-01-25 08:58:21 +00002161llvm::Constant *GenerateConstantVector(CGBuilderTy &Builder,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002162 SmallVector<unsigned, 4> &Elts) {
2163 SmallVector<llvm::Constant*, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00002164 for (unsigned i = 0, e = Elts.size(); i != e; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002165 CElts.push_back(Builder.getInt32(Elts[i]));
Nate Begemand3862152008-05-13 21:03:02 +00002166
Chris Lattner91c08ad2011-02-15 00:14:06 +00002167 return llvm::ConstantVector::get(CElts);
Nate Begemand3862152008-05-13 21:03:02 +00002168}
2169
Chris Lattner9e751ca2007-08-02 23:37:31 +00002170LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002171EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00002172 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00002173 LValue Base;
2174
2175 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00002176 if (E->isArrow()) {
2177 // If it is a pointer to a vector, emit the address and form an lvalue with
2178 // it.
Chris Lattnerb8211f62009-02-16 22:14:05 +00002179 llvm::Value *Ptr = EmitScalarExpr(E->getBase());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002180 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
Daniel Dunbarf166a522010-08-21 03:44:13 +00002181 Base = MakeAddrLValue(Ptr, PT->getPointeeType());
2182 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00002183 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00002184 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
2185 // emit the base as an lvalue.
2186 assert(E->getBase()->getType()->isVectorType());
2187 Base = EmitLValue(E->getBase());
2188 } else {
2189 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00002190 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00002191 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00002192 llvm::Value *Vec = EmitScalarExpr(E->getBase());
2193
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00002194 // Store the vector to memory (because LValue wants an address).
Daniel Dunbara7566f12010-02-09 02:48:28 +00002195 llvm::Value *VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002196 Builder.CreateStore(Vec, VecMem);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002197 Base = MakeAddrLValue(VecMem, E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002198 }
John McCall1553b192011-06-16 04:16:24 +00002199
2200 QualType type =
2201 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002202
Nate Begemand3862152008-05-13 21:03:02 +00002203 // Encode the element access list into a vector of unsigned indices.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002204 SmallVector<unsigned, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00002205 E->getEncodedElementAccess(Indices);
2206
2207 if (Base.isSimple()) {
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002208 llvm::Constant *CV = GenerateConstantVector(Builder, Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00002209 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
2210 Base.getAlignment());
Nate Begemand3862152008-05-13 21:03:02 +00002211 }
2212 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
2213
2214 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002215 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00002216
Chris Lattner595ba3a2012-01-30 06:20:36 +00002217 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
2218 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00002219 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
Eli Friedman610bb872012-03-22 22:36:39 +00002220 return LValue::MakeExtVectorElt(Base.getExtVectorAddr(), CV, type,
2221 Base.getAlignment());
Chris Lattner9e751ca2007-08-02 23:37:31 +00002222}
2223
Devang Patel30efa2e2007-10-23 20:28:39 +00002224LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00002225 Expr *BaseExpr = E->getBase();
Eli Friedman327944b2008-06-13 23:01:12 +00002226
Chris Lattner4e4186b2007-12-02 18:52:07 +00002227 // 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 +00002228 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00002229 if (E->isArrow()) {
2230 llvm::Value *Ptr = EmitScalarExpr(BaseExpr);
2231 QualType PtrTy = BaseExpr->getType()->getPointeeType();
Richard Smithe30752c2012-10-09 19:52:38 +00002232 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Ptr, PtrTy);
Richard Smith69d0d262012-08-24 00:54:33 +00002233 BaseLV = MakeNaturalAlignAddrLValue(Ptr, PtrTy);
2234 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00002235 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00002236
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002237 NamedDecl *ND = E->getMemberDecl();
2238 if (FieldDecl *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00002239 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002240 setObjCGCLValueClass(getContext(), E, LV);
2241 return LV;
2242 }
2243
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00002244 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
2245 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002246
2247 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
2248 return EmitFunctionDeclLValue(*this, E, FD);
2249
David Blaikie83d382b2011-09-23 05:06:16 +00002250 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00002251}
Devang Patel30efa2e2007-10-23 20:28:39 +00002252
Eli Friedman7f1ff602012-04-16 03:54:45 +00002253LValue CodeGenFunction::EmitLValueForField(LValue base,
2254 const FieldDecl *field) {
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00002255 if (field->isBitField()) {
2256 const CGRecordLayout &RL =
2257 CGM.getTypes().getCGRecordLayout(field->getParent());
2258 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002259 llvm::Value *Addr = base.getAddress();
2260 unsigned Idx = RL.getLLVMFieldNo(field);
2261 if (Idx != 0)
2262 // For structs, we GEP to the field that the record layout suggests.
2263 Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
2264 // Get the access type.
2265 llvm::Type *PtrTy = llvm::Type::getIntNPtrTy(
2266 getLLVMContext(), Info.StorageSize,
2267 CGM.getContext().getTargetAddressSpace(base.getType()));
2268 if (Addr->getType() != PtrTy)
2269 Addr = Builder.CreateBitCast(Addr, PtrTy);
2270
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00002271 QualType fieldType =
2272 field->getType().withCVRQualifiers(base.getVRQualifiers());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002273 return LValue::MakeBitfield(Addr, Info, fieldType, base.getAlignment());
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00002274 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002275
John McCall53fcbd22011-02-26 08:07:02 +00002276 const RecordDecl *rec = field->getParent();
2277 QualType type = field->getType();
Eli Friedmana0544d62011-12-03 04:14:32 +00002278 CharUnits alignment = getContext().getDeclAlign(field);
Eli Friedman133e8042008-05-29 11:33:25 +00002279
Eli Friedman7f1ff602012-04-16 03:54:45 +00002280 // FIXME: It should be impossible to have an LValue without alignment for a
2281 // complete type.
2282 if (!base.getAlignment().isZero())
2283 alignment = std::min(alignment, base.getAlignment());
2284
John McCall53fcbd22011-02-26 08:07:02 +00002285 bool mayAlias = rec->hasAttr<MayAliasAttr>();
2286
Eli Friedman7f1ff602012-04-16 03:54:45 +00002287 llvm::Value *addr = base.getAddress();
2288 unsigned cvr = base.getVRQualifiers();
John McCall53fcbd22011-02-26 08:07:02 +00002289 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00002290 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00002291 assert(!type->isReferenceType() && "union has reference member");
John McCall53fcbd22011-02-26 08:07:02 +00002292 } else {
2293 // For structs, we GEP to the field that the record layout suggests.
2294 unsigned idx = CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
Chris Lattner13ee4f42011-07-10 05:34:54 +00002295 addr = Builder.CreateStructGEP(addr, idx, field->getName());
John McCall53fcbd22011-02-26 08:07:02 +00002296
2297 // If this is a reference field, load the reference right now.
2298 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
2299 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
2300 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
Eli Friedmana0544d62011-12-03 04:14:32 +00002301 load->setAlignment(alignment.getQuantity());
John McCall53fcbd22011-02-26 08:07:02 +00002302
2303 if (CGM.shouldUseTBAA()) {
2304 llvm::MDNode *tbaa;
2305 if (mayAlias)
2306 tbaa = CGM.getTBAAInfo(getContext().CharTy);
2307 else
2308 tbaa = CGM.getTBAAInfo(type);
2309 CGM.DecorateInstruction(load, tbaa);
2310 }
2311
2312 addr = load;
2313 mayAlias = false;
2314 type = refType->getPointeeType();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002315 if (type->isIncompleteType())
Eli Friedmana0544d62011-12-03 04:14:32 +00002316 alignment = CharUnits();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002317 else
Eli Friedmana0544d62011-12-03 04:14:32 +00002318 alignment = getContext().getTypeAlignInChars(type);
John McCall53fcbd22011-02-26 08:07:02 +00002319 cvr = 0; // qualifiers don't recursively apply to referencee
2320 }
Devang Pateled93c3c2007-10-26 19:42:18 +00002321 }
Chris Lattner13ee4f42011-07-10 05:34:54 +00002322
2323 // Make sure that the address is pointing to the right type. This is critical
2324 // for both unions and structs. A union needs a bitcast, a struct element
2325 // will need a bitcast if the LLVM type laid out doesn't match the desired
2326 // type.
Chandler Carruth4678f672011-07-12 08:58:26 +00002327 addr = EmitBitCastOfLValueToProperType(*this, addr,
Chris Lattner3f32d692011-07-12 06:52:18 +00002328 CGM.getTypes().ConvertTypeForMem(type),
2329 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00002330
Julien Lerouge5a6b6982011-09-09 22:41:49 +00002331 if (field->hasAttr<AnnotateAttr>())
2332 addr = EmitFieldAnnotations(field, addr);
2333
John McCall53fcbd22011-02-26 08:07:02 +00002334 LValue LV = MakeAddrLValue(addr, type, alignment);
2335 LV.getQuals().addCVRQualifiers(cvr);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002336
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002337 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00002338 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
2339 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00002340
2341 // Fields of may_alias structs act like 'char' for TBAA purposes.
2342 // FIXME: this should get propagated down through anonymous structs
2343 // and unions.
2344 if (mayAlias && LV.getTBAAInfo())
2345 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
2346
Daniel Dunbarf166a522010-08-21 03:44:13 +00002347 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00002348}
2349
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002350LValue
Eli Friedman7f1ff602012-04-16 03:54:45 +00002351CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
2352 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002353 QualType FieldType = Field->getType();
2354
2355 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00002356 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002357
Daniel Dunbar034299e2010-03-31 01:09:11 +00002358 const CGRecordLayout &RL =
2359 CGM.getTypes().getCGRecordLayout(Field->getParent());
2360 unsigned idx = RL.getLLVMFieldNo(Field);
Eli Friedman7f1ff602012-04-16 03:54:45 +00002361 llvm::Value *V = Builder.CreateStructGEP(Base.getAddress(), idx);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002362 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs");
2363
Chris Lattnerd7c59352011-07-10 05:53:24 +00002364 // Make sure that the address is pointing to the right type. This is critical
2365 // for both unions and structs. A union needs a bitcast, a struct element
2366 // will need a bitcast if the LLVM type laid out doesn't match the desired
2367 // type.
Chris Lattner2192fe52011-07-18 04:24:23 +00002368 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
Eli Friedman7f1ff602012-04-16 03:54:45 +00002369 V = EmitBitCastOfLValueToProperType(*this, V, llvmType, Field->getName());
2370
Eli Friedmana0544d62011-12-03 04:14:32 +00002371 CharUnits Alignment = getContext().getDeclAlign(Field);
Eli Friedman7f1ff602012-04-16 03:54:45 +00002372
2373 // FIXME: It should be impossible to have an LValue without alignment for a
2374 // complete type.
2375 if (!Base.getAlignment().isZero())
2376 Alignment = std::min(Alignment, Base.getAlignment());
2377
Daniel Dunbar5c816372010-08-21 04:20:22 +00002378 return MakeAddrLValue(V, FieldType, Alignment);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00002379}
2380
Chris Lattnerf53c0962010-09-06 00:11:41 +00002381LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00002382 if (E->isFileScope()) {
2383 llvm::Value *GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
2384 return MakeAddrLValue(GlobalPtr, E->getType());
2385 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00002386 if (E->getType()->isVariablyModifiedType())
2387 // make sure to emit the VLA size.
2388 EmitVariablyModifiedType(E->getType());
Fariborz Jahanianbbc5bbf2012-06-07 17:07:15 +00002389
Daniel Dunbar27bacaf2010-02-16 19:43:39 +00002390 llvm::Value *DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00002391 const Expr *InitExpr = E->getInitializer();
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002392 LValue Result = MakeAddrLValue(DeclPtr, E->getType());
Eli Friedman9fd8b682008-05-13 23:18:27 +00002393
Chad Rosier615ed1a2012-03-29 17:37:10 +00002394 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
2395 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00002396
2397 return Result;
2398}
2399
Richard Smithbb653bd2012-05-14 21:57:21 +00002400LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
2401 if (!E->isGLValue())
2402 // Initializing an aggregate temporary in C++11: T{...}.
2403 return EmitAggExprToLValue(E);
2404
2405 // An lvalue initializer list must be initializing a reference.
2406 assert(E->getNumInits() == 1 && "reference init with multiple values");
2407 return EmitLValue(E->getInit(0));
2408}
2409
John McCallc07a0c72011-02-17 10:25:35 +00002410LValue CodeGenFunction::
2411EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
2412 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00002413 // ?: here should be an aggregate.
John McCallc07a0c72011-02-17 10:25:35 +00002414 assert((hasAggregateLLVMType(expr->getType()) &&
2415 !expr->getType()->isAnyComplexType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00002416 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00002417 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00002418 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00002419
Eli Friedman59954892012-01-25 05:04:17 +00002420 OpaqueValueMapping binding(*this, expr);
2421
John McCallc07a0c72011-02-17 10:25:35 +00002422 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00002423 bool CondExprBool;
2424 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00002425 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00002426 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00002427
2428 if (!ContainsLabel(dead))
2429 return EmitLValue(live);
John McCall0a6bf2e2011-01-26 19:21:13 +00002430 }
2431
John McCallc07a0c72011-02-17 10:25:35 +00002432 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
2433 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
2434 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00002435
2436 ConditionalEvaluation eval(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002437 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002438
2439 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00002440 EmitBlock(lhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002441 eval.begin(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002442 LValue lhs = EmitLValue(expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00002443 eval.end(*this);
2444
John McCallc07a0c72011-02-17 10:25:35 +00002445 if (!lhs.isSimple())
2446 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00002447
John McCallc07a0c72011-02-17 10:25:35 +00002448 lhsBlock = Builder.GetInsertBlock();
2449 Builder.CreateBr(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002450
2451 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00002452 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002453 eval.begin(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002454 LValue rhs = EmitLValue(expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00002455 eval.end(*this);
John McCallc07a0c72011-02-17 10:25:35 +00002456 if (!rhs.isSimple())
2457 return EmitUnsupportedLValue(expr, "conditional operator");
2458 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00002459
John McCallc07a0c72011-02-17 10:25:35 +00002460 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00002461
Jay Foad20c0f022011-03-30 11:28:58 +00002462 llvm::PHINode *phi = Builder.CreatePHI(lhs.getAddress()->getType(), 2,
John McCall0a6bf2e2011-01-26 19:21:13 +00002463 "cond-lvalue");
John McCallc07a0c72011-02-17 10:25:35 +00002464 phi->addIncoming(lhs.getAddress(), lhsBlock);
2465 phi->addIncoming(rhs.getAddress(), rhsBlock);
2466 return MakeAddrLValue(phi, expr->getType());
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00002467}
2468
Richard Smithbb653bd2012-05-14 21:57:21 +00002469/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
2470/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00002471/// otherwise if a cast is needed by the code generator in an lvalue context,
2472/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00002473/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00002474/// are permitted with aggregate result, including noop aggregate casts, and
2475/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00002476LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00002477 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00002478 case CK_ToVoid:
Eli Friedman8c98dff2009-11-16 05:48:01 +00002479 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
John McCall8cb679e2010-11-15 09:13:47 +00002480
2481 case CK_Dependent:
2482 llvm_unreachable("dependent cast kind in IR gen!");
Eli Friedman34866c72012-08-31 00:14:07 +00002483
2484 case CK_BuiltinFnToFnPtr:
2485 llvm_unreachable("builtin functions are handled elsewhere");
2486
David Chisnallfa35df62012-01-16 17:27:18 +00002487 // These two casts are currently treated as no-ops, although they could
2488 // potentially be real operations depending on the target's ABI.
2489 case CK_NonAtomicToAtomic:
2490 case CK_AtomicToNonAtomic:
John McCall8cb679e2010-11-15 09:13:47 +00002491
John McCalle3027922010-08-25 11:45:40 +00002492 case CK_NoOp:
Douglas Gregor21d3fca2011-01-27 23:22:05 +00002493 case CK_LValueToRValue:
2494 if (!E->getSubExpr()->Classify(getContext()).isPRValue()
2495 || E->getType()->isRecordType())
John McCalle26a8722010-12-04 08:14:53 +00002496 return EmitLValue(E->getSubExpr());
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002497 // Fall through to synthesize a temporary.
John McCall8cb679e2010-11-15 09:13:47 +00002498
John McCalle3027922010-08-25 11:45:40 +00002499 case CK_BitCast:
2500 case CK_ArrayToPointerDecay:
2501 case CK_FunctionToPointerDecay:
2502 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00002503 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00002504 case CK_IntegralToPointer:
2505 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00002506 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00002507 case CK_VectorSplat:
2508 case CK_IntegralCast:
John McCall8cb679e2010-11-15 09:13:47 +00002509 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00002510 case CK_IntegralToFloating:
2511 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00002512 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00002513 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00002514 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00002515 case CK_FloatingComplexToReal:
2516 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00002517 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00002518 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00002519 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00002520 case CK_IntegralComplexToReal:
2521 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00002522 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00002523 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00002524 case CK_DerivedToBaseMemberPointer:
2525 case CK_BaseToDerivedMemberPointer:
2526 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00002527 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00002528 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00002529 case CK_ARCProduceObject:
2530 case CK_ARCConsumeObject:
2531 case CK_ARCReclaimReturnedObject:
Douglas Gregored90df32012-02-22 05:02:47 +00002532 case CK_ARCExtendBlockObject:
2533 case CK_CopyAndAutoreleaseBlockObject: {
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002534 // These casts only produce lvalues when we're binding a reference to a
2535 // temporary realized from a (converted) pure rvalue. Emit the expression
2536 // as a value, copy it into a temporary, and return an lvalue referring to
2537 // that temporary.
2538 llvm::Value *V = CreateMemTemp(E->getType(), "ref.temp");
Chad Rosier615ed1a2012-03-29 17:37:10 +00002539 EmitAnyExprToMem(E, V, E->getType().getQualifiers(), false);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002540 return MakeAddrLValue(V, E->getType());
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002541 }
Eli Friedman8c98dff2009-11-16 05:48:01 +00002542
Anders Carlsson8a01a752011-04-11 02:03:26 +00002543 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00002544 LValue LV = EmitLValue(E->getSubExpr());
2545 llvm::Value *V = LV.getAddress();
2546 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(E);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002547 return MakeAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00002548 }
2549
John McCalle3027922010-08-25 11:45:40 +00002550 case CK_ConstructorConversion:
2551 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00002552 case CK_CPointerToObjCPointerCast:
2553 case CK_BlockPointerToObjCPointerCast:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00002554 return EmitLValue(E->getSubExpr());
Anders Carlssond95f9602009-09-12 16:16:49 +00002555
John McCalle3027922010-08-25 11:45:40 +00002556 case CK_UncheckedDerivedToBase:
2557 case CK_DerivedToBase: {
Anders Carlssond95f9602009-09-12 16:16:49 +00002558 const RecordType *DerivedClassTy =
2559 E->getSubExpr()->getType()->getAs<RecordType>();
2560 CXXRecordDecl *DerivedClassDecl =
2561 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Anders Carlssond95f9602009-09-12 16:16:49 +00002562
2563 LValue LV = EmitLValue(E->getSubExpr());
John McCalle26a8722010-12-04 08:14:53 +00002564 llvm::Value *This = LV.getAddress();
Anders Carlssond95f9602009-09-12 16:16:49 +00002565
2566 // Perform the derived-to-base conversion
2567 llvm::Value *Base =
Fariborz Jahanian64cda8b2010-06-17 23:00:29 +00002568 GetAddressOfBaseClass(This, DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00002569 E->path_begin(), E->path_end(),
2570 /*NullCheckValue=*/false);
Anders Carlssond95f9602009-09-12 16:16:49 +00002571
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002572 return MakeAddrLValue(Base, E->getType());
Anders Carlssond95f9602009-09-12 16:16:49 +00002573 }
John McCalle3027922010-08-25 11:45:40 +00002574 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00002575 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00002576 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00002577 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
2578 CXXRecordDecl *DerivedClassDecl =
2579 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
2580
2581 LValue LV = EmitLValue(E->getSubExpr());
2582
2583 // Perform the base-to-derived conversion
2584 llvm::Value *Derived =
Anders Carlsson8a64c1c2010-04-24 21:23:59 +00002585 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00002586 E->path_begin(), E->path_end(),
2587 /*NullCheckValue=*/false);
Anders Carlsson8c793172009-11-23 17:57:54 +00002588
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002589 return MakeAddrLValue(Derived, E->getType());
Eli Friedman8c98dff2009-11-16 05:48:01 +00002590 }
John McCalle3027922010-08-25 11:45:40 +00002591 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00002592 // This must be a reinterpret_cast (or c-style equivalent).
2593 const ExplicitCastExpr *CE = cast<ExplicitCastExpr>(E);
Anders Carlsson50cb3212009-11-14 21:21:42 +00002594
2595 LValue LV = EmitLValue(E->getSubExpr());
2596 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2597 ConvertType(CE->getTypeAsWritten()));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002598 return MakeAddrLValue(V, E->getType());
Anders Carlsson50cb3212009-11-14 21:21:42 +00002599 }
John McCalle3027922010-08-25 11:45:40 +00002600 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002601 LValue LV = EmitLValue(E->getSubExpr());
2602 QualType ToType = getContext().getLValueReferenceType(E->getType());
2603 llvm::Value *V = Builder.CreateBitCast(LV.getAddress(),
2604 ConvertType(ToType));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002605 return MakeAddrLValue(V, E->getType());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002606 }
Anders Carlssond95f9602009-09-12 16:16:49 +00002607 }
Douglas Gregorcdb466e2010-07-15 18:58:16 +00002608
2609 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00002610}
2611
Fariborz Jahaniane4d94ce2009-10-20 23:29:04 +00002612LValue CodeGenFunction::EmitNullInitializationLValue(
Douglas Gregor747eb782010-07-08 06:14:04 +00002613 const CXXScalarValueInitExpr *E) {
Fariborz Jahaniane4d94ce2009-10-20 23:29:04 +00002614 QualType Ty = E->getType();
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002615 LValue LV = MakeAddrLValue(CreateMemTemp(Ty), Ty);
Anders Carlssonc0964b62010-05-22 17:35:42 +00002616 EmitNullInitialization(LV.getAddress(), Ty);
Daniel Dunbara7566f12010-02-09 02:48:28 +00002617 return LV;
Fariborz Jahaniane4d94ce2009-10-20 23:29:04 +00002618}
2619
John McCall1bf58462011-02-16 08:02:54 +00002620LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00002621 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00002622 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00002623}
2624
Douglas Gregorfe314812011-06-21 17:03:29 +00002625LValue CodeGenFunction::EmitMaterializeTemporaryExpr(
2626 const MaterializeTemporaryExpr *E) {
John McCall17054bd62011-08-26 21:08:13 +00002627 RValue RV = EmitReferenceBindingToExpr(E, /*InitializedDecl=*/0);
Douglas Gregord410c082011-06-21 18:20:46 +00002628 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Douglas Gregorfe314812011-06-21 17:03:29 +00002629}
2630
Eli Friedman7f1ff602012-04-16 03:54:45 +00002631RValue CodeGenFunction::EmitRValueForField(LValue LV,
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002632 const FieldDecl *FD) {
2633 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00002634 LValue FieldLV = EmitLValueForField(LV, FD);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002635 if (FT->isAnyComplexType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00002636 return RValue::getComplex(
2637 LoadComplexFromAddr(FieldLV.getAddress(),
2638 FieldLV.isVolatileQualified()));
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002639 else if (CodeGenFunction::hasAggregateLLVMType(FT))
Eli Friedman7f1ff602012-04-16 03:54:45 +00002640 return FieldLV.asAggregateRValue();
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002641
Eli Friedman7f1ff602012-04-16 03:54:45 +00002642 return EmitLoadOfLValue(FieldLV);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00002643}
Douglas Gregorfe314812011-06-21 17:03:29 +00002644
Chris Lattnere47e4402007-06-01 18:02:12 +00002645//===--------------------------------------------------------------------===//
2646// Expression Emission
2647//===--------------------------------------------------------------------===//
2648
Anders Carlsson17490832009-12-24 20:40:36 +00002649RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
2650 ReturnValueSlot ReturnValue) {
Eric Christopher7cdf9482011-10-13 21:45:18 +00002651 if (CGDebugInfo *DI = getDebugInfo())
2652 DI->EmitLocation(Builder, E->getLocStart());
Devang Pateld3a6b0f2011-03-04 18:54:42 +00002653
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002654 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00002655 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00002656 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00002657
Anders Carlssone5fd6f22009-04-03 22:50:24 +00002658 if (const CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00002659 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00002660
Peter Collingbournefe883422011-10-06 18:29:37 +00002661 if (const CUDAKernelCallExpr *CE = dyn_cast<CUDAKernelCallExpr>(E))
2662 return EmitCUDAKernelCallExpr(CE, ReturnValue);
2663
Douglas Gregore0e96302011-09-06 21:41:04 +00002664 const Decl *TargetDecl = E->getCalleeDecl();
2665 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
2666 if (unsigned builtinID = FD->getBuiltinID())
2667 return EmitBuiltinExpr(FD, builtinID, E);
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00002668 }
2669
Chris Lattner4ca97c32009-06-13 00:26:38 +00002670 if (const CXXOperatorCallExpr *CE = dyn_cast<CXXOperatorCallExpr>(E))
Anders Carlsson4034a952009-05-27 04:18:27 +00002671 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
Anders Carlssonbfb36712009-12-24 21:13:40 +00002672 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00002673
John McCall31168b02011-06-15 23:02:42 +00002674 if (const CXXPseudoDestructorExpr *PseudoDtor
2675 = dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
2676 QualType DestroyedType = PseudoDtor->getDestroyedType();
Richard Smith9c6890a2012-11-01 22:30:59 +00002677 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002678 DestroyedType->isObjCLifetimeType() &&
2679 (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong ||
2680 DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) {
Benjamin Kramerdd19c012011-06-18 10:34:00 +00002681 // Automatic Reference Counting:
2682 // If the pseudo-expression names a retainable object with weak or
2683 // strong lifetime, the object shall be released.
John McCall31168b02011-06-15 23:02:42 +00002684 Expr *BaseExpr = PseudoDtor->getBase();
2685 llvm::Value *BaseValue = NULL;
2686 Qualifiers BaseQuals;
2687
Benjamin Kramerdd19c012011-06-18 10:34:00 +00002688 // 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 +00002689 if (PseudoDtor->isArrow()) {
2690 BaseValue = EmitScalarExpr(BaseExpr);
2691 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
2692 BaseQuals = PTy->getPointeeType().getQualifiers();
2693 } else {
2694 LValue BaseLV = EmitLValue(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00002695 BaseValue = BaseLV.getAddress();
2696 QualType BaseTy = BaseExpr->getType();
2697 BaseQuals = BaseTy.getQualifiers();
2698 }
2699
2700 switch (PseudoDtor->getDestroyedType().getObjCLifetime()) {
2701 case Qualifiers::OCL_None:
2702 case Qualifiers::OCL_ExplicitNone:
2703 case Qualifiers::OCL_Autoreleasing:
2704 break;
2705
2706 case Qualifiers::OCL_Strong:
2707 EmitARCRelease(Builder.CreateLoad(BaseValue,
Benjamin Kramerdd19c012011-06-18 10:34:00 +00002708 PseudoDtor->getDestroyedType().isVolatileQualified()),
John McCall31168b02011-06-15 23:02:42 +00002709 /*precise*/ true);
2710 break;
2711
2712 case Qualifiers::OCL_Weak:
2713 EmitARCDestroyWeak(BaseValue);
2714 break;
2715 }
2716 } else {
2717 // C++ [expr.pseudo]p1:
2718 // The result shall only be used as the operand for the function call
2719 // operator (), and the result of such a call has type void. The only
2720 // effect is the evaluation of the postfix-expression before the dot or
2721 // arrow.
2722 EmitScalarExpr(E->getCallee());
2723 }
2724
Douglas Gregorad8a3362009-09-04 17:36:40 +00002725 return RValue::get(0);
2726 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002727
Chris Lattner2da04b32007-08-24 05:35:26 +00002728 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Anders Carlsson17490832009-12-24 20:40:36 +00002729 return EmitCall(E->getCallee()->getType(), Callee, ReturnValue,
Anders Carlsson3a9463b2009-05-27 01:22:39 +00002730 E->arg_begin(), E->arg_end(), TargetDecl);
Chris Lattner9e47ead2007-08-31 04:44:06 +00002731}
2732
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00002733LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00002734 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00002735 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00002736 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00002737 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00002738 return EmitLValue(E->getRHS());
2739 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002740
John McCalle3027922010-08-25 11:45:40 +00002741 if (E->getOpcode() == BO_PtrMemD ||
2742 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00002743 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00002744
John McCalla2342eb2010-12-05 02:00:02 +00002745 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00002746
2747 // Note that in all of these cases, __block variables need the RHS
2748 // evaluated first just in case the variable gets moved by the RHS.
John McCall4f29b492010-11-16 23:07:28 +00002749
Anders Carlsson0999aaf2009-10-19 18:28:22 +00002750 if (!hasAggregateLLVMType(E->getType())) {
John McCall31168b02011-06-15 23:02:42 +00002751 switch (E->getLHS()->getType().getObjCLifetime()) {
2752 case Qualifiers::OCL_Strong:
2753 return EmitARCStoreStrong(E, /*ignored*/ false).first;
2754
2755 case Qualifiers::OCL_Autoreleasing:
2756 return EmitARCStoreAutoreleasing(E).first;
2757
2758 // No reason to do any of these differently.
2759 case Qualifiers::OCL_None:
2760 case Qualifiers::OCL_ExplicitNone:
2761 case Qualifiers::OCL_Weak:
2762 break;
2763 }
2764
John McCalld0a30012010-12-06 06:10:02 +00002765 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00002766 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
John McCall55e1fbc2011-06-25 02:11:03 +00002767 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00002768 return LV;
2769 }
John McCall4f29b492010-11-16 23:07:28 +00002770
2771 if (E->getType()->isAnyComplexType())
2772 return EmitComplexAssignmentLValue(E);
2773
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00002774 return EmitAggExprToLValue(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00002775}
2776
Christopher Lambd91c3d42007-12-29 05:02:41 +00002777LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00002778 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00002779
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002780 if (!RV.isScalar())
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002781 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002782
2783 assert(E->getCallReturnType()->isReferenceType() &&
2784 "Can't have a scalar return unless the return type is a "
2785 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00002786
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002787 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00002788}
2789
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00002790LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
2791 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00002792 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00002793}
2794
Anders Carlsson3be22e22009-05-30 23:23:33 +00002795LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00002796 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
2797 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002798 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00002799 EmitCXXConstructExpr(E, Slot);
2800 return MakeAddrLValue(Slot.getAddr(), E->getType());
Anders Carlsson3be22e22009-05-30 23:23:33 +00002801}
2802
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00002803LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00002804CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002805 return MakeAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00002806}
2807
Nico Webercf4ff5862012-10-11 10:13:44 +00002808llvm::Value *CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
2809 return CGM.GetAddrOfUuidDescriptor(E);
2810}
2811
2812LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
2813 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType());
2814}
2815
Mike Stumpc9b231c2009-11-15 08:09:41 +00002816LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00002817CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00002818 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00002819 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00002820 EmitAggExpr(E->getSubExpr(), Slot);
Peter Collingbourne702b2842011-11-27 22:09:22 +00002821 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddr());
John McCall8ea46b62010-09-18 00:58:34 +00002822 return MakeAddrLValue(Slot.getAddr(), E->getType());
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00002823}
2824
Eli Friedman5bc17122012-02-08 05:34:55 +00002825LValue
2826CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00002827 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00002828 EmitLambdaExpr(E, Slot);
Eli Friedman5bc17122012-02-08 05:34:55 +00002829 return MakeAddrLValue(Slot.getAddr(), E->getType());
2830}
2831
Daniel Dunbarc8317a42008-08-23 10:51:21 +00002832LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00002833 RValue RV = EmitObjCMessageExpr(E);
Anders Carlsson280e61f12010-06-21 20:59:55 +00002834
2835 if (!RV.isScalar())
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002836 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Anders Carlsson280e61f12010-06-21 20:59:55 +00002837
2838 assert(E->getMethodDecl()->getResultType()->isReferenceType() &&
2839 "Can't have a scalar return unless the return type is a "
2840 "reference type!");
2841
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002842 return MakeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00002843}
2844
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00002845LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
2846 llvm::Value *V =
2847 CGM.getObjCRuntime().GetSelector(Builder, E->getSelector(), true);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002848 return MakeAddrLValue(V, E->getType());
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00002849}
2850
Daniel Dunbar722f4242009-04-22 05:08:15 +00002851llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002852 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00002853 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002854}
2855
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00002856LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
2857 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002858 const ObjCIvarDecl *Ivar,
2859 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00002860 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00002861 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002862}
2863
2864LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00002865 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
2866 llvm::Value *BaseValue = 0;
2867 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00002868 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00002869 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00002870 if (E->isArrow()) {
2871 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002872 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00002873 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00002874 } else {
2875 LValue BaseLV = EmitLValue(BaseExpr);
2876 // FIXME: this isn't right for bitfields.
2877 BaseValue = BaseLV.getAddress();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00002878 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00002879 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00002880 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00002881
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002882 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00002883 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
2884 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002885 setObjCGCLValueClass(getContext(), E, LV);
2886 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00002887}
2888
Chris Lattnera4185c52009-04-25 19:35:26 +00002889LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00002890 // Can only get l-value for message expression returning aggregate type
2891 RValue RV = EmitAnyExprToTemp(E);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00002892 return MakeAddrLValue(RV.getAggregateAddr(), E->getType());
Chris Lattnera4185c52009-04-25 19:35:26 +00002893}
2894
Anders Carlsson0435ed52009-12-24 19:08:58 +00002895RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
Anders Carlsson17490832009-12-24 20:40:36 +00002896 ReturnValueSlot ReturnValue,
Anders Carlsson3a9463b2009-05-27 01:22:39 +00002897 CallExpr::const_arg_iterator ArgBeg,
2898 CallExpr::const_arg_iterator ArgEnd,
2899 const Decl *TargetDecl) {
Mike Stump4a3999f2009-09-09 13:00:44 +00002900 // Get the actual function type. The callee type will always be a pointer to
2901 // function type or a block pointer type.
2902 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00002903 "Call must have function pointer type!");
2904
John McCall6fd4c232009-10-23 08:22:42 +00002905 CalleeType = getContext().getCanonicalType(CalleeType);
2906
John McCallab26cfa2010-02-05 21:31:56 +00002907 const FunctionType *FnType
2908 = cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00002909
2910 CallArgList Args;
John McCall6fd4c232009-10-23 08:22:42 +00002911 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), ArgBeg, ArgEnd);
Daniel Dunbarc722b852008-08-30 03:02:31 +00002912
John McCalla729c622012-02-17 03:33:10 +00002913 const CGFunctionInfo &FnInfo =
John McCall8dda7b22012-07-07 06:41:13 +00002914 CGM.getTypes().arrangeFreeFunctionCall(Args, FnType);
John McCallcbc038a2011-09-21 08:08:30 +00002915
2916 // C99 6.5.2.2p6:
2917 // If the expression that denotes the called function has a type
2918 // that does not include a prototype, [the default argument
2919 // promotions are performed]. If the number of arguments does not
2920 // equal the number of parameters, the behavior is undefined. If
2921 // the function is defined with a type that includes a prototype,
2922 // and either the prototype ends with an ellipsis (, ...) or the
2923 // types of the arguments after promotion are not compatible with
2924 // the types of the parameters, the behavior is undefined. If the
2925 // function is defined with a type that does not include a
2926 // prototype, and the types of the arguments after promotion are
2927 // not compatible with those of the parameters after promotion,
2928 // the behavior is undefined [except in some trivial cases].
2929 // That is, in the general case, we should assume that a call
2930 // through an unprototyped function type works like a *non-variadic*
2931 // call. The way we make this work is to cast to the exact type
2932 // of the promoted arguments.
John McCalla729c622012-02-17 03:33:10 +00002933 if (isa<FunctionNoProtoType>(FnType) && !FnInfo.isVariadic()) {
2934 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00002935 CalleeTy = CalleeTy->getPointerTo();
2936 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
2937 }
2938
2939 return EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00002940}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00002941
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002942LValue CodeGenFunction::
2943EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
Eli Friedman928a5672009-11-18 05:01:17 +00002944 llvm::Value *BaseV;
John McCalle3027922010-08-25 11:45:40 +00002945 if (E->getOpcode() == BO_PtrMemI)
Eli Friedman928a5672009-11-18 05:01:17 +00002946 BaseV = EmitScalarExpr(E->getLHS());
2947 else
2948 BaseV = EmitLValue(E->getLHS()).getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002949
John McCallc134eb52010-08-31 21:07:20 +00002950 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
2951
2952 const MemberPointerType *MPT
2953 = E->getRHS()->getType()->getAs<MemberPointerType>();
2954
2955 llvm::Value *AddV =
2956 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, BaseV, OffsetV, MPT);
2957
2958 return MakeAddrLValue(AddV, MPT->getPointeeType());
Fariborz Jahanianffba6622009-10-22 22:57:31 +00002959}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002960
2961static void
2962EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, llvm::Value *Dest,
2963 llvm::Value *Ptr, llvm::Value *Val1, llvm::Value *Val2,
2964 uint64_t Size, unsigned Align, llvm::AtomicOrdering Order) {
Richard Smithfeea8832012-04-12 05:08:17 +00002965 llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add;
2966 llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
2967
2968 switch (E->getOp()) {
2969 case AtomicExpr::AO__c11_atomic_init:
2970 llvm_unreachable("Already handled!");
2971
2972 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2973 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2974 case AtomicExpr::AO__atomic_compare_exchange:
2975 case AtomicExpr::AO__atomic_compare_exchange_n: {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002976 // Note that cmpxchg only supports specifying one ordering and
2977 // doesn't support weak cmpxchg, at least at the moment.
2978 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
2979 LoadVal1->setAlignment(Align);
2980 llvm::LoadInst *LoadVal2 = CGF.Builder.CreateLoad(Val2);
2981 LoadVal2->setAlignment(Align);
2982 llvm::AtomicCmpXchgInst *CXI =
2983 CGF.Builder.CreateAtomicCmpXchg(Ptr, LoadVal1, LoadVal2, Order);
2984 CXI->setVolatile(E->isVolatile());
2985 llvm::StoreInst *StoreVal1 = CGF.Builder.CreateStore(CXI, Val1);
2986 StoreVal1->setAlignment(Align);
2987 llvm::Value *Cmp = CGF.Builder.CreateICmpEQ(CXI, LoadVal1);
2988 CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType()));
2989 return;
2990 }
2991
Richard Smithfeea8832012-04-12 05:08:17 +00002992 case AtomicExpr::AO__c11_atomic_load:
2993 case AtomicExpr::AO__atomic_load_n:
2994 case AtomicExpr::AO__atomic_load: {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002995 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
2996 Load->setAtomic(Order);
2997 Load->setAlignment(Size);
2998 Load->setVolatile(E->isVolatile());
2999 llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Load, Dest);
3000 StoreDest->setAlignment(Align);
3001 return;
3002 }
3003
Richard Smithfeea8832012-04-12 05:08:17 +00003004 case AtomicExpr::AO__c11_atomic_store:
3005 case AtomicExpr::AO__atomic_store:
3006 case AtomicExpr::AO__atomic_store_n: {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003007 assert(!Dest && "Store does not return a value");
3008 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
3009 LoadVal1->setAlignment(Align);
3010 llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr);
3011 Store->setAtomic(Order);
3012 Store->setAlignment(Size);
3013 Store->setVolatile(E->isVolatile());
3014 return;
3015 }
3016
Richard Smithfeea8832012-04-12 05:08:17 +00003017 case AtomicExpr::AO__c11_atomic_exchange:
3018 case AtomicExpr::AO__atomic_exchange_n:
3019 case AtomicExpr::AO__atomic_exchange:
3020 Op = llvm::AtomicRMWInst::Xchg;
3021 break;
3022
3023 case AtomicExpr::AO__atomic_add_fetch:
3024 PostOp = llvm::Instruction::Add;
3025 // Fall through.
3026 case AtomicExpr::AO__c11_atomic_fetch_add:
3027 case AtomicExpr::AO__atomic_fetch_add:
3028 Op = llvm::AtomicRMWInst::Add;
3029 break;
3030
3031 case AtomicExpr::AO__atomic_sub_fetch:
3032 PostOp = llvm::Instruction::Sub;
3033 // Fall through.
3034 case AtomicExpr::AO__c11_atomic_fetch_sub:
3035 case AtomicExpr::AO__atomic_fetch_sub:
3036 Op = llvm::AtomicRMWInst::Sub;
3037 break;
3038
3039 case AtomicExpr::AO__atomic_and_fetch:
3040 PostOp = llvm::Instruction::And;
3041 // Fall through.
3042 case AtomicExpr::AO__c11_atomic_fetch_and:
3043 case AtomicExpr::AO__atomic_fetch_and:
3044 Op = llvm::AtomicRMWInst::And;
3045 break;
3046
3047 case AtomicExpr::AO__atomic_or_fetch:
3048 PostOp = llvm::Instruction::Or;
3049 // Fall through.
3050 case AtomicExpr::AO__c11_atomic_fetch_or:
3051 case AtomicExpr::AO__atomic_fetch_or:
3052 Op = llvm::AtomicRMWInst::Or;
3053 break;
3054
3055 case AtomicExpr::AO__atomic_xor_fetch:
3056 PostOp = llvm::Instruction::Xor;
3057 // Fall through.
3058 case AtomicExpr::AO__c11_atomic_fetch_xor:
3059 case AtomicExpr::AO__atomic_fetch_xor:
3060 Op = llvm::AtomicRMWInst::Xor;
3061 break;
Richard Smithd65cee92012-04-13 06:31:38 +00003062
3063 case AtomicExpr::AO__atomic_nand_fetch:
3064 PostOp = llvm::Instruction::And;
3065 // Fall through.
3066 case AtomicExpr::AO__atomic_fetch_nand:
3067 Op = llvm::AtomicRMWInst::Nand;
3068 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003069 }
Richard Smithfeea8832012-04-12 05:08:17 +00003070
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003071 llvm::LoadInst *LoadVal1 = CGF.Builder.CreateLoad(Val1);
3072 LoadVal1->setAlignment(Align);
3073 llvm::AtomicRMWInst *RMWI =
3074 CGF.Builder.CreateAtomicRMW(Op, Ptr, LoadVal1, Order);
3075 RMWI->setVolatile(E->isVolatile());
Richard Smithfeea8832012-04-12 05:08:17 +00003076
3077 // For __atomic_*_fetch operations, perform the operation again to
3078 // determine the value which was written.
3079 llvm::Value *Result = RMWI;
3080 if (PostOp)
3081 Result = CGF.Builder.CreateBinOp(PostOp, RMWI, LoadVal1);
Richard Smithd65cee92012-04-13 06:31:38 +00003082 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
3083 Result = CGF.Builder.CreateNot(Result);
Richard Smithfeea8832012-04-12 05:08:17 +00003084 llvm::StoreInst *StoreDest = CGF.Builder.CreateStore(Result, Dest);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003085 StoreDest->setAlignment(Align);
3086}
3087
3088// This function emits any expression (scalar, complex, or aggregate)
3089// into a temporary alloca.
3090static llvm::Value *
3091EmitValToTemp(CodeGenFunction &CGF, Expr *E) {
3092 llvm::Value *DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp");
Chad Rosier615ed1a2012-03-29 17:37:10 +00003093 CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(),
3094 /*Init*/ true);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003095 return DeclPtr;
3096}
3097
3098static RValue ConvertTempToRValue(CodeGenFunction &CGF, QualType Ty,
3099 llvm::Value *Dest) {
3100 if (Ty->isAnyComplexType())
3101 return RValue::getComplex(CGF.LoadComplexFromAddr(Dest, false));
3102 if (CGF.hasAggregateLLVMType(Ty))
3103 return RValue::getAggregate(Dest);
3104 return RValue::get(CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(Dest, Ty)));
3105}
3106
3107RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest) {
3108 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
Richard Smithfeea8832012-04-12 05:08:17 +00003109 QualType MemTy = AtomicTy;
3110 if (const AtomicType *AT = AtomicTy->getAs<AtomicType>())
3111 MemTy = AT->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003112 CharUnits sizeChars = getContext().getTypeSizeInChars(AtomicTy);
3113 uint64_t Size = sizeChars.getQuantity();
3114 CharUnits alignChars = getContext().getTypeAlignInChars(AtomicTy);
3115 unsigned Align = alignChars.getQuantity();
Benjamin Kramer37196de2012-11-17 17:30:55 +00003116 unsigned MaxInlineWidthInBits =
3117 getContext().getTargetInfo().getMaxAtomicInlineWidth();
3118 bool UseLibcall = (Size != Align ||
3119 getContext().toBits(sizeChars) > MaxInlineWidthInBits);
David Chisnallfa35df62012-01-16 17:27:18 +00003120
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003121 llvm::Value *Ptr, *Order, *OrderFail = 0, *Val1 = 0, *Val2 = 0;
3122 Ptr = EmitScalarExpr(E->getPtr());
David Chisnallfa35df62012-01-16 17:27:18 +00003123
Richard Smithfeea8832012-04-12 05:08:17 +00003124 if (E->getOp() == AtomicExpr::AO__c11_atomic_init) {
David Chisnallfa35df62012-01-16 17:27:18 +00003125 assert(!Dest && "Init does not return a value");
David Chisnalleb9496e2012-04-11 17:24:05 +00003126 if (!hasAggregateLLVMType(E->getVal1()->getType())) {
Douglas Gregor298f43d2012-04-12 20:42:30 +00003127 QualType PointeeType
3128 = E->getPtr()->getType()->getAs<PointerType>()->getPointeeType();
3129 EmitScalarInit(EmitScalarExpr(E->getVal1()),
3130 LValue::MakeAddr(Ptr, PointeeType, alignChars,
3131 getContext()));
David Chisnalleb9496e2012-04-11 17:24:05 +00003132 } else if (E->getType()->isAnyComplexType()) {
3133 EmitComplexExprIntoAddr(E->getVal1(), Ptr, E->isVolatile());
3134 } else {
3135 AggValueSlot Slot = AggValueSlot::forAddr(Ptr, alignChars,
3136 AtomicTy.getQualifiers(),
3137 AggValueSlot::IsNotDestructed,
3138 AggValueSlot::DoesNotNeedGCBarriers,
3139 AggValueSlot::IsNotAliased);
3140 EmitAggExpr(E->getVal1(), Slot);
3141 }
David Chisnallfa35df62012-01-16 17:27:18 +00003142 return RValue::get(0);
3143 }
3144
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003145 Order = EmitScalarExpr(E->getOrder());
Richard Smithfeea8832012-04-12 05:08:17 +00003146
3147 switch (E->getOp()) {
3148 case AtomicExpr::AO__c11_atomic_init:
3149 llvm_unreachable("Already handled!");
3150
3151 case AtomicExpr::AO__c11_atomic_load:
3152 case AtomicExpr::AO__atomic_load_n:
3153 break;
3154
3155 case AtomicExpr::AO__atomic_load:
3156 Dest = EmitScalarExpr(E->getVal1());
3157 break;
3158
3159 case AtomicExpr::AO__atomic_store:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003160 Val1 = EmitScalarExpr(E->getVal1());
Richard Smithfeea8832012-04-12 05:08:17 +00003161 break;
3162
3163 case AtomicExpr::AO__atomic_exchange:
3164 Val1 = EmitScalarExpr(E->getVal1());
3165 Dest = EmitScalarExpr(E->getVal2());
3166 break;
3167
3168 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3169 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3170 case AtomicExpr::AO__atomic_compare_exchange_n:
3171 case AtomicExpr::AO__atomic_compare_exchange:
3172 Val1 = EmitScalarExpr(E->getVal1());
3173 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
3174 Val2 = EmitScalarExpr(E->getVal2());
3175 else
3176 Val2 = EmitValToTemp(*this, E->getVal2());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003177 OrderFail = EmitScalarExpr(E->getOrderFail());
Richard Smithfeea8832012-04-12 05:08:17 +00003178 // Evaluate and discard the 'weak' argument.
3179 if (E->getNumSubExprs() == 6)
3180 EmitScalarExpr(E->getWeak());
3181 break;
3182
3183 case AtomicExpr::AO__c11_atomic_fetch_add:
3184 case AtomicExpr::AO__c11_atomic_fetch_sub:
Richard Smithfeea8832012-04-12 05:08:17 +00003185 if (MemTy->isPointerType()) {
3186 // For pointer arithmetic, we're required to do a bit of math:
3187 // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
Richard Smith01ba47d2012-04-13 00:45:38 +00003188 // ... but only for the C11 builtins. The GNU builtins expect the
3189 // user to multiply by sizeof(T).
Richard Smithfeea8832012-04-12 05:08:17 +00003190 QualType Val1Ty = E->getVal1()->getType();
3191 llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
3192 CharUnits PointeeIncAmt =
3193 getContext().getTypeSizeInChars(MemTy->getPointeeType());
3194 Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
3195 Val1 = CreateMemTemp(Val1Ty, ".atomictmp");
3196 EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Val1, Val1Ty));
3197 break;
3198 }
3199 // Fall through.
Richard Smith01ba47d2012-04-13 00:45:38 +00003200 case AtomicExpr::AO__atomic_fetch_add:
3201 case AtomicExpr::AO__atomic_fetch_sub:
3202 case AtomicExpr::AO__atomic_add_fetch:
3203 case AtomicExpr::AO__atomic_sub_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00003204 case AtomicExpr::AO__c11_atomic_store:
3205 case AtomicExpr::AO__c11_atomic_exchange:
3206 case AtomicExpr::AO__atomic_store_n:
3207 case AtomicExpr::AO__atomic_exchange_n:
3208 case AtomicExpr::AO__c11_atomic_fetch_and:
3209 case AtomicExpr::AO__c11_atomic_fetch_or:
3210 case AtomicExpr::AO__c11_atomic_fetch_xor:
3211 case AtomicExpr::AO__atomic_fetch_and:
3212 case AtomicExpr::AO__atomic_fetch_or:
3213 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00003214 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00003215 case AtomicExpr::AO__atomic_and_fetch:
3216 case AtomicExpr::AO__atomic_or_fetch:
3217 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00003218 case AtomicExpr::AO__atomic_nand_fetch:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003219 Val1 = EmitValToTemp(*this, E->getVal1());
Richard Smithfeea8832012-04-12 05:08:17 +00003220 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003221 }
3222
Richard Smithfeea8832012-04-12 05:08:17 +00003223 if (!E->getType()->isVoidType() && !Dest)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003224 Dest = CreateMemTemp(E->getType(), ".atomicdst");
3225
David Chisnalldb365f32012-03-29 18:01:11 +00003226 // Use a library call. See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003227 if (UseLibcall) {
David Chisnalldb365f32012-03-29 18:01:11 +00003228
3229 llvm::SmallVector<QualType, 5> Params;
3230 CallArgList Args;
3231 // Size is always the first parameter
3232 Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
3233 getContext().getSizeType());
3234 // Atomic address is always the second parameter
3235 Args.add(RValue::get(EmitCastToVoidPtr(Ptr)),
3236 getContext().VoidPtrTy);
3237
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003238 const char* LibCallName;
David Chisnalldb365f32012-03-29 18:01:11 +00003239 QualType RetTy = getContext().VoidTy;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003240 switch (E->getOp()) {
David Chisnalldb365f32012-03-29 18:01:11 +00003241 // There is only one libcall for compare an exchange, because there is no
3242 // optimisation benefit possible from a libcall version of a weak compare
3243 // and exchange.
3244 // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
Richard Smithfeea8832012-04-12 05:08:17 +00003245 // void *desired, int success, int failure)
3246 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3247 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3248 case AtomicExpr::AO__atomic_compare_exchange:
3249 case AtomicExpr::AO__atomic_compare_exchange_n:
David Chisnalldb365f32012-03-29 18:01:11 +00003250 LibCallName = "__atomic_compare_exchange";
3251 RetTy = getContext().BoolTy;
3252 Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3253 getContext().VoidPtrTy);
3254 Args.add(RValue::get(EmitCastToVoidPtr(Val2)),
3255 getContext().VoidPtrTy);
3256 Args.add(RValue::get(Order),
3257 getContext().IntTy);
3258 Order = OrderFail;
3259 break;
3260 // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
3261 // int order)
Richard Smithfeea8832012-04-12 05:08:17 +00003262 case AtomicExpr::AO__c11_atomic_exchange:
3263 case AtomicExpr::AO__atomic_exchange_n:
3264 case AtomicExpr::AO__atomic_exchange:
David Chisnalldb365f32012-03-29 18:01:11 +00003265 LibCallName = "__atomic_exchange";
3266 Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3267 getContext().VoidPtrTy);
3268 Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
3269 getContext().VoidPtrTy);
3270 break;
3271 // void __atomic_store(size_t size, void *mem, void *val, int order)
Richard Smithfeea8832012-04-12 05:08:17 +00003272 case AtomicExpr::AO__c11_atomic_store:
3273 case AtomicExpr::AO__atomic_store:
3274 case AtomicExpr::AO__atomic_store_n:
David Chisnalldb365f32012-03-29 18:01:11 +00003275 LibCallName = "__atomic_store";
3276 Args.add(RValue::get(EmitCastToVoidPtr(Val1)),
3277 getContext().VoidPtrTy);
3278 break;
3279 // void __atomic_load(size_t size, void *mem, void *return, int order)
Richard Smithfeea8832012-04-12 05:08:17 +00003280 case AtomicExpr::AO__c11_atomic_load:
3281 case AtomicExpr::AO__atomic_load:
3282 case AtomicExpr::AO__atomic_load_n:
David Chisnalldb365f32012-03-29 18:01:11 +00003283 LibCallName = "__atomic_load";
3284 Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
3285 getContext().VoidPtrTy);
3286 break;
3287#if 0
3288 // These are only defined for 1-16 byte integers. It is not clear what
3289 // their semantics would be on anything else...
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003290 case AtomicExpr::Add: LibCallName = "__atomic_fetch_add_generic"; break;
3291 case AtomicExpr::Sub: LibCallName = "__atomic_fetch_sub_generic"; break;
3292 case AtomicExpr::And: LibCallName = "__atomic_fetch_and_generic"; break;
3293 case AtomicExpr::Or: LibCallName = "__atomic_fetch_or_generic"; break;
3294 case AtomicExpr::Xor: LibCallName = "__atomic_fetch_xor_generic"; break;
David Chisnalldb365f32012-03-29 18:01:11 +00003295#endif
3296 default: return EmitUnsupportedRValue(E, "atomic library call");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003297 }
David Chisnalldb365f32012-03-29 18:01:11 +00003298 // order is always the last parameter
3299 Args.add(RValue::get(Order),
3300 getContext().IntTy);
3301
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003302 const CGFunctionInfo &FuncInfo =
John McCall8dda7b22012-07-07 06:41:13 +00003303 CGM.getTypes().arrangeFreeFunctionCall(RetTy, Args,
David Chisnalldb365f32012-03-29 18:01:11 +00003304 FunctionType::ExtInfo(), RequiredArgs::All);
3305 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FuncInfo);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003306 llvm::Constant *Func = CGM.CreateRuntimeFunction(FTy, LibCallName);
3307 RValue Res = EmitCall(FuncInfo, Func, ReturnValueSlot(), Args);
3308 if (E->isCmpXChg())
3309 return Res;
Richard Smithfeea8832012-04-12 05:08:17 +00003310 if (E->getType()->isVoidType())
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003311 return RValue::get(0);
3312 return ConvertTempToRValue(*this, E->getType(), Dest);
3313 }
David Chisnalldb365f32012-03-29 18:01:11 +00003314
Eli Friedmanfb9c49e2012-10-30 01:15:28 +00003315 bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
3316 E->getOp() == AtomicExpr::AO__atomic_store ||
3317 E->getOp() == AtomicExpr::AO__atomic_store_n;
3318 bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
3319 E->getOp() == AtomicExpr::AO__atomic_load ||
3320 E->getOp() == AtomicExpr::AO__atomic_load_n;
3321
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003322 llvm::Type *IPtrTy =
3323 llvm::IntegerType::get(getLLVMContext(), Size * 8)->getPointerTo();
3324 llvm::Value *OrigDest = Dest;
3325 Ptr = Builder.CreateBitCast(Ptr, IPtrTy);
3326 if (Val1) Val1 = Builder.CreateBitCast(Val1, IPtrTy);
3327 if (Val2) Val2 = Builder.CreateBitCast(Val2, IPtrTy);
3328 if (Dest && !E->isCmpXChg()) Dest = Builder.CreateBitCast(Dest, IPtrTy);
3329
3330 if (isa<llvm::ConstantInt>(Order)) {
3331 int ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
3332 switch (ord) {
3333 case 0: // memory_order_relaxed
3334 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3335 llvm::Monotonic);
3336 break;
3337 case 1: // memory_order_consume
3338 case 2: // memory_order_acquire
Eli Friedmanfb9c49e2012-10-30 01:15:28 +00003339 if (IsStore)
3340 break; // Avoid crashing on code with undefined behavior
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003341 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3342 llvm::Acquire);
3343 break;
3344 case 3: // memory_order_release
Eli Friedmanfb9c49e2012-10-30 01:15:28 +00003345 if (IsLoad)
3346 break; // Avoid crashing on code with undefined behavior
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003347 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3348 llvm::Release);
3349 break;
3350 case 4: // memory_order_acq_rel
Eli Friedmanfb9c49e2012-10-30 01:15:28 +00003351 if (IsLoad || IsStore)
3352 break; // Avoid crashing on code with undefined behavior
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003353 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3354 llvm::AcquireRelease);
3355 break;
3356 case 5: // memory_order_seq_cst
3357 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3358 llvm::SequentiallyConsistent);
3359 break;
3360 default: // invalid order
3361 // We should not ever get here normally, but it's hard to
3362 // enforce that in general.
Richard Smithfeea8832012-04-12 05:08:17 +00003363 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003364 }
Richard Smithfeea8832012-04-12 05:08:17 +00003365 if (E->getType()->isVoidType())
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003366 return RValue::get(0);
3367 return ConvertTempToRValue(*this, E->getType(), OrigDest);
3368 }
3369
3370 // Long case, when Order isn't obviously constant.
3371
3372 // Create all the relevant BB's
Eli Friedmanc2025562011-10-11 20:00:47 +00003373 llvm::BasicBlock *MonotonicBB = 0, *AcquireBB = 0, *ReleaseBB = 0,
3374 *AcqRelBB = 0, *SeqCstBB = 0;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003375 MonotonicBB = createBasicBlock("monotonic", CurFn);
Richard Smithfeea8832012-04-12 05:08:17 +00003376 if (!IsStore)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003377 AcquireBB = createBasicBlock("acquire", CurFn);
Richard Smithfeea8832012-04-12 05:08:17 +00003378 if (!IsLoad)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003379 ReleaseBB = createBasicBlock("release", CurFn);
Richard Smithfeea8832012-04-12 05:08:17 +00003380 if (!IsLoad && !IsStore)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003381 AcqRelBB = createBasicBlock("acqrel", CurFn);
3382 SeqCstBB = createBasicBlock("seqcst", CurFn);
3383 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
3384
3385 // Create the switch for the split
3386 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
3387 // doesn't matter unless someone is crazy enough to use something that
3388 // doesn't fold to a constant for the ordering.
3389 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
3390 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
3391
3392 // Emit all the different atomics
3393 Builder.SetInsertPoint(MonotonicBB);
3394 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3395 llvm::Monotonic);
3396 Builder.CreateBr(ContBB);
Richard Smithfeea8832012-04-12 05:08:17 +00003397 if (!IsStore) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003398 Builder.SetInsertPoint(AcquireBB);
3399 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3400 llvm::Acquire);
3401 Builder.CreateBr(ContBB);
3402 SI->addCase(Builder.getInt32(1), AcquireBB);
3403 SI->addCase(Builder.getInt32(2), AcquireBB);
3404 }
Richard Smithfeea8832012-04-12 05:08:17 +00003405 if (!IsLoad) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003406 Builder.SetInsertPoint(ReleaseBB);
3407 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3408 llvm::Release);
3409 Builder.CreateBr(ContBB);
3410 SI->addCase(Builder.getInt32(3), ReleaseBB);
3411 }
Richard Smithfeea8832012-04-12 05:08:17 +00003412 if (!IsLoad && !IsStore) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003413 Builder.SetInsertPoint(AcqRelBB);
3414 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3415 llvm::AcquireRelease);
3416 Builder.CreateBr(ContBB);
3417 SI->addCase(Builder.getInt32(4), AcqRelBB);
3418 }
3419 Builder.SetInsertPoint(SeqCstBB);
3420 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, Size, Align,
3421 llvm::SequentiallyConsistent);
3422 Builder.CreateBr(ContBB);
3423 SI->addCase(Builder.getInt32(5), SeqCstBB);
3424
3425 // Cleanup and return
3426 Builder.SetInsertPoint(ContBB);
Richard Smithfeea8832012-04-12 05:08:17 +00003427 if (E->getType()->isVoidType())
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003428 return RValue::get(0);
3429 return ConvertTempToRValue(*this, E->getType(), OrigDest);
3430}
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003431
Duncan Sandse81111c2012-04-10 08:23:07 +00003432void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003433 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00003434 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003435 return;
3436
Duncan Sands65229ed2012-04-16 16:29:47 +00003437 llvm::MDBuilder MDHelper(getLLVMContext());
3438 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003439
Duncan Sands6fc46192012-04-14 12:37:26 +00003440 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003441}
John McCallfe96e0b2011-11-06 09:01:30 +00003442
3443namespace {
3444 struct LValueOrRValue {
3445 LValue LV;
3446 RValue RV;
3447 };
3448}
3449
3450static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
3451 const PseudoObjectExpr *E,
3452 bool forLValue,
3453 AggValueSlot slot) {
3454 llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
3455
3456 // Find the result expression, if any.
3457 const Expr *resultExpr = E->getResultExpr();
3458 LValueOrRValue result;
3459
3460 for (PseudoObjectExpr::const_semantics_iterator
3461 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3462 const Expr *semantic = *i;
3463
3464 // If this semantic expression is an opaque value, bind it
3465 // to the result of its source expression.
3466 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
3467
3468 // If this is the result expression, we may need to evaluate
3469 // directly into the slot.
3470 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
3471 OVMA opaqueData;
3472 if (ov == resultExpr && ov->isRValue() && !forLValue &&
3473 CodeGenFunction::hasAggregateLLVMType(ov->getType()) &&
3474 !ov->getType()->isAnyComplexType()) {
3475 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
3476
3477 LValue LV = CGF.MakeAddrLValue(slot.getAddr(), ov->getType());
3478 opaqueData = OVMA::bind(CGF, ov, LV);
3479 result.RV = slot.asRValue();
3480
3481 // Otherwise, emit as normal.
3482 } else {
3483 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
3484
3485 // If this is the result, also evaluate the result now.
3486 if (ov == resultExpr) {
3487 if (forLValue)
3488 result.LV = CGF.EmitLValue(ov);
3489 else
3490 result.RV = CGF.EmitAnyExpr(ov, slot);
3491 }
3492 }
3493
3494 opaques.push_back(opaqueData);
3495
3496 // Otherwise, if the expression is the result, evaluate it
3497 // and remember the result.
3498 } else if (semantic == resultExpr) {
3499 if (forLValue)
3500 result.LV = CGF.EmitLValue(semantic);
3501 else
3502 result.RV = CGF.EmitAnyExpr(semantic, slot);
3503
3504 // Otherwise, evaluate the expression in an ignored context.
3505 } else {
3506 CGF.EmitIgnoredExpr(semantic);
3507 }
3508 }
3509
3510 // Unbind all the opaques now.
3511 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
3512 opaques[i].unbind(CGF);
3513
3514 return result;
3515}
3516
3517RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
3518 AggValueSlot slot) {
3519 return emitPseudoObjectExpr(*this, E, false, slot).RV;
3520}
3521
3522LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
3523 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
3524}