blob: 6635e570c64adac1d4da7390c7b90c0b641b1223 [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"
Alexey Bataev97720002014-11-11 04:05:39 +000019#include "CGOpenMPRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "CGRecordLayout.h"
21#include "CodeGenModule.h"
John McCallcbc038a2011-09-21 08:08:30 +000022#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000023#include "clang/AST/ASTContext.h"
Renato Golin230c5eb2014-05-19 18:15:42 +000024#include "clang/AST/Attr.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000025#include "clang/AST/DeclObjC.h"
Chandler Carruth85098242010-06-15 23:19:56 +000026#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "llvm/ADT/Hashing.h"
Alexey Bataevec474782014-10-09 08:45:04 +000028#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000029#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/LLVMContext.h"
32#include "llvm/IR/MDBuilder.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000033#include "llvm/Support/ConvertUTF.h"
Peter Collingbourne3eea6772015-05-11 21:39:14 +000034#include "llvm/Support/MathExtras.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000035
Chris Lattnere47e4402007-06-01 18:02:12 +000036using namespace clang;
37using namespace CodeGen;
38
Chris Lattnerd7f58862007-06-02 05:24:33 +000039//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000040// Miscellaneous Helper Methods
41//===--------------------------------------------------------------------===//
42
John McCallad7c5c12011-02-08 08:22:06 +000043llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
44 unsigned addressSpace =
45 cast<llvm::PointerType>(value->getType())->getAddressSpace();
46
Chris Lattner2192fe52011-07-18 04:24:23 +000047 llvm::PointerType *destType = Int8PtrTy;
John McCallad7c5c12011-02-08 08:22:06 +000048 if (addressSpace)
49 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
50
51 if (value->getType() == destType) return value;
52 return Builder.CreateBitCast(value, destType);
53}
54
Chris Lattnere9a64532007-06-22 21:44:33 +000055/// CreateTempAlloca - This creates a alloca and inserts it into the entry
56/// block.
John McCall7f416cc2015-09-08 08:05:57 +000057Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
58 const Twine &Name) {
59 auto Alloca = CreateTempAlloca(Ty, Name);
60 Alloca->setAlignment(Align.getQuantity());
61 return Address(Alloca, Align);
62}
63
64/// CreateTempAlloca - This creates a alloca and inserts it into the entry
65/// block.
Chris Lattner2192fe52011-07-18 04:24:23 +000066llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000067 const Twine &Name) {
Chris Lattner47640222009-03-22 00:24:14 +000068 if (!Builder.isNamePreserving())
Craig Topper8a13c412014-05-21 05:09:00 +000069 return new llvm::AllocaInst(Ty, nullptr, "", AllocaInsertPt);
70 return new llvm::AllocaInst(Ty, nullptr, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +000071}
Chris Lattner8394d792007-06-05 20:53:16 +000072
John McCall7f416cc2015-09-08 08:05:57 +000073/// CreateDefaultAlignTempAlloca - This creates an alloca with the
74/// default alignment of the corresponding LLVM type, which is *not*
75/// guaranteed to be related in any way to the expected alignment of
76/// an AST type that might have been lowered to Ty.
77Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
78 const Twine &Name) {
79 CharUnits Align =
80 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
81 return CreateTempAlloca(Ty, Align, Name);
82}
83
84void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
85 assert(isa<llvm::AllocaInst>(Var.getPointer()));
86 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
87 Store->setAlignment(Var.getAlignment().getQuantity());
John McCall2e6567a2010-04-22 01:10:34 +000088 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
89 Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
90}
91
John McCall7f416cc2015-09-08 08:05:57 +000092Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +000093 CharUnits Align = getContext().getTypeAlignInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +000094 return CreateTempAlloca(ConvertType(Ty), Align, Name);
Daniel Dunbard0049182010-02-16 19:44:13 +000095}
96
John McCall7f416cc2015-09-08 08:05:57 +000097Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name) {
Daniel Dunbara7566f12010-02-09 02:48:28 +000098 // FIXME: Should we prefer the preferred type alignment here?
John McCall7f416cc2015-09-08 08:05:57 +000099 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name);
100}
101
102Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
103 const Twine &Name) {
104 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name);
Daniel Dunbara7566f12010-02-09 02:48:28 +0000105}
106
Chris Lattner8394d792007-06-05 20:53:16 +0000107/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
108/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000109llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000110 PGO.setCurrentStmt(E);
John McCall7a9aac22010-08-23 01:21:21 +0000111 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +0000112 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +0000113 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +0000114 }
John McCall7a9aac22010-08-23 01:21:21 +0000115
116 QualType BoolTy = getContext().BoolTy;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000117 SourceLocation Loc = E->getExprLoc();
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000118 if (!E->getType()->isAnyComplexType())
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000119 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +0000120
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000121 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
122 Loc);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000123}
124
John McCalla2342eb2010-12-05 02:00:02 +0000125/// EmitIgnoredExpr - Emit code to compute the specified expression,
126/// ignoring the result.
127void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
128 if (E->isRValue())
129 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
130
131 // Just emit it as an l-value and drop the result.
132 EmitLValue(E);
133}
134
John McCall7a626f62010-09-15 10:14:12 +0000135/// EmitAnyExpr - Emit code to compute the specified expression which
136/// can have any type. The result is returned as an RValue struct.
137/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000138/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000139RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
140 AggValueSlot aggSlot,
141 bool ignoreResult) {
John McCall47fb9502013-03-07 21:37:08 +0000142 switch (getEvaluationKind(E->getType())) {
143 case TEK_Scalar:
John McCall4e8ca4f2012-07-02 23:58:38 +0000144 return RValue::get(EmitScalarExpr(E, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000145 case TEK_Complex:
John McCall4e8ca4f2012-07-02 23:58:38 +0000146 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000147 case TEK_Aggregate:
148 if (!ignoreResult && aggSlot.isIgnored())
149 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
150 EmitAggExpr(E, aggSlot);
151 return aggSlot.asRValue();
152 }
153 llvm_unreachable("bad evaluation kind");
Chris Lattner4647a212007-08-31 22:49:20 +0000154}
155
Mike Stump4a3999f2009-09-09 13:00:44 +0000156/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
157/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000158RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
159 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000160
John McCall47fb9502013-03-07 21:37:08 +0000161 if (hasAggregateEvaluationKind(E->getType()))
John McCall7a626f62010-09-15 10:14:12 +0000162 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
163 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000164}
165
John McCall21886962010-04-21 10:05:39 +0000166/// EmitAnyExprToMem - Evaluate an expression into a given memory
167/// location.
168void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000169 Address Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000170 Qualifiers Quals,
171 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000172 // FIXME: This function should take an LValue as an argument.
John McCall47fb9502013-03-07 21:37:08 +0000173 switch (getEvaluationKind(E->getType())) {
174 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000175 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
John McCall47fb9502013-03-07 21:37:08 +0000176 /*isInit*/ false);
177 return;
178
179 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000180 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000181 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000182 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000183 AggValueSlot::IsAliased_t(!IsInit)));
John McCall47fb9502013-03-07 21:37:08 +0000184 return;
185 }
186
187 case TEK_Scalar: {
John McCall21886962010-04-21 10:05:39 +0000188 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000189 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000190 EmitStoreThroughLValue(RV, LV);
John McCall47fb9502013-03-07 21:37:08 +0000191 return;
John McCall21886962010-04-21 10:05:39 +0000192 }
John McCall47fb9502013-03-07 21:37:08 +0000193 }
194 llvm_unreachable("bad evaluation kind");
John McCall21886962010-04-21 10:05:39 +0000195}
196
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000197static void
198pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
John McCall7f416cc2015-09-08 08:05:57 +0000199 const Expr *E, Address ReferenceTemporary) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000200 // Objective-C++ ARC:
201 // If we are binding a reference to a temporary that has ownership, we
202 // need to perform retain/release operations on the temporary.
Richard Smith736a9472013-06-12 20:42:33 +0000203 //
204 // FIXME: This should be looking at E, not M.
205 if (CGF.getLangOpts().ObjCAutoRefCount &&
206 M->getType()->isObjCLifetimeType()) {
207 QualType ObjCARCReferenceLifetimeType = M->getType();
208 switch (Qualifiers::ObjCLifetime Lifetime =
209 ObjCARCReferenceLifetimeType.getObjCLifetime()) {
210 case Qualifiers::OCL_None:
211 case Qualifiers::OCL_ExplicitNone:
212 // Carry on to normal cleanup handling.
213 break;
Sebastian Redl29526f02011-11-27 16:50:07 +0000214
Richard Smith736a9472013-06-12 20:42:33 +0000215 case Qualifiers::OCL_Autoreleasing:
216 // Nothing to do; cleaned up by an autorelease pool.
217 return;
218
219 case Qualifiers::OCL_Strong:
220 case Qualifiers::OCL_Weak:
221 switch (StorageDuration Duration = M->getStorageDuration()) {
222 case SD_Static:
223 // Note: we intentionally do not register a cleanup to release
224 // the object on program termination.
225 return;
226
227 case SD_Thread:
228 // FIXME: We should probably register a cleanup in this case.
229 return;
230
231 case SD_Automatic:
232 case SD_FullExpression:
Richard Smith736a9472013-06-12 20:42:33 +0000233 CodeGenFunction::Destroyer *Destroy;
234 CleanupKind CleanupKind;
235 if (Lifetime == Qualifiers::OCL_Strong) {
236 const ValueDecl *VD = M->getExtendingDecl();
237 bool Precise =
238 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
239 CleanupKind = CGF.getARCCleanupKind();
240 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
241 : &CodeGenFunction::destroyARCStrongImprecise;
242 } else {
243 // __weak objects always get EH cleanups; otherwise, exceptions
244 // could cause really nasty crashes instead of mere leaks.
245 CleanupKind = NormalAndEHCleanup;
246 Destroy = &CodeGenFunction::destroyARCWeak;
247 }
248 if (Duration == SD_FullExpression)
249 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
250 ObjCARCReferenceLifetimeType, *Destroy,
251 CleanupKind & EHCleanup);
252 else
253 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
254 ObjCARCReferenceLifetimeType,
255 *Destroy, CleanupKind & EHCleanup);
256 return;
257
258 case SD_Dynamic:
259 llvm_unreachable("temporary cannot have dynamic storage duration");
260 }
261 llvm_unreachable("unknown storage duration");
262 }
263 }
264
Craig Topper8a13c412014-05-21 05:09:00 +0000265 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
Richard Smith736a9472013-06-12 20:42:33 +0000266 if (const RecordType *RT =
267 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
268 // Get the destructor for the reference temporary.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000269 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith736a9472013-06-12 20:42:33 +0000270 if (!ClassDecl->hasTrivialDestructor())
271 ReferenceTemporaryDtor = ClassDecl->getDestructor();
272 }
273
274 if (!ReferenceTemporaryDtor)
275 return;
276
277 // Call the destructor for the temporary.
278 switch (M->getStorageDuration()) {
279 case SD_Static:
280 case SD_Thread: {
281 llvm::Constant *CleanupFn;
282 llvm::Constant *CleanupArg;
283 if (E->getType()->isArrayType()) {
284 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
John McCall7f416cc2015-09-08 08:05:57 +0000285 ReferenceTemporary, E->getType(),
David Blaikieebe87e12013-08-27 23:57:18 +0000286 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
287 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
Richard Smith736a9472013-06-12 20:42:33 +0000288 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
289 } else {
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000290 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
291 StructorType::Complete);
John McCall7f416cc2015-09-08 08:05:57 +0000292 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
Richard Smith736a9472013-06-12 20:42:33 +0000293 }
294 CGF.CGM.getCXXABI().registerGlobalDtor(
295 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
296 break;
297 }
298
299 case SD_FullExpression:
300 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
301 CodeGenFunction::destroyCXXObject,
302 CGF.getLangOpts().Exceptions);
303 break;
304
305 case SD_Automatic:
306 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
307 ReferenceTemporary, E->getType(),
308 CodeGenFunction::destroyCXXObject,
309 CGF.getLangOpts().Exceptions);
310 break;
311
312 case SD_Dynamic:
313 llvm_unreachable("temporary cannot have dynamic storage duration");
314 }
315}
316
John McCall7f416cc2015-09-08 08:05:57 +0000317static Address
Richard Smith736a9472013-06-12 20:42:33 +0000318createReferenceTemporary(CodeGenFunction &CGF,
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000319 const MaterializeTemporaryExpr *M, const Expr *Inner) {
Richard Smith736a9472013-06-12 20:42:33 +0000320 switch (M->getStorageDuration()) {
321 case SD_FullExpression:
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000322 case SD_Automatic: {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000323 // If we have a constant temporary array or record try to promote it into a
324 // constant global under the same rules a normal constant would've been
325 // promoted. This is easier on the optimizer and generally emits fewer
326 // instructions.
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000327 QualType Ty = Inner->getType();
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000328 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000329 (Ty->isArrayType() || Ty->isRecordType()) &&
330 CGF.CGM.isTypeConstant(Ty, true))
331 if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000332 auto *GV = new llvm::GlobalVariable(
333 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
334 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp");
John McCall7f416cc2015-09-08 08:05:57 +0000335 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
336 GV->setAlignment(alignment.getQuantity());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000337 // FIXME: Should we put the new global into a COMDAT?
John McCall7f416cc2015-09-08 08:05:57 +0000338 return Address(GV, alignment);
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000339 }
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000340 return CGF.CreateMemTemp(Ty, "ref.tmp");
341 }
Richard Smith736a9472013-06-12 20:42:33 +0000342 case SD_Thread:
343 case SD_Static:
Hans Wennborgf9d865b2015-03-17 16:38:58 +0000344 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
Richard Smith736a9472013-06-12 20:42:33 +0000345
346 case SD_Dynamic:
347 llvm_unreachable("temporary can't have dynamic storage duration");
348 }
349 llvm_unreachable("unknown storage duration");
350}
351
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000352LValue CodeGenFunction::
353EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000354 const Expr *E = M->GetTemporaryExpr();
Richard Smith7c5d4dc2013-06-11 02:41:00 +0000355
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000356 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
357 // as that will cause the lifetime adjustment to be lost for ARC
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000358 if (getLangOpts().ObjCAutoRefCount &&
Richard Smith736a9472013-06-12 20:42:33 +0000359 M->getType()->isObjCLifetimeType() &&
360 M->getType().getObjCLifetime() != Qualifiers::OCL_None &&
361 M->getType().getObjCLifetime() != Qualifiers::OCL_ExplicitNone) {
John McCall7f416cc2015-09-08 08:05:57 +0000362 Address Object = createReferenceTemporary(*this, M, E);
363 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
364 Object = Address(llvm::ConstantExpr::getBitCast(Var,
365 ConvertTypeForMem(E->getType())
366 ->getPointerTo(Object.getAddressSpace())),
367 Object.getAlignment());
Richard Smitha509f2f2013-06-14 03:07:01 +0000368 // We should not have emitted the initializer for this temporary as a
369 // constant.
370 assert(!Var->hasInitializer());
371 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
372 }
John McCall7f416cc2015-09-08 08:05:57 +0000373 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
374 AlignmentSource::Decl);
Richard Smitha509f2f2013-06-14 03:07:01 +0000375
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000376 switch (getEvaluationKind(E->getType())) {
377 default: llvm_unreachable("expected scalar or aggregate expression");
378 case TEK_Scalar:
379 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
380 break;
381 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000382 EmitAggExpr(E, AggValueSlot::forAddr(Object,
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000383 E->getType().getQualifiers(),
384 AggValueSlot::IsDestructed,
385 AggValueSlot::DoesNotNeedGCBarriers,
386 AggValueSlot::IsNotAliased));
387 break;
388 }
389 }
Richard Smith736a9472013-06-12 20:42:33 +0000390
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000391 pushTemporaryCleanup(*this, M, E, Object);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000392 return RefTempDst;
Jordan Roseb1312a52013-04-11 00:58:58 +0000393 }
394
Richard Smithf3fabd22013-06-03 00:17:11 +0000395 SmallVector<const Expr *, 2> CommaLHSs;
Jordan Roseb1312a52013-04-11 00:58:58 +0000396 SmallVector<SubobjectAdjustment, 2> Adjustments;
Richard Smithf3fabd22013-06-03 00:17:11 +0000397 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
398
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000399 for (const auto &Ignored : CommaLHSs)
400 EmitIgnoredExpr(Ignored);
Richard Smithf3fabd22013-06-03 00:17:11 +0000401
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000402 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
Richard Smith736a9472013-06-12 20:42:33 +0000403 if (opaque->getType()->isRecordType()) {
404 assert(Adjustments.empty());
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000405 return EmitOpaqueValueLValue(opaque);
Jordan Roseb1312a52013-04-11 00:58:58 +0000406 }
407 }
408
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000409 // Create and initialize the reference temporary.
John McCall7f416cc2015-09-08 08:05:57 +0000410 Address Object = createReferenceTemporary(*this, M, E);
411 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
412 Object = Address(llvm::ConstantExpr::getBitCast(
413 Var, ConvertTypeForMem(E->getType())->getPointerTo()),
414 Object.getAlignment());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000415 // If the temporary is a global and has a constant initializer or is a
416 // constant temporary that we promoted to a global, we may have already
417 // initialized it.
Richard Smitha509f2f2013-06-14 03:07:01 +0000418 if (!Var->hasInitializer()) {
419 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
420 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
421 }
422 } else {
423 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
424 }
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000425 pushTemporaryCleanup(*this, M, E, Object);
Jordan Roseb1312a52013-04-11 00:58:58 +0000426
Richard Smith736a9472013-06-12 20:42:33 +0000427 // Perform derived-to-base casts and/or field accesses, to get from the
428 // temporary object we created (and, potentially, for which we extended
429 // the lifetime) to the subobject we're binding the reference to.
430 for (unsigned I = Adjustments.size(); I != 0; --I) {
431 SubobjectAdjustment &Adjustment = Adjustments[I-1];
432 switch (Adjustment.Kind) {
433 case SubobjectAdjustment::DerivedToBaseAdjustment:
434 Object =
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000435 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
436 Adjustment.DerivedToBase.BasePath->path_begin(),
437 Adjustment.DerivedToBase.BasePath->path_end(),
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000438 /*NullCheckValue=*/ false, E->getExprLoc());
Richard Smith736a9472013-06-12 20:42:33 +0000439 break;
Richard Smithf3fabd22013-06-03 00:17:11 +0000440
Richard Smith736a9472013-06-12 20:42:33 +0000441 case SubobjectAdjustment::FieldAdjustment: {
John McCall7f416cc2015-09-08 08:05:57 +0000442 LValue LV = MakeAddrLValue(Object, E->getType(),
443 AlignmentSource::Decl);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000444 LV = EmitLValueForField(LV, Adjustment.Field);
Richard Smith736a9472013-06-12 20:42:33 +0000445 assert(LV.isSimple() &&
446 "materialized temporary field is not a simple lvalue");
447 Object = LV.getAddress();
448 break;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000449 }
450
Richard Smith736a9472013-06-12 20:42:33 +0000451 case SubobjectAdjustment::MemberPointerAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000452 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
John McCall7f416cc2015-09-08 08:05:57 +0000453 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
454 Adjustment.Ptr.MPT);
Richard Smith736a9472013-06-12 20:42:33 +0000455 break;
456 }
457 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000458 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000459
John McCall7f416cc2015-09-08 08:05:57 +0000460 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000461}
462
463RValue
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000464CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
465 // Emit the expression as an lvalue.
466 LValue LV = EmitLValue(E);
467 assert(LV.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000468 llvm::Value *Value = LV.getPointer();
Richard Smith736a9472013-06-12 20:42:33 +0000469
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000470 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000471 // C++11 [dcl.ref]p5 (as amended by core issue 453):
472 // If a glvalue to which a reference is directly bound designates neither
473 // an existing object or function of an appropriate type nor a region of
474 // storage of suitable size and alignment to contain an object of the
475 // reference's type, the behavior is undefined.
476 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000477 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000478 }
John McCall8680f872010-07-21 06:29:51 +0000479
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000480 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000481}
482
483
Mike Stump4a3999f2009-09-09 13:00:44 +0000484/// getAccessedFieldNo - Given an encoded value and a result number, return the
485/// input field number being accessed.
486unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000487 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000488 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
489 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000490}
491
Richard Smith4d3110a2012-10-25 02:14:12 +0000492/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
493static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
494 llvm::Value *High) {
495 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
496 llvm::Value *K47 = Builder.getInt64(47);
497 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
498 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
499 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
500 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
501 return Builder.CreateMul(B1, KMul);
502}
503
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000504bool CodeGenFunction::sanitizePerformTypeCheck() const {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000505 return SanOpts.has(SanitizerKind::Null) |
506 SanOpts.has(SanitizerKind::Alignment) |
507 SanOpts.has(SanitizerKind::ObjectSize) |
508 SanOpts.has(SanitizerKind::Vptr);
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000509}
510
Richard Smithe30752c2012-10-09 19:52:38 +0000511void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +0000512 llvm::Value *Ptr, QualType Ty,
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000513 CharUnits Alignment, bool SkipNullCheck) {
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000514 if (!sanitizePerformTypeCheck())
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000515 return;
516
Richard Smith2d8b2942012-11-01 07:22:08 +0000517 // Don't check pointers outside the default address space. The null check
518 // isn't correct, the object-size check isn't supported by LLVM, and we can't
519 // communicate the addresses to the runtime handler for the vptr check.
John McCall7f416cc2015-09-08 08:05:57 +0000520 if (Ptr->getType()->getPointerAddressSpace())
Richard Smith2d8b2942012-11-01 07:22:08 +0000521 return;
522
Alexey Samsonov24cad992014-07-17 18:46:27 +0000523 SanitizerScope SanScope(this);
524
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000525 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
Craig Topper8a13c412014-05-21 05:09:00 +0000526 llvm::BasicBlock *Done = nullptr;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000527
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000528 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
529 TCK == TCK_UpcastToVirtualBase;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000530 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
531 !SkipNullCheck) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000532 // The glvalue must not be an empty glvalue.
John McCall7f416cc2015-09-08 08:05:57 +0000533 llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr);
Richard Smith2c5868c2013-02-13 21:18:23 +0000534
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000535 if (AllowNullPointers) {
536 // When performing pointer casts, it's OK if the value is null.
Richard Smith2c5868c2013-02-13 21:18:23 +0000537 // Skip the remaining checks in that case.
538 Done = createBasicBlock("null");
539 llvm::BasicBlock *Rest = createBasicBlock("not.null");
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000540 Builder.CreateCondBr(IsNonNull, Rest, Done);
Richard Smith2c5868c2013-02-13 21:18:23 +0000541 EmitBlock(Rest);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +0000542 } else {
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000543 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
Richard Smith2c5868c2013-02-13 21:18:23 +0000544 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000545 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000546
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000547 if (SanOpts.has(SanitizerKind::ObjectSize) && !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000548 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000549
Richard Smith69d0d262012-08-24 00:54:33 +0000550 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000551 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000552 // to check this.
Matt Arsenault2f152632013-10-07 19:00:18 +0000553 // FIXME: Get object address space
554 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
555 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smith69d0d262012-08-24 00:54:33 +0000556 llvm::Value *Min = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +0000557 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
Richard Smith69d0d262012-08-24 00:54:33 +0000558 llvm::Value *LargeEnough =
David Blaikie43f9bb72015-05-18 22:14:03 +0000559 Builder.CreateICmpUGE(Builder.CreateCall(F, {CastAddr, Min}),
Richard Smith69d0d262012-08-24 00:54:33 +0000560 llvm::ConstantInt::get(IntPtrTy, Size));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000561 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
Richard Smithe30752c2012-10-09 19:52:38 +0000562 }
Richard Smith69d0d262012-08-24 00:54:33 +0000563
Richard Smithb1b0ab42012-11-05 22:21:05 +0000564 uint64_t AlignVal = 0;
565
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000566 if (SanOpts.has(SanitizerKind::Alignment)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000567 AlignVal = Alignment.getQuantity();
568 if (!Ty->isIncompleteType() && !AlignVal)
569 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
570
Richard Smith69d0d262012-08-24 00:54:33 +0000571 // The glvalue must be suitably aligned.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000572 if (AlignVal) {
573 llvm::Value *Align =
John McCall7f416cc2015-09-08 08:05:57 +0000574 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
Richard Smithb1b0ab42012-11-05 22:21:05 +0000575 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
576 llvm::Value *Aligned =
577 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000578 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000579 }
Richard Smith69d0d262012-08-24 00:54:33 +0000580 }
581
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000582 if (Checks.size() > 0) {
Richard Smithe30752c2012-10-09 19:52:38 +0000583 llvm::Constant *StaticData[] = {
584 EmitCheckSourceLocation(Loc),
585 EmitCheckTypeDescriptor(Ty),
586 llvm::ConstantInt::get(SizeTy, AlignVal),
587 llvm::ConstantInt::get(Int8Ty, TCK)
588 };
John McCall7f416cc2015-09-08 08:05:57 +0000589 EmitCheck(Checks, "type_mismatch", StaticData, Ptr);
Richard Smithe30752c2012-10-09 19:52:38 +0000590 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000591
Richard Smithb1b0ab42012-11-05 22:21:05 +0000592 // If possible, check that the vptr indicates that there is a subobject of
593 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000594 //
595 // C++11 [basic.life]p5,6:
596 // [For storage which does not refer to an object within its lifetime]
597 // The program has undefined behavior if:
598 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000599 // or call a non-static member function
Richard Smith4d3110a2012-10-25 02:14:12 +0000600 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000601 if (SanOpts.has(SanitizerKind::Vptr) &&
Richard Smith2c5868c2013-02-13 21:18:23 +0000602 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000603 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
604 TCK == TCK_UpcastToVirtualBase) &&
Richard Smith4d3110a2012-10-25 02:14:12 +0000605 RD && RD->hasDefinition() && RD->isDynamicClass()) {
Richard Smith4d3110a2012-10-25 02:14:12 +0000606 // Compute a hash of the mangled name of the type.
607 //
608 // FIXME: This is not guaranteed to be deterministic! Move to a
609 // fingerprinting mechanism once LLVM provides one. For the time
610 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000611 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000612 llvm::raw_svector_ostream Out(MangledName);
613 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
614 Out);
Richard Smith4d3110a2012-10-25 02:14:12 +0000615
Alexey Samsonov84856012014-07-10 22:34:19 +0000616 // Blacklist based on the mangled type.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000617 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
618 Out.str())) {
Alexey Samsonov84856012014-07-10 22:34:19 +0000619 llvm::hash_code TypeHash = hash_value(Out.str());
Richard Smith4d3110a2012-10-25 02:14:12 +0000620
Alexey Samsonov84856012014-07-10 22:34:19 +0000621 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
622 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
623 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
John McCall7f416cc2015-09-08 08:05:57 +0000624 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000625 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
626 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
Richard Smith4d3110a2012-10-25 02:14:12 +0000627
Alexey Samsonov84856012014-07-10 22:34:19 +0000628 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
629 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
Richard Smith4d3110a2012-10-25 02:14:12 +0000630
Alexey Samsonov84856012014-07-10 22:34:19 +0000631 // Look the hash up in our cache.
632 const int CacheSize = 128;
633 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
634 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
635 "__ubsan_vptr_type_cache");
636 llvm::Value *Slot = Builder.CreateAnd(Hash,
637 llvm::ConstantInt::get(IntPtrTy,
638 CacheSize-1));
639 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
640 llvm::Value *CacheVal =
John McCall7f416cc2015-09-08 08:05:57 +0000641 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
642 getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000643
644 // If the hash isn't in the cache, call a runtime handler to perform the
645 // hard work of checking whether the vptr is for an object of the right
646 // type. This will either fill in the cache and return, or produce a
647 // diagnostic.
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000648 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
Alexey Samsonov84856012014-07-10 22:34:19 +0000649 llvm::Constant *StaticData[] = {
650 EmitCheckSourceLocation(Loc),
651 EmitCheckTypeDescriptor(Ty),
652 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
653 llvm::ConstantInt::get(Int8Ty, TCK)
654 };
John McCall7f416cc2015-09-08 08:05:57 +0000655 llvm::Value *DynamicData[] = { Ptr, Hash };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000656 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
657 "dynamic_type_cache_miss", StaticData, DynamicData);
Alexey Samsonov84856012014-07-10 22:34:19 +0000658 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000659 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000660
661 if (Done) {
662 Builder.CreateBr(Done);
663 EmitBlock(Done);
664 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000665}
Chris Lattner4647a212007-08-31 22:49:20 +0000666
Richard Smith539e4a72013-02-23 02:53:19 +0000667/// Determine whether this expression refers to a flexible array member in a
668/// struct. We disable array bounds checks for such members.
669static bool isFlexibleArrayMemberExpr(const Expr *E) {
670 // For compatibility with existing code, we treat arrays of length 0 or
671 // 1 as flexible array members.
672 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000673 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000674 if (CAT->getSize().ugt(1))
675 return false;
676 } else if (!isa<IncompleteArrayType>(AT))
677 return false;
678
679 E = E->IgnoreParens();
680
681 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000682 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000683 // FIXME: If the base type of the member expr is not FD->getParent(),
684 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000685 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith539e4a72013-02-23 02:53:19 +0000686 RecordDecl::field_iterator FI(
687 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
688 return ++FI == FD->getParent()->field_end();
689 }
690 }
691
692 return false;
693}
694
695/// If Base is known to point to the start of an array, return the length of
696/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000697static llvm::Value *getArrayIndexingBound(
698 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000699 // For the vector indexing extension, the bound is the number of elements.
700 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
701 IndexedType = Base->getType();
702 return CGF.Builder.getInt32(VT->getNumElements());
703 }
704
705 Base = Base->IgnoreParens();
706
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000707 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000708 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
709 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
710 IndexedType = CE->getSubExpr()->getType();
711 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000712 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000713 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000714 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000715 return CGF.getVLASize(VAT).first;
716 }
717 }
718
Craig Topper8a13c412014-05-21 05:09:00 +0000719 return nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000720}
721
722void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
723 llvm::Value *Index, QualType IndexType,
724 bool Accessed) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000725 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
Richard Smith6b53e222013-10-22 22:51:04 +0000726 "should not be called unless adding bounds checks");
Alexey Samsonov24cad992014-07-17 18:46:27 +0000727 SanitizerScope SanScope(this);
Richard Smith2847b222013-02-24 01:56:24 +0000728
Richard Smith539e4a72013-02-23 02:53:19 +0000729 QualType IndexedType;
730 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
731 if (!Bound)
732 return;
733
734 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
735 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
736 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
737
738 llvm::Constant *StaticData[] = {
739 EmitCheckSourceLocation(E->getExprLoc()),
740 EmitCheckTypeDescriptor(IndexedType),
741 EmitCheckTypeDescriptor(IndexType)
742 };
743 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
744 : Builder.CreateICmpULE(IndexVal, BoundVal);
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000745 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds), "out_of_bounds",
746 StaticData, Index);
Richard Smith539e4a72013-02-23 02:53:19 +0000747}
748
Chris Lattner116ce8f2010-01-09 21:40:03 +0000749
Chris Lattner116ce8f2010-01-09 21:40:03 +0000750CodeGenFunction::ComplexPairTy CodeGenFunction::
751EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
752 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000753 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +0000754
Chris Lattner116ce8f2010-01-09 21:40:03 +0000755 llvm::Value *NextVal;
756 if (isa<llvm::IntegerType>(InVal.first->getType())) {
757 uint64_t AmountVal = isInc ? 1 : -1;
758 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +0000759
Chris Lattner116ce8f2010-01-09 21:40:03 +0000760 // Add the inc/dec to the real part.
761 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
762 } else {
763 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
764 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
765 if (!isInc)
766 FVal.changeSign();
767 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
Craig Topper99e79272013-07-26 05:59:26 +0000768
Chris Lattner116ce8f2010-01-09 21:40:03 +0000769 // Add the inc/dec to the real part.
770 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
771 }
Craig Topper99e79272013-07-26 05:59:26 +0000772
Chris Lattner116ce8f2010-01-09 21:40:03 +0000773 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +0000774
Chris Lattner116ce8f2010-01-09 21:40:03 +0000775 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +0000776 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Craig Topper99e79272013-07-26 05:59:26 +0000777
Chris Lattner116ce8f2010-01-09 21:40:03 +0000778 // If this is a postinc, return the value read from memory, otherwise use the
779 // updated value.
780 return isPre ? IncVal : InVal;
781}
782
Chris Lattnera45c5af2007-06-02 19:47:04 +0000783//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000784// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000785//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000786
John McCall7f416cc2015-09-08 08:05:57 +0000787/// EmitPointerWithAlignment - Given an expression of pointer type, try to
788/// derive a more accurate bound on the alignment of the pointer.
789Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
790 AlignmentSource *Source) {
791 // We allow this with ObjC object pointers because of fragile ABIs.
792 assert(E->getType()->isPointerType() ||
793 E->getType()->isObjCObjectPointerType());
794 E = E->IgnoreParens();
795
796 // Casts:
797 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
798 // Bind VLAs in the cast type.
799 if (E->getType()->isVariablyModifiedType())
800 EmitVariablyModifiedType(E->getType());
801
802 switch (CE->getCastKind()) {
803 // Non-converting casts (but not C's implicit conversion from void*).
804 case CK_BitCast:
805 case CK_NoOp:
806 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
807 if (PtrTy->getPointeeType()->isVoidType())
808 break;
809
810 AlignmentSource InnerSource;
811 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerSource);
812 if (Source) *Source = InnerSource;
813
814 // If this is an explicit bitcast, and the source l-value is
815 // opaque, honor the alignment of the casted-to type.
816 if (isa<ExplicitCastExpr>(CE) &&
817 CE->getCastKind() == CK_BitCast &&
818 InnerSource != AlignmentSource::Decl) {
819 Addr = Address(Addr.getPointer(),
820 getNaturalPointeeTypeAlignment(E->getType(), Source));
821 }
822
823 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
824 }
825 break;
826
827 // Array-to-pointer decay.
828 case CK_ArrayToPointerDecay:
829 return EmitArrayToPointerDecay(CE->getSubExpr(), Source);
830
831 // Derived-to-base conversions.
832 case CK_UncheckedDerivedToBase:
833 case CK_DerivedToBase: {
834 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), Source);
835 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
836 return GetAddressOfBaseClass(Addr, Derived,
837 CE->path_begin(), CE->path_end(),
838 ShouldNullCheckClassCastValue(CE),
839 CE->getExprLoc());
840 }
841
842 // TODO: Is there any reason to treat base-to-derived conversions
843 // specially?
844 default:
845 break;
846 }
847 }
848
849 // Unary &.
850 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
851 if (UO->getOpcode() == UO_AddrOf) {
852 LValue LV = EmitLValue(UO->getSubExpr());
853 if (Source) *Source = LV.getAlignmentSource();
854 return LV.getAddress();
855 }
856 }
857
858 // TODO: conditional operators, comma.
859
860 // Otherwise, use the alignment of the type.
861 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), Source);
862 return Address(EmitScalarExpr(E), Align);
863}
864
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000865RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000866 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +0000867 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +0000868
869 switch (getEvaluationKind(Ty)) {
870 case TEK_Complex: {
871 llvm::Type *EltTy =
872 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +0000873 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000874 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000875 }
Craig Topper99e79272013-07-26 05:59:26 +0000876
Chris Lattner65526f02010-08-23 05:26:13 +0000877 // If this is a use of an undefined aggregate type, the aggregate must have an
878 // identifiable address. Just because the contents of the value are undefined
879 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +0000880 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000881 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +0000882 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000883 }
John McCall47fb9502013-03-07 21:37:08 +0000884
885 case TEK_Scalar:
886 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
887 }
888 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +0000889}
890
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000891RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
892 const char *Name) {
893 ErrorUnsupported(E, Name);
894 return GetUndefRValue(E->getType());
895}
896
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000897LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
898 const char *Name) {
899 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000900 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +0000901 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
902 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000903}
904
Richard Smith4d1458e2012-09-08 02:08:36 +0000905LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +0000906 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000907 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +0000908 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
909 else
910 LV = EmitLValue(E);
Daniel Dunbardc406b82010-04-05 21:36:35 +0000911 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
John McCall7f416cc2015-09-08 08:05:57 +0000912 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
Richard Smithe30752c2012-10-09 19:52:38 +0000913 E->getType(), LV.getAlignment());
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000914 return LV;
915}
916
Chris Lattner8394d792007-06-05 20:53:16 +0000917/// EmitLValue - Emit code to compute a designator that specifies the location
918/// of the expression.
919///
Mike Stump4a3999f2009-09-09 13:00:44 +0000920/// This can return one of two things: a simple address or a bitfield reference.
921/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
922/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +0000923///
Mike Stump4a3999f2009-09-09 13:00:44 +0000924/// If this returns a bitfield reference, nothing about the pointee type of the
925/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +0000926///
Mike Stump4a3999f2009-09-09 13:00:44 +0000927/// If this returns a normal address, and if the lvalue's C type is fixed size,
928/// this method guarantees that the returned pointer type will point to an LLVM
929/// type of the same size of the lvalue's type. If the lvalue has a variable
930/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +0000931///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000932LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +0000933 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +0000934 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000935 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000936
John McCallc109a252011-11-07 03:59:57 +0000937 case Expr::ObjCPropertyRefExprClass:
938 llvm_unreachable("cannot emit a property reference directly");
939
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000940 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +0000941 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000942 case Expr::ObjCIsaExprClass:
943 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000944 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +0000945 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +0000946 case Expr::CompoundAssignOperatorClass: {
947 QualType Ty = E->getType();
948 if (const AtomicType *AT = Ty->getAs<AtomicType>())
949 Ty = AT->getValueType();
950 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +0000951 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
952 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +0000953 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000954 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +0000955 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000956 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +0000957 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000958 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +0000959 case Expr::VAArgExprClass:
960 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000961 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000962 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +0000963 case Expr::ParenExprClass:
964 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +0000965 case Expr::GenericSelectionExprClass:
966 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +0000967 case Expr::PredefinedExprClass:
968 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +0000969 case Expr::StringLiteralClass:
970 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +0000971 case Expr::ObjCEncodeExprClass:
972 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +0000973 case Expr::PseudoObjectExprClass:
974 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +0000975 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +0000976 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +0000977 case Expr::CXXTemporaryObjectExprClass:
978 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +0000979 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
980 case Expr::CXXBindTemporaryExprClass:
981 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +0000982 case Expr::CXXUuidofExprClass:
983 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +0000984 case Expr::LambdaExprClass:
985 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +0000986
987 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000988 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +0000989 enterFullExpression(cleanups);
990 RunCleanupsScope Scope(*this);
991 return EmitLValue(cleanups->getSubExpr());
992 }
993
Anders Carlsson52ce3bb2009-11-14 01:51:50 +0000994 case Expr::CXXDefaultArgExprClass:
995 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +0000996 case Expr::CXXDefaultInitExprClass: {
997 CXXDefaultInitExprScope Scope(*this);
998 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
999 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001000 case Expr::CXXTypeidExprClass:
1001 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001002
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001003 case Expr::ObjCMessageExprClass:
1004 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001005 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001006 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001007 case Expr::StmtExprClass:
1008 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001009 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001010 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001011 case Expr::ArraySubscriptExprClass:
1012 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001013 case Expr::OMPArraySectionExprClass:
1014 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001015 case Expr::ExtVectorElementExprClass:
1016 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001017 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001018 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001019 case Expr::CompoundLiteralExprClass:
1020 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001021 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001022 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001023 case Expr::BinaryConditionalOperatorClass:
1024 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001025 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001026 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001027 case Expr::OpaqueValueExprClass:
1028 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001029 case Expr::SubstNonTypeTemplateParmExprClass:
1030 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001031 case Expr::ImplicitCastExprClass:
1032 case Expr::CStyleCastExprClass:
1033 case Expr::CXXFunctionalCastExprClass:
1034 case Expr::CXXStaticCastExprClass:
1035 case Expr::CXXDynamicCastExprClass:
1036 case Expr::CXXReinterpretCastExprClass:
1037 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001038 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001039 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001040
Douglas Gregorfe314812011-06-21 17:03:29 +00001041 case Expr::MaterializeTemporaryExprClass:
1042 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001043 }
1044}
1045
John McCall71335052012-03-10 03:05:10 +00001046/// Given an object of the given canonical type, can we safely copy a
1047/// value out of it based on its initializer?
1048static bool isConstantEmittableObjectType(QualType type) {
1049 assert(type.isCanonical());
1050 assert(!type->isReferenceType());
1051
1052 // Must be const-qualified but non-volatile.
1053 Qualifiers qs = type.getLocalQualifiers();
1054 if (!qs.hasConst() || qs.hasVolatile()) return false;
1055
1056 // Otherwise, all object types satisfy this except C++ classes with
1057 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001058 if (const auto *RT = dyn_cast<RecordType>(type))
1059 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001060 if (RD->hasMutableFields() || !RD->isTrivial())
1061 return false;
1062
1063 return true;
1064}
1065
1066/// Can we constant-emit a load of a reference to a variable of the
1067/// given type? This is different from predicates like
1068/// Decl::isUsableInConstantExpressions because we do want it to apply
1069/// in situations that don't necessarily satisfy the language's rules
1070/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1071/// to do this with const float variables even if those variables
1072/// aren't marked 'constexpr'.
1073enum ConstantEmissionKind {
1074 CEK_None,
1075 CEK_AsReferenceOnly,
1076 CEK_AsValueOrReference,
1077 CEK_AsValueOnly
1078};
1079static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1080 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001081 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001082 if (isConstantEmittableObjectType(ref->getPointeeType()))
1083 return CEK_AsValueOrReference;
1084 return CEK_AsReferenceOnly;
1085 }
1086 if (isConstantEmittableObjectType(type))
1087 return CEK_AsValueOnly;
1088 return CEK_None;
1089}
1090
1091/// Try to emit a reference to the given value without producing it as
1092/// an l-value. This is actually more than an optimization: we can't
1093/// produce an l-value for variables that we never actually captured
1094/// in a block or lambda, which means const int variables or constexpr
1095/// literals or similar.
1096CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001097CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1098 ValueDecl *value = refExpr->getDecl();
1099
John McCall71335052012-03-10 03:05:10 +00001100 // The value needs to be an enum constant or a constant variable.
1101 ConstantEmissionKind CEK;
1102 if (isa<ParmVarDecl>(value)) {
1103 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001104 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001105 CEK = checkVarTypeForConstantEmission(var->getType());
1106 } else if (isa<EnumConstantDecl>(value)) {
1107 CEK = CEK_AsValueOnly;
1108 } else {
1109 CEK = CEK_None;
1110 }
1111 if (CEK == CEK_None) return ConstantEmission();
1112
John McCall71335052012-03-10 03:05:10 +00001113 Expr::EvalResult result;
1114 bool resultIsReference;
1115 QualType resultType;
1116
1117 // It's best to evaluate all the way as an r-value if that's permitted.
1118 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001119 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001120 resultIsReference = false;
1121 resultType = refExpr->getType();
1122
1123 // Otherwise, try to evaluate as an l-value.
1124 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001125 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001126 resultIsReference = true;
1127 resultType = value->getType();
1128
1129 // Failure.
1130 } else {
1131 return ConstantEmission();
1132 }
1133
1134 // In any case, if the initializer has side-effects, abandon ship.
1135 if (result.HasSideEffects)
1136 return ConstantEmission();
1137
1138 // Emit as a constant.
1139 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1140
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001141 // Make sure we emit a debug reference to the global variable.
1142 // This should probably fire even for
1143 if (isa<VarDecl>(value)) {
1144 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1145 EmitDeclRefExprDbgValue(refExpr, C);
1146 } else {
1147 assert(isa<EnumConstantDecl>(value));
1148 EmitDeclRefExprDbgValue(refExpr, C);
1149 }
John McCall71335052012-03-10 03:05:10 +00001150
1151 // If we emitted a reference constant, we need to dereference that.
1152 if (resultIsReference)
1153 return ConstantEmission::forReference(C);
1154
1155 return ConstantEmission::forValue(C);
1156}
1157
Nick Lewycky2d84e842013-10-02 02:29:49 +00001158llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1159 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +00001160 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001161 lvalue.getType(), Loc, lvalue.getAlignmentSource(),
1162 lvalue.getTBAAInfo(),
Manman Renc451e572013-04-04 21:53:22 +00001163 lvalue.getTBAABaseType(), lvalue.getTBAAOffset());
John McCall1553b192011-06-16 04:16:24 +00001164}
1165
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001166static bool hasBooleanRepresentation(QualType Ty) {
1167 if (Ty->isBooleanType())
1168 return true;
1169
1170 if (const EnumType *ET = Ty->getAs<EnumType>())
1171 return ET->getDecl()->getIntegerType()->isBooleanType();
1172
Douglas Gregor298f43d2012-04-12 20:42:30 +00001173 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1174 return hasBooleanRepresentation(AT->getValueType());
1175
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001176 return false;
1177}
1178
Richard Smith1629da92012-12-13 07:11:50 +00001179static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1180 llvm::APInt &Min, llvm::APInt &End,
1181 bool StrictEnums) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001182 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001183 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1184 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001185 bool IsBool = hasBooleanRepresentation(Ty);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001186 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001187 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001188
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001189 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001190 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1191 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001192 } else {
1193 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001194 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001195 unsigned Bitwidth = LTy->getScalarSizeInBits();
1196 unsigned NumNegativeBits = ED->getNumNegativeBits();
1197 unsigned NumPositiveBits = ED->getNumPositiveBits();
1198
1199 if (NumNegativeBits) {
1200 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1201 assert(NumBits <= Bitwidth);
1202 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1203 Min = -End;
1204 } else {
1205 assert(NumPositiveBits <= Bitwidth);
1206 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1207 Min = llvm::APInt(Bitwidth, 0);
1208 }
1209 }
Richard Smith1629da92012-12-13 07:11:50 +00001210 return true;
1211}
1212
1213llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1214 llvm::APInt Min, End;
1215 if (!getRangeForType(*this, Ty, Min, End,
1216 CGM.getCodeGenOpts().StrictEnums))
Craig Topper8a13c412014-05-21 05:09:00 +00001217 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001218
Duncan Sandsc720e782012-04-15 18:04:54 +00001219 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001220 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001221}
1222
John McCall7f416cc2015-09-08 08:05:57 +00001223llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1224 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001225 SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +00001226 AlignmentSource AlignSource,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001227 llvm::MDNode *TBAAInfo,
1228 QualType TBAABaseType,
1229 uint64_t TBAAOffset) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001230 // For better performance, handle vector loads differently.
1231 if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001232 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001233
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001234 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001235
John McCall7f416cc2015-09-08 08:05:57 +00001236 // Handle vectors of size 3 like size 4 for better performance.
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001237 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001238
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001239 // Bitcast to vec4 type.
1240 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
1241 4);
John McCall7f416cc2015-09-08 08:05:57 +00001242 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001243 // Now load value.
John McCall7f416cc2015-09-08 08:05:57 +00001244 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001245
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001246 // Shuffle vector to get vec3.
John McCall7f416cc2015-09-08 08:05:57 +00001247 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
Benjamin Kramer99383102015-07-28 16:25:32 +00001248 {0, 1, 2}, "extractVec");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001249 return EmitFromMemory(V, Ty);
1250 }
1251 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001252
1253 // Atomic operations have to be done on integral types.
David Majnemera5b195a2015-02-14 01:35:12 +00001254 if (Ty->isAtomicType() || typeIsSuitableForInlineAtomic(Ty, Volatile)) {
John McCall7f416cc2015-09-08 08:05:57 +00001255 LValue lvalue =
1256 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
David Majnemereeaec262015-02-14 02:18:14 +00001257 return EmitAtomicLoad(lvalue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001258 }
Craig Topper99e79272013-07-26 05:59:26 +00001259
John McCall7f416cc2015-09-08 08:05:57 +00001260 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Manman Renc451e572013-04-04 21:53:22 +00001261 if (TBAAInfo) {
1262 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1263 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001264 if (TBAAPath)
1265 CGM.DecorateInstruction(Load, TBAAPath, false/*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001266 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001267
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00001268 bool NeedsBoolCheck =
1269 SanOpts.has(SanitizerKind::Bool) && hasBooleanRepresentation(Ty);
1270 bool NeedsEnumCheck =
1271 SanOpts.has(SanitizerKind::Enum) && Ty->getAs<EnumType>();
1272 if (NeedsBoolCheck || NeedsEnumCheck) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00001273 SanitizerScope SanScope(this);
Richard Smith1629da92012-12-13 07:11:50 +00001274 llvm::APInt Min, End;
1275 if (getRangeForType(*this, Ty, Min, End, true)) {
1276 --End;
1277 llvm::Value *Check;
1278 if (!Min)
1279 Check = Builder.CreateICmpULE(
1280 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1281 else {
1282 llvm::Value *Upper = Builder.CreateICmpSLE(
1283 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1284 llvm::Value *Lower = Builder.CreateICmpSGE(
1285 Load, llvm::ConstantInt::get(getLLVMContext(), Min));
1286 Check = Builder.CreateAnd(Upper, Lower);
1287 }
Nick Lewycky2d84e842013-10-02 02:29:49 +00001288 llvm::Constant *StaticArgs[] = {
1289 EmitCheckSourceLocation(Loc),
1290 EmitCheckTypeDescriptor(Ty)
1291 };
Peter Collingbourne3eea6772015-05-11 21:39:14 +00001292 SanitizerMask Kind = NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
Alexey Samsonove396bfc2014-11-11 22:03:54 +00001293 EmitCheck(std::make_pair(Check, Kind), "load_invalid_value", StaticArgs,
1294 EmitCheckValue(Load));
Richard Smith1629da92012-12-13 07:11:50 +00001295 }
1296 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001297 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1298 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001299
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001300 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001301}
1302
John McCall3a7f6922010-10-27 20:58:56 +00001303llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1304 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001305 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001306 // This should really always be an i1, but sometimes it's already
1307 // an i8, and it's awkward to track those cases down.
1308 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001309 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1310 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1311 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001312 }
1313
1314 return Value;
1315}
1316
1317llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1318 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001319 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001320 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1321 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001322 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1323 }
1324
1325 return Value;
1326}
1327
John McCall7f416cc2015-09-08 08:05:57 +00001328void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1329 bool Volatile, QualType Ty,
1330 AlignmentSource AlignSource,
1331 llvm::MDNode *TBAAInfo,
Manman Renc451e572013-04-04 21:53:22 +00001332 bool isInit, QualType TBAABaseType,
1333 uint64_t TBAAOffset) {
Craig Topper99e79272013-07-26 05:59:26 +00001334
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001335 // Handle vectors differently to get better performance.
1336 if (Ty->isVectorType()) {
1337 llvm::Type *SrcTy = Value->getType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001338 auto *VecTy = cast<llvm::VectorType>(SrcTy);
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001339 // Handle vec3 special.
1340 if (VecTy->getNumElements() == 3) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001341 // Our source is a vec3, do a shuffle vector to make it a vec4.
Benjamin Kramer99383102015-07-28 16:25:32 +00001342 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1343 Builder.getInt32(2),
1344 llvm::UndefValue::get(Builder.getInt32Ty())};
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001345 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1346 Value = Builder.CreateShuffleVector(Value,
1347 llvm::UndefValue::get(VecTy),
1348 MaskV, "extractVec");
1349 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1350 }
John McCall7f416cc2015-09-08 08:05:57 +00001351 if (Addr.getElementType() != SrcTy) {
1352 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001353 }
1354 }
Craig Topper99e79272013-07-26 05:59:26 +00001355
John McCall3a7f6922010-10-27 20:58:56 +00001356 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001357
David Majnemera5b195a2015-02-14 01:35:12 +00001358 if (Ty->isAtomicType() ||
1359 (!isInit && typeIsSuitableForInlineAtomic(Ty, Volatile))) {
John McCalla8ec7eb2013-03-07 21:37:17 +00001360 EmitAtomicStore(RValue::get(Value),
John McCall7f416cc2015-09-08 08:05:57 +00001361 LValue::MakeAddr(Addr, Ty, getContext(),
1362 AlignSource, TBAAInfo),
John McCalla8ec7eb2013-03-07 21:37:17 +00001363 isInit);
1364 return;
1365 }
1366
Daniel Dunbar03816342010-08-21 02:24:36 +00001367 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Manman Renc451e572013-04-04 21:53:22 +00001368 if (TBAAInfo) {
1369 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1370 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001371 if (TBAAPath)
1372 CGM.DecorateInstruction(Store, TBAAPath, false/*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001373 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001374}
1375
David Chisnallfa35df62012-01-16 17:27:18 +00001376void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001377 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001378 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001379 lvalue.getType(), lvalue.getAlignmentSource(),
Manman Renc451e572013-04-04 21:53:22 +00001380 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
1381 lvalue.getTBAAOffset());
John McCall1553b192011-06-16 04:16:24 +00001382}
1383
Mike Stump4a3999f2009-09-09 13:00:44 +00001384/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1385/// method emits the address of the lvalue, then loads the result as an rvalue,
1386/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001387RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001388 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001389 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001390 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001391 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1392 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001393 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001394 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1395 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1396 Object = EmitObjCConsumeObject(LV.getType(), Object);
1397 return RValue::get(Object);
1398 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001399
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001400 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001401 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001402
John McCalla1dee5302010-08-22 10:59:02 +00001403 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001404 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001405 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001406
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001407 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001408 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001409 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001410 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001411 "vecext"));
1412 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001413
1414 // If this is a reference to a subset of the elements of a vector, either
1415 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001416 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001417 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001418
Renato Golin230c5eb2014-05-19 18:15:42 +00001419 // Global Register variables always invoke intrinsics
1420 if (LV.isGlobalReg())
1421 return EmitLoadOfGlobalRegLValue(LV);
1422
John McCallc109a252011-11-07 03:59:57 +00001423 assert(LV.isBitField() && "Unknown LValue type!");
1424 return EmitLoadOfBitfieldLValue(LV);
Chris Lattner8394d792007-06-05 20:53:16 +00001425}
1426
John McCall55e1fbc2011-06-25 02:11:03 +00001427RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001428 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001429
Daniel Dunbar3447a022010-04-13 23:34:15 +00001430 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001431 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001432
John McCall7f416cc2015-09-08 08:05:57 +00001433 Address Ptr = LV.getBitFieldAddress();
1434 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001435
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001436 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001437 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001438 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1439 if (HighBits)
1440 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1441 if (Info.Offset + HighBits)
1442 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1443 } else {
1444 if (Info.Offset)
1445 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001446 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001447 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1448 Info.Size),
1449 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001450 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001451 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001452
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001453 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001454}
1455
Nate Begemanb699c9b2009-01-18 06:42:49 +00001456// If this is a reference to a subset of the elements of a vector, create an
1457// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001458RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001459 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1460 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001461
Nate Begemanf322eab2008-05-09 06:41:27 +00001462 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001463
1464 // If the result of the expression is a non-vector type, we must be extracting
1465 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001466 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001467 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001468 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001469 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001470 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001471 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001472
1473 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001474 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001475
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001476 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001477 for (unsigned i = 0; i != NumResultElts; ++i)
1478 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001479
Chris Lattner91c08ad2011-02-15 00:14:06 +00001480 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1481 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001482 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001483 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001484}
1485
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001486/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001487Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1488 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001489 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1490 QualType EQT = ExprVT->getElementType();
1491 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001492
John McCall7f416cc2015-09-08 08:05:57 +00001493 Address CastToPointerElement =
1494 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1495 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001496
1497 const llvm::Constant *Elts = LV.getExtVectorElts();
1498 unsigned ix = getAccessedFieldNo(0, Elts);
1499
John McCall7f416cc2015-09-08 08:05:57 +00001500 Address VectorBasePtrPlusIx =
1501 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1502 getContext().getTypeSizeInChars(EQT),
1503 "vector.elt");
1504
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001505 return VectorBasePtrPlusIx;
1506}
1507
Renato Golin230c5eb2014-05-19 18:15:42 +00001508/// @brief Load of global gamed gegisters are always calls to intrinsics.
1509RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001510 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1511 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001512 llvm::MDNode *RegName = cast<llvm::MDNode>(
1513 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001514
1515 // We accept integer and pointer types only
1516 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1517 llvm::Type *Ty = OrigTy;
1518 if (OrigTy->isPointerTy())
1519 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1520 llvm::Type *Types[] = { Ty };
1521
Renato Golin230c5eb2014-05-19 18:15:42 +00001522 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001523 llvm::Value *Call = Builder.CreateCall(
1524 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001525 if (OrigTy->isPointerTy())
1526 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001527 return RValue::get(Call);
1528}
Chris Lattner40ff7012007-08-03 16:18:34 +00001529
Chris Lattner9369a562007-06-29 16:31:29 +00001530
Chris Lattner8394d792007-06-05 20:53:16 +00001531/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1532/// lvalue, where both are guaranteed to the have the same type, and that type
1533/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001534void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001535 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001536 if (!Dst.isSimple()) {
1537 if (Dst.isVectorElt()) {
1538 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001539 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1540 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001541 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001542 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001543 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1544 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001545 return;
1546 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001547
Nate Begemance4d7fc2008-04-18 23:10:10 +00001548 // If this is an update of extended vector elements, insert them as
1549 // appropriate.
1550 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001551 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001552
Renato Golin230c5eb2014-05-19 18:15:42 +00001553 if (Dst.isGlobalReg())
1554 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1555
John McCallc109a252011-11-07 03:59:57 +00001556 assert(Dst.isBitField() && "Unknown LValue type");
1557 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001558 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001559
John McCall31168b02011-06-15 23:02:42 +00001560 // There's special magic for assigning into an ARC-qualified l-value.
1561 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1562 switch (Lifetime) {
1563 case Qualifiers::OCL_None:
1564 llvm_unreachable("present but none");
1565
1566 case Qualifiers::OCL_ExplicitNone:
1567 // nothing special
1568 break;
1569
1570 case Qualifiers::OCL_Strong:
John McCall55e1fbc2011-06-25 02:11:03 +00001571 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001572 return;
1573
1574 case Qualifiers::OCL_Weak:
1575 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1576 return;
1577
1578 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001579 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1580 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001581 // fall into the normal path
1582 break;
1583 }
1584 }
1585
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001586 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001587 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001588 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001589 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001590 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001591 return;
1592 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001593
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001594 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001595 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001596 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001597 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001598 if (Dst.isObjCIvar()) {
1599 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001600 llvm::Type *ResultType = IntPtrTy;
1601 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1602 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001603 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001604 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001605 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1606 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001607 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001608 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001609 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001610 } else if (Dst.isGlobalObjCRef()) {
1611 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1612 Dst.isThreadLocalRef());
1613 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001614 else
1615 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001616 return;
1617 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001618
Chris Lattner6278e6a2007-08-11 00:04:45 +00001619 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001620 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001621}
1622
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001623void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001624 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001625 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001626 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001627 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001628
Daniel Dunbar67aba792010-04-15 03:47:33 +00001629 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001630 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001631
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001632 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001633 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001634 /*IsSigned=*/false);
1635 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001636
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001637 // See if there are other bits in the bitfield's storage we'll need to load
1638 // and mask together with source before storing.
1639 if (Info.StorageSize != Info.Size) {
1640 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001641 llvm::Value *Val =
1642 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001643
1644 // Mask the source value as needed.
1645 if (!hasBooleanRepresentation(Dst.getType()))
1646 SrcVal = Builder.CreateAnd(SrcVal,
1647 llvm::APInt::getLowBitsSet(Info.StorageSize,
1648 Info.Size),
1649 "bf.value");
1650 MaskedVal = SrcVal;
1651 if (Info.Offset)
1652 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1653
1654 // Mask out the original value.
1655 Val = Builder.CreateAnd(Val,
1656 ~llvm::APInt::getBitsSet(Info.StorageSize,
1657 Info.Offset,
1658 Info.Offset + Info.Size),
1659 "bf.clear");
1660
1661 // Or together the unchanged values and the source value.
1662 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1663 } else {
1664 assert(Info.Offset == 0);
1665 }
1666
1667 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001668 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001669
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001670 // Return the new value of the bit-field, if requested.
1671 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001672 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001673
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001674 // Sign extend the value if needed.
1675 if (Info.IsSigned) {
1676 assert(Info.Size <= Info.StorageSize);
1677 unsigned HighBits = Info.StorageSize - Info.Size;
1678 if (HighBits) {
1679 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1680 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1681 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001682 }
1683
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001684 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1685 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001686 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001687 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001688}
1689
Nate Begemance4d7fc2008-04-18 23:10:10 +00001690void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001691 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001692 // This access turns into a read/modify/write of the vector. Load the input
1693 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001694 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1695 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001696 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001697
Chris Lattner4647a212007-08-31 22:49:20 +00001698 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001699
John McCall55e1fbc2011-06-25 02:11:03 +00001700 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001701 unsigned NumSrcElts = VTy->getNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001702 unsigned NumDstElts =
1703 cast<llvm::VectorType>(Vec->getType())->getNumElements();
1704 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001705 // Use shuffle vector is the src and destination are the same number of
1706 // elements and restore the vector mask since it is on the side it will be
1707 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001708 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001709 for (unsigned i = 0; i != NumSrcElts; ++i)
1710 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001711
Chris Lattner91c08ad2011-02-15 00:14:06 +00001712 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001713 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001714 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001715 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001716 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001717 // Extended the source vector to the same length and then shuffle it
1718 // into the destination.
1719 // FIXME: since we're shuffling with undef, can we just use the indices
1720 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001721 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001722 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001723 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001724 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001725 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001726 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001727 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001728 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001729 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001730 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001731 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001732 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001733 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001734
Joey Goulycf4143b2013-11-21 17:09:05 +00001735 // When the vector size is odd and .odd or .hi is used, the last element
1736 // of the Elts constant array will be one past the size of the vector.
1737 // Ignore the last element here, if it is greater than the mask size.
1738 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1739 NumSrcElts--;
1740
Nate Begemanb699c9b2009-01-18 06:42:49 +00001741 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001742 for (unsigned i = 0; i != NumSrcElts; ++i)
1743 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001744 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001745 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001746 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001747 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001748 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001749 }
1750 } else {
1751 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001752 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001753 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001754 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001755 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001756
John McCall7f416cc2015-09-08 08:05:57 +00001757 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1758 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001759}
1760
Renato Golin230c5eb2014-05-19 18:15:42 +00001761/// @brief Store of global named registers are always calls to intrinsics.
1762void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001763 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1764 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001765 llvm::MDNode *RegName = cast<llvm::MDNode>(
1766 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00001767 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00001768
1769 // We accept integer and pointer types only
1770 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1771 llvm::Type *Ty = OrigTy;
1772 if (OrigTy->isPointerTy())
1773 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1774 llvm::Type *Types[] = { Ty };
1775
Renato Golin230c5eb2014-05-19 18:15:42 +00001776 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1777 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00001778 if (OrigTy->isPointerTy())
1779 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00001780 Builder.CreateCall(
1781 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00001782}
1783
Eric Christopherc9e2a682014-05-20 17:10:39 +00001784// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001785// generating write-barries API. It is currently a global, ivar,
1786// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001787static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001788 LValue &LV,
1789 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001790 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001791 return;
Craig Topper99e79272013-07-26 05:59:26 +00001792
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001793 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001794 QualType ExpTy = E->getType();
1795 if (IsMemberAccess && ExpTy->isPointerType()) {
1796 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00001797 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001798 // writer-barrier conservatively.
1799 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1800 if (ExpTy->isRecordType()) {
1801 LV.setObjCIvar(false);
1802 return;
1803 }
1804 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001805 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001806 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001807 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001808 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001809 return;
1810 }
Craig Topper99e79272013-07-26 05:59:26 +00001811
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001812 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1813 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001814 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001815 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00001816 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001817 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001818 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001819 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001820 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001821 }
Craig Topper99e79272013-07-26 05:59:26 +00001822
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001823 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001824 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001825 return;
1826 }
Craig Topper99e79272013-07-26 05:59:26 +00001827
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001828 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001829 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001830 if (LV.isObjCIvar()) {
1831 // If cast is to a structure pointer, follow gcc's behavior and make it
1832 // a non-ivar write-barrier.
1833 QualType ExpTy = E->getType();
1834 if (ExpTy->isPointerType())
1835 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1836 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00001837 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001838 }
1839 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001840 }
Peter Collingbourne91147592011-04-15 00:35:48 +00001841
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001842 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001843 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1844 return;
1845 }
1846
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001847 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001848 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001849 return;
1850 }
Craig Topper99e79272013-07-26 05:59:26 +00001851
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001852 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001853 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001854 return;
1855 }
John McCall31168b02011-06-15 23:02:42 +00001856
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001857 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001858 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00001859 return;
1860 }
1861
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001862 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001863 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00001864 if (LV.isObjCIvar() && !LV.isObjCArray())
1865 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001866 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00001867 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001868 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00001869 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001870 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001871 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001872 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001873 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001874
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001875 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001876 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001877 // We don't know if member is an 'ivar', but this flag is looked at
1878 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001879 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001880 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001881 }
1882}
1883
Chris Lattner3f32d692011-07-12 06:52:18 +00001884static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00001885EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00001886 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001887 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00001888 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00001889 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00001890}
1891
Alexey Bataev97720002014-11-11 04:05:39 +00001892static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00001893 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
1894 llvm::Type *RealVarTy, SourceLocation Loc) {
1895 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
1896 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
1897 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
1898}
1899
1900Address CodeGenFunction::EmitLoadOfReference(Address Addr,
1901 const ReferenceType *RefTy,
1902 AlignmentSource *Source) {
1903 llvm::Value *Ptr = Builder.CreateLoad(Addr);
1904 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
1905 Source, /*forPointee*/ true));
1906
1907}
1908
1909LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
1910 const ReferenceType *RefTy) {
1911 AlignmentSource Source;
1912 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &Source);
1913 return MakeAddrLValue(Addr, RefTy->getPointeeType(), Source);
Alexey Bataev97720002014-11-11 04:05:39 +00001914}
1915
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001916static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1917 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00001918 QualType T = E->getType();
1919
1920 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00001921 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1922 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00001923 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
1924
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001925 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001926 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
1927 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00001928 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00001929 Address Addr(V, Alignment);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001930 LValue LV;
Alexey Bataev97720002014-11-11 04:05:39 +00001931 // Emit reference to the private copy of the variable if it is an OpenMP
1932 // threadprivate variable.
1933 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001934 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001935 E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001936 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
1937 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001938 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001939 LV = CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001940 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001941 setObjCGCLValueClass(CGF.getContext(), E, LV);
1942 return LV;
1943}
1944
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001945static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
Chris Lattner13ee4f42011-07-10 05:34:54 +00001946 const Expr *E, const FunctionDecl *FD) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00001947 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001948 if (!FD->hasPrototype()) {
1949 if (const FunctionProtoType *Proto =
1950 FD->getType()->getAs<FunctionProtoType>()) {
1951 // Ugly case: for a K&R-style definition, the type of the definition
1952 // isn't the same as the type of a use. Correct for this with a
1953 // bitcast.
1954 QualType NoProtoType =
Alp Toker314cc812014-01-25 16:55:45 +00001955 CGF.getContext().getFunctionNoProtoType(Proto->getReturnType());
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001956 NoProtoType = CGF.getContext().getPointerType(NoProtoType);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001957 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001958 }
1959 }
Eli Friedmana0544d62011-12-03 04:14:32 +00001960 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
John McCall7f416cc2015-09-08 08:05:57 +00001961 return CGF.MakeAddrLValue(V, E->getType(), Alignment, AlignmentSource::Decl);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001962}
1963
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00001964static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
1965 llvm::Value *ThisValue) {
1966 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
1967 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
1968 return CGF.EmitLValueForField(LV, FD);
1969}
1970
Renato Golin230c5eb2014-05-19 18:15:42 +00001971/// Named Registers are named metadata pointing to the register name
1972/// which will be read from/written to as an argument to the intrinsic
1973/// @llvm.read/write_register.
1974/// So far, only the name is being passed down, but other options such as
1975/// register type, allocation type or even optimization options could be
1976/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00001977static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00001978 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00001979 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00001980 assert(Asm->getLabel().size() < 64-Name.size() &&
1981 "Register name too big");
1982 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00001983 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00001984 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00001985 if (M->getNumOperands() == 0) {
1986 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
1987 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001988 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00001989 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
1990 }
John McCall7f416cc2015-09-08 08:05:57 +00001991
1992 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
1993
1994 llvm::Value *Ptr =
1995 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
1996 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00001997}
1998
Chris Lattnerd7f58862007-06-02 05:24:33 +00001999LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002000 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002001 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002002
Renato Goline7b3d5d2014-05-27 16:46:27 +00002003 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2004 // Global Named registers access via intrinsics only
2005 if (VD->getStorageClass() == SC_Register &&
2006 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002007 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002008
Renato Goline7b3d5d2014-05-27 16:46:27 +00002009 // A DeclRefExpr for a reference initialized by a constant expression can
2010 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002011 const Expr *Init = VD->getAnyInitializer(VD);
2012 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2013 VD->isUsableInConstantExpressions(getContext()) &&
2014 VD->checkInitIsICE()) {
2015 llvm::Constant *Val =
2016 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2017 assert(Val && "failed to emit reference constant expression");
2018 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002019
2020 // Should we be using the alignment of the constant pointer we emitted?
2021 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2022 /*pointee*/ true);
2023
2024 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
Richard Smith5a1104b2012-10-20 01:38:33 +00002025 }
David Majnemer602cfe72015-01-01 09:49:44 +00002026
2027 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002028 if (E->refersToEnclosingVariableOrCapture()) {
David Majnemer602cfe72015-01-01 09:49:44 +00002029 if (auto *FD = LambdaCaptureFields.lookup(VD))
2030 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2031 else if (CapturedStmtInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002032 auto it = LocalDeclMap.find(VD);
2033 if (it != LocalDeclMap.end()) {
2034 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2035 return EmitLoadOfReferenceLValue(it->second, RefTy);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002036 }
John McCall7f416cc2015-09-08 08:05:57 +00002037 return MakeAddrLValue(it->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002038 }
2039 return EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2040 CapturedStmtInfo->getContextValue());
David Majnemer602cfe72015-01-01 09:49:44 +00002041 }
John McCall7f416cc2015-09-08 08:05:57 +00002042
David Majnemer602cfe72015-01-01 09:49:44 +00002043 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002044 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2045 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002046 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002047 }
2048
Eli Friedman5720e342012-01-21 04:52:58 +00002049 // FIXME: We should be able to assert this for FunctionDecls as well!
2050 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2051 // those with a valid source location.
2052 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2053 !E->getLocation().isValid()) &&
2054 "Should not use decl without marking it used!");
2055
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002056 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002057 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002058 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2059 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002060 }
2061
Renato Goline7b3d5d2014-05-27 16:46:27 +00002062 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002063 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002064 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002065 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002066
John McCall7f416cc2015-09-08 08:05:57 +00002067 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002068
John McCall7f416cc2015-09-08 08:05:57 +00002069 // The variable should generally be present in the local decl map.
2070 auto iter = LocalDeclMap.find(VD);
2071 if (iter != LocalDeclMap.end()) {
2072 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002073
John McCall7f416cc2015-09-08 08:05:57 +00002074 // Otherwise, it might be static local we haven't emitted yet for
2075 // some reason; most likely, because it's in an outer function.
2076 } else if (VD->isStaticLocal()) {
2077 addr = Address(CGM.getOrCreateStaticVarDecl(
2078 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2079 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002080
John McCall7f416cc2015-09-08 08:05:57 +00002081 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002082 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002083 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2084 }
2085
2086
2087 // Check for OpenMP threadprivate variables.
2088 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2089 return EmitThreadPrivateVarDeclLValue(
2090 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2091 E->getExprLoc());
2092 }
2093
2094 // Drill into block byref variables.
2095 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2096 if (isBlockByref) {
2097 addr = emitBlockByrefAddress(addr, VD);
2098 }
2099
2100 // Drill into reference types.
2101 LValue LV;
2102 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2103 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2104 } else {
2105 LV = MakeAddrLValue(addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002106 }
Chris Lattner3f32d692011-07-12 06:52:18 +00002107
John McCallcdda29c2013-03-13 03:10:54 +00002108 bool isLocalStorage = VD->hasLocalStorage();
2109
2110 bool NonGCable = isLocalStorage &&
2111 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002112 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002113 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002114 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002115 LV.setNonGC(true);
2116 }
John McCallcdda29c2013-03-13 03:10:54 +00002117
2118 bool isImpreciseLifetime =
2119 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2120 if (isImpreciseLifetime)
2121 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002122 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002123 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002124 }
John McCallf3a88602011-02-03 08:15:49 +00002125
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002126 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002127 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002128
David Blaikie83d382b2011-09-23 05:06:16 +00002129 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002130}
Chris Lattnere47e4402007-06-01 18:02:12 +00002131
Chris Lattner8394d792007-06-05 20:53:16 +00002132LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2133 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002134 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002135 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002136
Chris Lattner0f398c42008-07-26 22:37:01 +00002137 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002138 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002139 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002140 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002141 QualType T = E->getSubExpr()->getType()->getPointeeType();
2142 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002143
John McCall7f416cc2015-09-08 08:05:57 +00002144 AlignmentSource AlignSource;
2145 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &AlignSource);
2146 LValue LV = MakeAddrLValue(Addr, T, AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002147 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002148
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002149 // We should not generate __weak write barrier on indirect reference
2150 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2151 // But, we continue to generate __strong write barrier on indirect write
2152 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002153 if (getLangOpts().ObjC1 &&
2154 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002155 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002156 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002157 return LV;
2158 }
John McCalle3027922010-08-25 11:45:40 +00002159 case UO_Real:
2160 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002161 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002162 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002163
Richard Smith0b6b8e42012-02-18 20:53:32 +00002164 // __real is valid on scalars. This is a faster way of testing that.
2165 // __imag can only produce an rvalue on scalars.
2166 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002167 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002168 assert(E->getSubExpr()->getType()->isArithmeticType());
2169 return LV;
2170 }
2171
2172 assert(E->getSubExpr()->getType()->isAnyComplexType());
2173
John McCall7f416cc2015-09-08 08:05:57 +00002174 Address Component =
2175 (E->getOpcode() == UO_Real
2176 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2177 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
2178 return MakeAddrLValue(Component, ExprTy, LV.getAlignmentSource());
Chris Lattner595db862007-10-30 22:53:42 +00002179 }
John McCalle3027922010-08-25 11:45:40 +00002180 case UO_PreInc:
2181 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002182 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002183 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002184
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002185 if (E->getType()->isAnyComplexType())
2186 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2187 else
2188 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2189 return LV;
2190 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002191 }
Chris Lattner8394d792007-06-05 20:53:16 +00002192}
2193
Chris Lattner4347e3692007-06-06 04:54:52 +00002194LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002195 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
John McCall7f416cc2015-09-08 08:05:57 +00002196 E->getType(), AlignmentSource::Decl);
Chris Lattner4347e3692007-06-06 04:54:52 +00002197}
2198
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002199LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002200 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
John McCall7f416cc2015-09-08 08:05:57 +00002201 E->getType(), AlignmentSource::Decl);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002202}
2203
Mike Stump4a3999f2009-09-09 13:00:44 +00002204LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002205 auto SL = E->getFunctionName();
2206 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2207 StringRef FnName = CurFn->getName();
2208 if (FnName.startswith("\01"))
2209 FnName = FnName.substr(1);
2210 StringRef NameItems[] = {
2211 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2212 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002213 if (CurCodeDecl && isa<BlockDecl>(CurCodeDecl)) {
John McCall7f416cc2015-09-08 08:05:57 +00002214 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2215 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002216 }
Alexey Bataevec474782014-10-09 08:45:04 +00002217 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
John McCall7f416cc2015-09-08 08:05:57 +00002218 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002219}
2220
Richard Smithe30752c2012-10-09 19:52:38 +00002221/// Emit a type description suitable for use by a runtime sanitizer library. The
2222/// format of a type descriptor is
2223///
2224/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002225/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002226/// \endcode
2227///
Richard Smith683398a2012-10-09 23:55:19 +00002228/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2229/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002230llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002231 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002232 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002233 return C;
2234
Richard Smithe30752c2012-10-09 19:52:38 +00002235 uint16_t TypeKind = -1;
2236 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002237
Richard Smithe30752c2012-10-09 19:52:38 +00002238 if (T->isIntegerType()) {
2239 TypeKind = 0;
2240 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002241 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002242 } else if (T->isFloatingType()) {
2243 TypeKind = 1;
2244 TypeInfo = getContext().getTypeSize(T);
2245 }
2246
2247 // Format the type name as if for a diagnostic, including quotes and
2248 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002249 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002250 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2251 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002252 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002253 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002254
2255 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002256 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2257 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002258 };
2259 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2260
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002261 auto *GV = new llvm::GlobalVariable(
2262 CGM.getModule(), Descriptor->getType(),
2263 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Richard Smithe30752c2012-10-09 19:52:38 +00002264 GV->setUnnamedAddr(true);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002265 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002266
2267 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002268 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002269
Richard Smithe30752c2012-10-09 19:52:38 +00002270 return GV;
2271}
2272
2273llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2274 llvm::Type *TargetTy = IntPtrTy;
2275
Richard Smith48366f72013-03-22 00:47:07 +00002276 // Floating-point types which fit into intptr_t are bitcast to integers
2277 // and then passed directly (after zero-extension, if necessary).
2278 if (V->getType()->isFloatingPointTy()) {
2279 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2280 if (Bits <= TargetTy->getIntegerBitWidth())
2281 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2282 Bits));
2283 }
2284
Richard Smithe30752c2012-10-09 19:52:38 +00002285 // Integers which fit in intptr_t are zero-extended and passed directly.
2286 if (V->getType()->isIntegerTy() &&
2287 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2288 return Builder.CreateZExt(V, TargetTy);
2289
2290 // Pointers are passed directly, everything else is passed by address.
2291 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002292 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002293 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002294 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002295 }
2296 return Builder.CreatePtrToInt(V, TargetTy);
2297}
2298
2299/// \brief Emit a representation of a SourceLocation for passing to a handler
2300/// in a sanitizer runtime library. The format for this data is:
2301/// \code
2302/// struct SourceLocation {
2303/// const char *Filename;
2304/// int32_t Line, Column;
2305/// };
2306/// \endcode
2307/// For an invalid SourceLocation, the Filename pointer is null.
2308llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002309 llvm::Constant *Filename;
2310 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002311
Alexey Samsonov6c124142014-07-18 17:50:06 +00002312 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2313 if (PLoc.isValid()) {
2314 auto FilenameGV = CGM.GetAddrOfConstantCString(PLoc.getFilename(), ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002315 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2316 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2317 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002318 Line = PLoc.getLine();
2319 Column = PLoc.getColumn();
2320 } else {
2321 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2322 Line = Column = 0;
2323 }
2324
2325 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2326 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002327
2328 return llvm::ConstantStruct::getAnon(Data);
2329}
2330
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002331namespace {
2332/// \brief Specify under what conditions this check can be recovered
2333enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002334 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002335 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002336 /// Check supports recovering, runtime has both fatal (noreturn) and
2337 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002338 Recoverable,
2339 /// Runtime conditionally aborts, always need to support recovery.
2340 AlwaysRecoverable
2341};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002342}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002343
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002344static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2345 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002346 switch (Kind) {
2347 case SanitizerKind::Vptr:
2348 return CheckRecoverableKind::AlwaysRecoverable;
2349 case SanitizerKind::Return:
2350 case SanitizerKind::Unreachable:
2351 return CheckRecoverableKind::Unrecoverable;
2352 default:
2353 return CheckRecoverableKind::Recoverable;
2354 }
2355}
2356
Alexey Samsonov88459522015-01-12 22:39:12 +00002357static void emitCheckHandlerCall(CodeGenFunction &CGF,
2358 llvm::FunctionType *FnType,
2359 ArrayRef<llvm::Value *> FnArgs,
2360 StringRef CheckName,
2361 CheckRecoverableKind RecoverKind, bool IsFatal,
2362 llvm::BasicBlock *ContBB) {
2363 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2364 bool NeedsAbortSuffix =
2365 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2366 std::string FnName = ("__ubsan_handle_" + CheckName +
2367 (NeedsAbortSuffix ? "_abort" : "")).str();
2368 bool MayReturn =
2369 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2370
2371 llvm::AttrBuilder B;
2372 if (!MayReturn) {
2373 B.addAttribute(llvm::Attribute::NoReturn)
2374 .addAttribute(llvm::Attribute::NoUnwind);
2375 }
2376 B.addAttribute(llvm::Attribute::UWTable);
2377
2378 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2379 FnType, FnName,
2380 llvm::AttributeSet::get(CGF.getLLVMContext(),
2381 llvm::AttributeSet::FunctionIndex, B));
2382 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2383 if (!MayReturn) {
2384 HandlerCall->setDoesNotReturn();
2385 CGF.Builder.CreateUnreachable();
2386 } else {
2387 CGF.Builder.CreateBr(ContBB);
2388 }
2389}
2390
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002391void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002392 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002393 StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
2394 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002395 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002396 assert(Checked.size() > 0);
Alexey Samsonov88459522015-01-12 22:39:12 +00002397
2398 llvm::Value *FatalCond = nullptr;
2399 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002400 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002401 for (int i = 0, n = Checked.size(); i < n; ++i) {
2402 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002403 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002404 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002405 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2406 ? TrapCond
2407 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2408 ? RecoverableCond
2409 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002410 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2411 }
2412
Peter Collingbourne9881b782015-06-18 23:59:22 +00002413 if (TrapCond)
2414 EmitTrapCheck(TrapCond);
2415 if (!FatalCond && !RecoverableCond)
2416 return;
2417
Alexey Samsonov88459522015-01-12 22:39:12 +00002418 llvm::Value *JointCond;
2419 if (FatalCond && RecoverableCond)
2420 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2421 else
2422 JointCond = FatalCond ? FatalCond : RecoverableCond;
2423 assert(JointCond);
2424
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002425 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
2426 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002427#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002428 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002429 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002430 "All recoverable kinds in a single check must be same!");
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002431 assert(SanOpts.has(Checked[i].second));
2432 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002433#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002434
Richard Smith4d1458e2012-09-08 02:08:36 +00002435 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002436 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2437 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002438 // Give hint that we very much don't expect to execute the handler
2439 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2440 llvm::MDBuilder MDHelper(getLLVMContext());
2441 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2442 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002443 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002444
Alexey Samsonov88459522015-01-12 22:39:12 +00002445 // Emit handler arguments and create handler function type.
Richard Smithe30752c2012-10-09 19:52:38 +00002446 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002447 auto *InfoPtr =
Will Dietz450f1a12013-01-09 03:39:41 +00002448 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
Richard Smithe30752c2012-10-09 19:52:38 +00002449 llvm::GlobalVariable::PrivateLinkage, Info);
2450 InfoPtr->setUnnamedAddr(true);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002451 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
Richard Smithe30752c2012-10-09 19:52:38 +00002452
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002453 SmallVector<llvm::Value *, 4> Args;
2454 SmallVector<llvm::Type *, 4> ArgTypes;
Richard Smithe30752c2012-10-09 19:52:38 +00002455 Args.reserve(DynamicArgs.size() + 1);
2456 ArgTypes.reserve(DynamicArgs.size() + 1);
2457
2458 // Handler functions take an i8* pointing to the (handler-specific) static
2459 // information block, followed by a sequence of intptr_t arguments
2460 // representing operand values.
2461 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2462 ArgTypes.push_back(Int8PtrTy);
2463 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2464 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2465 ArgTypes.push_back(IntPtrTy);
2466 }
2467
2468 llvm::FunctionType *FnType =
2469 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002470
Alexey Samsonov88459522015-01-12 22:39:12 +00002471 if (!FatalCond || !RecoverableCond) {
2472 // Simple case: we need to generate a single handler call, either
2473 // fatal, or non-fatal.
2474 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind,
2475 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002476 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002477 // Emit two handler calls: first one for set of unrecoverable checks,
2478 // another one for recoverable.
2479 llvm::BasicBlock *NonFatalHandlerBB =
2480 createBasicBlock("non_fatal." + CheckName);
2481 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2482 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2483 EmitBlock(FatalHandlerBB);
2484 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, true,
2485 NonFatalHandlerBB);
2486 EmitBlock(NonFatalHandlerBB);
2487 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, false,
2488 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002489 }
Richard Smithe30752c2012-10-09 19:52:38 +00002490
Richard Smith4d1458e2012-09-08 02:08:36 +00002491 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002492}
2493
Chad Rosierae229d52013-01-29 23:31:22 +00002494void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00002495 llvm::BasicBlock *Cont = createBasicBlock("cont");
2496
2497 // If we're optimizing, collapse all calls to trap down to just one per
2498 // function to save on code size.
2499 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2500 TrapBB = createBasicBlock("trap");
2501 Builder.CreateCondBr(Checked, Cont, TrapBB);
2502 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002503 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00002504 TrapCall->setDoesNotReturn();
2505 TrapCall->setDoesNotThrow();
2506 Builder.CreateUnreachable();
2507 } else {
2508 Builder.CreateCondBr(Checked, Cont, TrapBB);
2509 }
2510
2511 EmitBlock(Cont);
2512}
2513
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002514llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00002515 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002516
2517 if (!CGM.getCodeGenOpts().TrapFuncName.empty())
2518 TrapCall->addAttribute(llvm::AttributeSet::FunctionIndex,
2519 "trap-func-name",
2520 CGM.getCodeGenOpts().TrapFuncName);
2521
2522 return TrapCall;
2523}
2524
John McCall7f416cc2015-09-08 08:05:57 +00002525Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
2526 AlignmentSource *AlignSource) {
2527 assert(E->getType()->isArrayType() &&
2528 "Array to pointer decay must have array source type!");
2529
2530 // Expressions of array type can't be bitfields or vector elements.
2531 LValue LV = EmitLValue(E);
2532 Address Addr = LV.getAddress();
2533 if (AlignSource) *AlignSource = LV.getAlignmentSource();
2534
2535 // If the array type was an incomplete type, we need to make sure
2536 // the decay ends up being the right type.
2537 llvm::Type *NewTy = ConvertType(E->getType());
2538 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2539
2540 // Note that VLA pointers are always decayed, so we don't need to do
2541 // anything here.
2542 if (!E->getType()->isVariableArrayType()) {
2543 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2544 "Expected pointer to array");
2545 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2546 }
2547
2548 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2549 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2550}
2551
Chris Lattner6c5abe82010-06-26 23:03:20 +00002552/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2553/// array to pointer, return the array subexpression.
2554static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2555 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002556 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00002557 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00002558 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002559
Chris Lattner6c5abe82010-06-26 23:03:20 +00002560 // If this is a decay from variable width array, bail out.
2561 const Expr *SubExpr = CE->getSubExpr();
2562 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00002563 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002564
Chris Lattner6c5abe82010-06-26 23:03:20 +00002565 return SubExpr;
2566}
2567
John McCall7f416cc2015-09-08 08:05:57 +00002568static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
2569 llvm::Value *ptr,
2570 ArrayRef<llvm::Value*> indices,
2571 bool inbounds,
2572 const llvm::Twine &name = "arrayidx") {
2573 if (inbounds) {
2574 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name);
2575 } else {
2576 return CGF.Builder.CreateGEP(ptr, indices, name);
2577 }
2578}
2579
2580static CharUnits getArrayElementAlign(CharUnits arrayAlign,
2581 llvm::Value *idx,
2582 CharUnits eltSize) {
2583 // If we have a constant index, we can use the exact offset of the
2584 // element we're accessing.
2585 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
2586 CharUnits offset = constantIdx->getZExtValue() * eltSize;
2587 return arrayAlign.alignmentAtOffset(offset);
2588
2589 // Otherwise, use the worst-case alignment for any element.
2590 } else {
2591 return arrayAlign.alignmentOfArrayElement(eltSize);
2592 }
2593}
2594
2595static QualType getFixedSizeElementType(const ASTContext &ctx,
2596 const VariableArrayType *vla) {
2597 QualType eltType;
2598 do {
2599 eltType = vla->getElementType();
2600 } while ((vla = ctx.getAsVariableArrayType(eltType)));
2601 return eltType;
2602}
2603
2604static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
2605 ArrayRef<llvm::Value*> indices,
2606 QualType eltType, bool inbounds,
2607 const llvm::Twine &name = "arrayidx") {
2608 // All the indices except that last must be zero.
2609#ifndef NDEBUG
2610 for (auto idx : indices.drop_back())
2611 assert(isa<llvm::ConstantInt>(idx) &&
2612 cast<llvm::ConstantInt>(idx)->isZero());
2613#endif
2614
2615 // Determine the element size of the statically-sized base. This is
2616 // the thing that the indices are expressed in terms of.
2617 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
2618 eltType = getFixedSizeElementType(CGF.getContext(), vla);
2619 }
2620
2621 // We can use that to compute the best alignment of the element.
2622 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
2623 CharUnits eltAlign =
2624 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
2625
2626 llvm::Value *eltPtr =
2627 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name);
2628 return Address(eltPtr, eltAlign);
2629}
2630
Richard Smith539e4a72013-02-23 02:53:19 +00002631LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2632 bool Accessed) {
Ted Kremenekc81614d2007-08-20 16:18:38 +00002633 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner2da04b32007-08-24 05:35:26 +00002634 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Eli Friedman07bbeca2009-06-06 19:09:26 +00002635 QualType IdxTy = E->getIdx()->getType();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002636 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Eli Friedman07bbeca2009-06-06 19:09:26 +00002637
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002638 if (SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00002639 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
2640
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002641 // If the base is a vector type, then we are forming a vector element lvalue
2642 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002643 if (E->getBase()->getType()->isVectorType() &&
2644 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002645 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00002646 LValue LHS = EmitLValue(E->getBase());
Ted Kremenekc81614d2007-08-20 16:18:38 +00002647 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Eli Friedman327944b2008-06-13 23:01:12 +00002648 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
John McCall7f416cc2015-09-08 08:05:57 +00002649 E->getBase()->getType(),
2650 LHS.getAlignmentSource());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002651 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002652
John McCall7f416cc2015-09-08 08:05:57 +00002653 // All the other cases basically behave like simple offsetting.
2654
Ted Kremenekc81614d2007-08-20 16:18:38 +00002655 // Extend or truncate the index type to 32 or 64-bits.
John McCalle3dc1702011-02-15 09:22:45 +00002656 if (Idx->getType() != IntPtrTy)
2657 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
Mike Stumpd9546382009-12-12 01:27:46 +00002658
John McCall7f416cc2015-09-08 08:05:57 +00002659 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002660 if (isa<ExtVectorElementExpr>(E->getBase())) {
2661 LValue LV = EmitLValue(E->getBase());
John McCall7f416cc2015-09-08 08:05:57 +00002662 Address Addr = EmitExtVectorElementLValue(LV);
2663
2664 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
2665 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true);
2666 return MakeAddrLValue(Addr, EltType, LV.getAlignmentSource());
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002667 }
John McCall7f416cc2015-09-08 08:05:57 +00002668
2669 AlignmentSource AlignSource;
2670 Address Addr = Address::invalid();
2671 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002672 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00002673 // The base must be a pointer, which is not an aggregate. Emit
2674 // it. It needs to be emitted first in case it's what captures
2675 // the VLA bounds.
John McCall7f416cc2015-09-08 08:05:57 +00002676 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00002677
John McCall23c29fe2011-06-24 21:55:10 +00002678 // The element count here is the total number of non-VLA elements.
2679 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00002680
John McCall77527a82011-06-25 01:32:37 +00002681 // Effectively, the multiply by the VLA size is part of the GEP.
2682 // GEP indexes are signed, and scaling an index isn't permitted to
2683 // signed-overflow, so we use the same semantics for our explicit
2684 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002685 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00002686 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00002687 } else {
2688 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00002689 }
John McCall7f416cc2015-09-08 08:05:57 +00002690
2691 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
2692 !getLangOpts().isSignedOverflowDefined());
2693
Chris Lattner6c5abe82010-06-26 23:03:20 +00002694 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
2695 // Indexing over an interface, as in "NSString *P; P[4];"
John McCall7f416cc2015-09-08 08:05:57 +00002696 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
2697 llvm::Value *InterfaceSizeVal =
2698 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());;
Mike Stump4a3999f2009-09-09 13:00:44 +00002699
John McCall7f416cc2015-09-08 08:05:57 +00002700 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002701
John McCall7f416cc2015-09-08 08:05:57 +00002702 // Emit the base pointer.
2703 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
2704
2705 // We don't necessarily build correct LLVM struct types for ObjC
2706 // interfaces, so we can't rely on GEP to do this scaling
2707 // correctly, so we need to cast to i8*. FIXME: is this actually
2708 // true? A lot of other things in the fragile ABI would break...
2709 llvm::Type *OrigBaseTy = Addr.getType();
2710 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
2711
2712 // Do the GEP.
2713 CharUnits EltAlign =
2714 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
2715 llvm::Value *EltPtr =
2716 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false);
2717 Addr = Address(EltPtr, EltAlign);
2718
2719 // Cast back.
2720 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00002721 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
2722 // If this is A[i] where A is an array, the frontend will have decayed the
2723 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
2724 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
2725 // "gep x, i" here. Emit one "gep A, 0, i".
2726 assert(Array->getType()->isArrayType() &&
2727 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00002728 LValue ArrayLV;
2729 // For simple multidimensional array indexing, set the 'accessed' flag for
2730 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002731 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00002732 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
2733 else
2734 ArrayLV = EmitLValue(Array);
Craig Topper99e79272013-07-26 05:59:26 +00002735
Daniel Dunbar82634272011-04-01 00:49:43 +00002736 // Propagate the alignment from the array itself to the result.
John McCall7f416cc2015-09-08 08:05:57 +00002737 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
2738 {CGM.getSize(CharUnits::Zero()), Idx},
2739 E->getType(),
2740 !getLangOpts().isSignedOverflowDefined());
2741 AlignSource = ArrayLV.getAlignmentSource();
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002742 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002743 // The base must be a pointer; emit it with an estimate of its alignment.
2744 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
2745 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
2746 !getLangOpts().isSignedOverflowDefined());
Anders Carlsson3d312f82008-12-21 00:11:23 +00002747 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002748
John McCall7f416cc2015-09-08 08:05:57 +00002749 LValue LV = MakeAddrLValue(Addr, E->getType(), AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00002750
John McCall7f416cc2015-09-08 08:05:57 +00002751 // TODO: Preserve/extend path TBAA metadata?
John McCall8ccfcb52009-09-24 19:53:00 +00002752
Richard Smith9c6890a2012-11-01 22:30:59 +00002753 if (getLangOpts().ObjC1 &&
2754 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00002755 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002756 setObjCGCLValueClass(getContext(), E, LV);
2757 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00002758 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00002759}
2760
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002761LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
2762 bool IsLowerBound) {
2763 LValue Base;
2764 if (auto *ASE =
2765 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
2766 Base = EmitOMPArraySectionExpr(ASE, IsLowerBound);
2767 else
2768 Base = EmitLValue(E->getBase());
2769 QualType BaseTy = Base.getType();
2770 llvm::Value *Idx = nullptr;
2771 QualType ResultExprTy;
2772 if (auto *AT = getContext().getAsArrayType(BaseTy))
2773 ResultExprTy = AT->getElementType();
2774 else
2775 ResultExprTy = BaseTy->getPointeeType();
2776 if (IsLowerBound || (!IsLowerBound && E->getColonLoc().isInvalid())) {
2777 // Requesting lower bound or upper bound, but without provided length and
2778 // without ':' symbol for the default length -> length = 1.
2779 // Idx = LowerBound ?: 0;
2780 if (auto *LowerBound = E->getLowerBound()) {
2781 Idx = Builder.CreateIntCast(
2782 EmitScalarExpr(LowerBound), IntPtrTy,
2783 LowerBound->getType()->hasSignedIntegerRepresentation());
2784 } else
2785 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
2786 } else {
2787 // Try to emit length or lower bound as constant. If this is possible, 1 is
2788 // subtracted from constant length or lower bound. Otherwise, emit LLVM IR
2789 // (LB + Len) - 1.
2790 auto &C = CGM.getContext();
2791 auto *Length = E->getLength();
2792 llvm::APSInt ConstLength;
2793 if (Length) {
2794 // Idx = LowerBound + Length - 1;
2795 if (Length->isIntegerConstantExpr(ConstLength, C)) {
2796 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
2797 Length = nullptr;
2798 }
2799 auto *LowerBound = E->getLowerBound();
2800 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
2801 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
2802 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
2803 LowerBound = nullptr;
2804 }
2805 if (!Length)
2806 --ConstLength;
2807 else if (!LowerBound)
2808 --ConstLowerBound;
2809
2810 if (Length || LowerBound) {
2811 auto *LowerBoundVal =
2812 LowerBound
2813 ? Builder.CreateIntCast(
2814 EmitScalarExpr(LowerBound), IntPtrTy,
2815 LowerBound->getType()->hasSignedIntegerRepresentation())
2816 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
2817 auto *LengthVal =
2818 Length
2819 ? Builder.CreateIntCast(
2820 EmitScalarExpr(Length), IntPtrTy,
2821 Length->getType()->hasSignedIntegerRepresentation())
2822 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
2823 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
2824 /*HasNUW=*/false,
2825 !getLangOpts().isSignedOverflowDefined());
2826 if (Length && LowerBound) {
2827 Idx = Builder.CreateSub(
2828 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
2829 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
2830 }
2831 } else
2832 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
2833 } else {
2834 // Idx = ArraySize - 1;
2835 if (auto *VAT = C.getAsVariableArrayType(BaseTy)) {
2836 Length = VAT->getSizeExpr();
2837 if (Length->isIntegerConstantExpr(ConstLength, C))
2838 Length = nullptr;
2839 } else {
2840 auto *CAT = C.getAsConstantArrayType(BaseTy);
2841 ConstLength = CAT->getSize();
2842 }
2843 if (Length) {
2844 auto *LengthVal = Builder.CreateIntCast(
2845 EmitScalarExpr(Length), IntPtrTy,
2846 Length->getType()->hasSignedIntegerRepresentation());
2847 Idx = Builder.CreateSub(
2848 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
2849 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
2850 } else {
2851 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
2852 --ConstLength;
2853 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
2854 }
2855 }
2856 }
2857 assert(Idx);
2858
John McCall7f416cc2015-09-08 08:05:57 +00002859 llvm::Value *EltPtr;
2860 QualType FixedSizeEltType = ResultExprTy;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002861 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
2862 // The element count here is the total number of non-VLA elements.
2863 llvm::Value *numElements = getVLASize(VLA).first;
John McCall7f416cc2015-09-08 08:05:57 +00002864 FixedSizeEltType = getFixedSizeElementType(getContext(), VLA);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002865
2866 // Effectively, the multiply by the VLA size is part of the GEP.
2867 // GEP indexes are signed, and scaling an index isn't permitted to
2868 // signed-overflow, so we use the same semantics for our explicit
2869 // multiply. We suppress this if overflow is not undefined behavior.
2870 if (getLangOpts().isSignedOverflowDefined()) {
2871 Idx = Builder.CreateMul(Idx, numElements);
John McCall7f416cc2015-09-08 08:05:57 +00002872 EltPtr = Builder.CreateGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002873 } else {
2874 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall7f416cc2015-09-08 08:05:57 +00002875 EltPtr = Builder.CreateInBoundsGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002876 }
2877 } else if (BaseTy->isConstantArrayType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002878 llvm::Value *ArrayPtr = Base.getPointer();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002879 llvm::Value *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
2880 llvm::Value *Args[] = {Zero, Idx};
2881
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002882 if (getLangOpts().isSignedOverflowDefined())
John McCall7f416cc2015-09-08 08:05:57 +00002883 EltPtr = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002884 else
John McCall7f416cc2015-09-08 08:05:57 +00002885 EltPtr = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002886 } else {
2887 // The base must be a pointer, which is not an aggregate. Emit it.
2888 if (getLangOpts().isSignedOverflowDefined())
John McCall7f416cc2015-09-08 08:05:57 +00002889 EltPtr = Builder.CreateGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002890 else
John McCall7f416cc2015-09-08 08:05:57 +00002891 EltPtr = Builder.CreateInBoundsGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002892 }
2893
John McCall7f416cc2015-09-08 08:05:57 +00002894 CharUnits EltAlign =
2895 Base.getAlignment().alignmentOfArrayElement(
2896 getContext().getTypeSizeInChars(FixedSizeEltType));
2897
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002898 // Limit the alignment to that of the result type.
John McCall7f416cc2015-09-08 08:05:57 +00002899 LValue LV = MakeAddrLValue(Address(EltPtr, EltAlign), ResultExprTy,
2900 Base.getAlignmentSource());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002901
2902 LV.getQuals().setAddressSpace(BaseTy.getAddressSpace());
2903
2904 return LV;
2905}
2906
Chris Lattner9e751ca2007-08-02 23:37:31 +00002907LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002908EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00002909 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00002910 LValue Base;
2911
2912 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00002913 if (E->isArrow()) {
2914 // If it is a pointer to a vector, emit the address and form an lvalue with
2915 // it.
John McCall7f416cc2015-09-08 08:05:57 +00002916 AlignmentSource AlignSource;
2917 Address Ptr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Chris Lattner4e1a3232009-12-23 21:31:11 +00002918 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
John McCall7f416cc2015-09-08 08:05:57 +00002919 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002920 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00002921 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00002922 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
2923 // emit the base as an lvalue.
2924 assert(E->getBase()->getType()->isVectorType());
2925 Base = EmitLValue(E->getBase());
2926 } else {
2927 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00002928 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00002929 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00002930 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00002931
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00002932 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00002933 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002934 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00002935 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
2936 AlignmentSource::Decl);
Chris Lattner4e1a3232009-12-23 21:31:11 +00002937 }
John McCall1553b192011-06-16 04:16:24 +00002938
2939 QualType type =
2940 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00002941
Nate Begemand3862152008-05-13 21:03:02 +00002942 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00002943 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00002944 E->getEncodedElementAccess(Indices);
2945
2946 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00002947 llvm::Constant *CV =
2948 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00002949 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
John McCall7f416cc2015-09-08 08:05:57 +00002950 Base.getAlignmentSource());
Nate Begemand3862152008-05-13 21:03:02 +00002951 }
2952 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
2953
2954 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002955 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00002956
Chris Lattner595ba3a2012-01-30 06:20:36 +00002957 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
2958 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00002959 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00002960 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
2961 Base.getAlignmentSource());
Chris Lattner9e751ca2007-08-02 23:37:31 +00002962}
2963
Devang Patel30efa2e2007-10-23 20:28:39 +00002964LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00002965 Expr *BaseExpr = E->getBase();
Eli Friedman327944b2008-06-13 23:01:12 +00002966
Chris Lattner4e4186b2007-12-02 18:52:07 +00002967 // 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 +00002968 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00002969 if (E->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00002970 AlignmentSource AlignSource;
2971 Address Addr = EmitPointerWithAlignment(BaseExpr, &AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00002972 QualType PtrTy = BaseExpr->getType()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00002973 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy);
2974 BaseLV = MakeAddrLValue(Addr, PtrTy, AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00002975 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00002976 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00002977
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002978 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002979 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00002980 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002981 setObjCGCLValueClass(getContext(), E, LV);
2982 return LV;
2983 }
Craig Topper99e79272013-07-26 05:59:26 +00002984
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002985 if (auto *VD = dyn_cast<VarDecl>(ND))
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00002986 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002987
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002988 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002989 return EmitFunctionDeclLValue(*this, E, FD);
2990
David Blaikie83d382b2011-09-23 05:06:16 +00002991 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00002992}
Devang Patel30efa2e2007-10-23 20:28:39 +00002993
John McCalldec348f72013-05-03 07:33:41 +00002994/// Given that we are currently emitting a lambda, emit an l-value for
2995/// one of its members.
2996LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
2997 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
2998 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
2999 QualType LambdaTagType =
3000 getContext().getTagDeclType(Field->getParent());
3001 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3002 return EmitLValueForField(LambdaLV, Field);
3003}
3004
John McCall7f416cc2015-09-08 08:05:57 +00003005/// Drill down to the storage of a field without walking into
3006/// reference types.
3007///
3008/// The resulting address doesn't necessarily have the right type.
3009static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3010 const FieldDecl *field) {
3011 const RecordDecl *rec = field->getParent();
3012
3013 unsigned idx =
3014 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3015
3016 CharUnits offset;
3017 // Adjust the alignment down to the given offset.
3018 // As a special case, if the LLVM field index is 0, we know that this
3019 // is zero.
3020 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3021 .getFieldOffset(field->getFieldIndex()) == 0) &&
3022 "LLVM field at index zero had non-zero offset?");
3023 if (idx != 0) {
3024 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3025 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3026 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3027 }
3028
3029 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3030}
3031
Eli Friedman7f1ff602012-04-16 03:54:45 +00003032LValue CodeGenFunction::EmitLValueForField(LValue base,
3033 const FieldDecl *field) {
John McCall7f416cc2015-09-08 08:05:57 +00003034 AlignmentSource fieldAlignSource =
3035 getFieldAlignmentSource(base.getAlignmentSource());
3036
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003037 if (field->isBitField()) {
3038 const CGRecordLayout &RL =
3039 CGM.getTypes().getCGRecordLayout(field->getParent());
3040 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003041 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003042 unsigned Idx = RL.getLLVMFieldNo(field);
3043 if (Idx != 0)
3044 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003045 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3046 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003047 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003048 llvm::Type *FieldIntTy =
3049 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3050 if (Addr.getElementType() != FieldIntTy)
3051 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003052
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003053 QualType fieldType =
3054 field->getType().withCVRQualifiers(base.getVRQualifiers());
John McCall7f416cc2015-09-08 08:05:57 +00003055 return LValue::MakeBitfield(Addr, Info, fieldType, fieldAlignSource);
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003056 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003057
John McCall53fcbd22011-02-26 08:07:02 +00003058 const RecordDecl *rec = field->getParent();
3059 QualType type = field->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003060
John McCall53fcbd22011-02-26 08:07:02 +00003061 bool mayAlias = rec->hasAttr<MayAliasAttr>();
3062
John McCall7f416cc2015-09-08 08:05:57 +00003063 Address addr = base.getAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003064 unsigned cvr = base.getVRQualifiers();
Manman Renc451e572013-04-04 21:53:22 +00003065 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
John McCall53fcbd22011-02-26 08:07:02 +00003066 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003067 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00003068 assert(!type->isReferenceType() && "union has reference member");
Manman Renc451e572013-04-04 21:53:22 +00003069 // TODO: handle path-aware TBAA for union.
3070 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003071 } else {
3072 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003073 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003074
3075 // If this is a reference field, load the reference right now.
3076 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3077 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3078 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3079
Manman Renc451e572013-04-04 21:53:22 +00003080 // Loading the reference will disable path-aware TBAA.
3081 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003082 if (CGM.shouldUseTBAA()) {
3083 llvm::MDNode *tbaa;
3084 if (mayAlias)
3085 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3086 else
3087 tbaa = CGM.getTBAAInfo(type);
Manman Ren4f755de2013-10-08 00:08:49 +00003088 if (tbaa)
3089 CGM.DecorateInstruction(load, tbaa);
John McCall53fcbd22011-02-26 08:07:02 +00003090 }
3091
John McCall53fcbd22011-02-26 08:07:02 +00003092 mayAlias = false;
3093 type = refType->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003094
3095 CharUnits alignment =
3096 getNaturalTypeAlignment(type, &fieldAlignSource, /*pointee*/ true);
3097 addr = Address(load, alignment);
3098
3099 // Qualifiers on the struct don't apply to the referencee, and
3100 // we'll pick up CVR from the actual type later, so reset these
3101 // additional qualifiers now.
3102 cvr = 0;
John McCall53fcbd22011-02-26 08:07:02 +00003103 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003104 }
Craig Topper99e79272013-07-26 05:59:26 +00003105
Chris Lattner13ee4f42011-07-10 05:34:54 +00003106 // Make sure that the address is pointing to the right type. This is critical
3107 // for both unions and structs. A union needs a bitcast, a struct element
3108 // will need a bitcast if the LLVM type laid out doesn't match the desired
3109 // type.
John McCall7f416cc2015-09-08 08:05:57 +00003110 addr = Builder.CreateElementBitCast(addr,
3111 CGM.getTypes().ConvertTypeForMem(type),
3112 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003113
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003114 if (field->hasAttr<AnnotateAttr>())
3115 addr = EmitFieldAnnotations(field, addr);
3116
John McCall7f416cc2015-09-08 08:05:57 +00003117 LValue LV = MakeAddrLValue(addr, type, fieldAlignSource);
John McCall53fcbd22011-02-26 08:07:02 +00003118 LV.getQuals().addCVRQualifiers(cvr);
Manman Renc451e572013-04-04 21:53:22 +00003119 if (TBAAPath) {
3120 const ASTRecordLayout &Layout =
3121 getContext().getASTRecordLayout(field->getParent());
3122 // Set the base type to be the base type of the base LValue and
3123 // update offset to be relative to the base type.
Manman Ren0e521662013-04-27 00:39:37 +00003124 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3125 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
Manman Renc451e572013-04-04 21:53:22 +00003126 Layout.getFieldOffset(field->getFieldIndex()) /
3127 getContext().getCharWidth());
3128 }
Daniel Dunbarf166a522010-08-21 03:44:13 +00003129
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003130 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003131 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3132 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003133
3134 // Fields of may_alias structs act like 'char' for TBAA purposes.
3135 // FIXME: this should get propagated down through anonymous structs
3136 // and unions.
3137 if (mayAlias && LV.getTBAAInfo())
3138 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3139
Daniel Dunbarf166a522010-08-21 03:44:13 +00003140 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003141}
3142
Craig Topper99e79272013-07-26 05:59:26 +00003143LValue
3144CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003145 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003146 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003147
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003148 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003149 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003150
John McCall7f416cc2015-09-08 08:05:57 +00003151 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003152
John McCall7f416cc2015-09-08 08:05:57 +00003153 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003154 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003155 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003156
John McCall7f416cc2015-09-08 08:05:57 +00003157 // TODO: access-path TBAA?
3158 auto FieldAlignSource = getFieldAlignmentSource(Base.getAlignmentSource());
3159 return MakeAddrLValue(V, FieldType, FieldAlignSource);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003160}
3161
Chris Lattnerf53c0962010-09-06 00:11:41 +00003162LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00003163 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003164 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3165 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
Richard Smith2d988f02011-11-22 22:48:32 +00003166 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003167 if (E->getType()->isVariablyModifiedType())
3168 // make sure to emit the VLA size.
3169 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003170
John McCall7f416cc2015-09-08 08:05:57 +00003171 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003172 const Expr *InitExpr = E->getInitializer();
John McCall7f416cc2015-09-08 08:05:57 +00003173 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003174
Chad Rosier615ed1a2012-03-29 17:37:10 +00003175 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3176 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003177
3178 return Result;
3179}
3180
Richard Smithbb653bd2012-05-14 21:57:21 +00003181LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3182 if (!E->isGLValue())
3183 // Initializing an aggregate temporary in C++11: T{...}.
3184 return EmitAggExprToLValue(E);
3185
3186 // An lvalue initializer list must be initializing a reference.
3187 assert(E->getNumInits() == 1 && "reference init with multiple values");
3188 return EmitLValue(E->getInit(0));
3189}
3190
Richard Smithf3076ff2014-06-20 18:43:47 +00003191/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3192/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3193/// LValue is returned and the current block has been terminated.
3194static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3195 const Expr *Operand) {
3196 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3197 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3198 return None;
3199 }
3200
3201 return CGF.EmitLValue(Operand);
3202}
3203
John McCallc07a0c72011-02-17 10:25:35 +00003204LValue CodeGenFunction::
3205EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3206 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003207 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003208 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003209 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003210 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003211 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003212
Eli Friedman59954892012-01-25 05:04:17 +00003213 OpaqueValueMapping binding(*this, expr);
3214
John McCallc07a0c72011-02-17 10:25:35 +00003215 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003216 bool CondExprBool;
3217 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003218 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003219 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003220
Justin Bogneref512b92014-01-06 22:27:43 +00003221 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003222 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003223 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003224 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003225 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003226 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003227 }
3228
John McCallc07a0c72011-02-17 10:25:35 +00003229 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3230 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3231 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003232
3233 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003234 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003235
John McCall0a6bf2e2011-01-26 19:21:13 +00003236 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003237 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003238 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003239 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003240 Optional<LValue> lhs =
3241 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003242 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003243
Richard Smithf3076ff2014-06-20 18:43:47 +00003244 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003245 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003246
John McCallc07a0c72011-02-17 10:25:35 +00003247 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003248 if (lhs)
3249 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003250
John McCall0a6bf2e2011-01-26 19:21:13 +00003251 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003252 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003253 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003254 Optional<LValue> rhs =
3255 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003256 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003257 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003258 return EmitUnsupportedLValue(expr, "conditional operator");
3259 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003260
John McCallc07a0c72011-02-17 10:25:35 +00003261 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003262
Richard Smithf3076ff2014-06-20 18:43:47 +00003263 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003264 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003265 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003266 phi->addIncoming(lhs->getPointer(), lhsBlock);
3267 phi->addIncoming(rhs->getPointer(), rhsBlock);
3268 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3269 AlignmentSource alignSource =
3270 std::max(lhs->getAlignmentSource(), rhs->getAlignmentSource());
3271 return MakeAddrLValue(result, expr->getType(), alignSource);
Richard Smithf3076ff2014-06-20 18:43:47 +00003272 } else {
3273 assert((lhs || rhs) &&
3274 "both operands of glvalue conditional are throw-expressions?");
3275 return lhs ? *lhs : *rhs;
3276 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003277}
3278
Richard Smithbb653bd2012-05-14 21:57:21 +00003279/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3280/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003281/// otherwise if a cast is needed by the code generator in an lvalue context,
3282/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003283/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003284/// are permitted with aggregate result, including noop aggregate casts, and
3285/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003286LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003287 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003288 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003289 case CK_BitCast:
3290 case CK_ArrayToPointerDecay:
3291 case CK_FunctionToPointerDecay:
3292 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003293 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003294 case CK_IntegralToPointer:
3295 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003296 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003297 case CK_VectorSplat:
3298 case CK_IntegralCast:
John McCall8cb679e2010-11-15 09:13:47 +00003299 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003300 case CK_IntegralToFloating:
3301 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003302 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003303 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003304 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003305 case CK_FloatingComplexToReal:
3306 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003307 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003308 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003309 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003310 case CK_IntegralComplexToReal:
3311 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003312 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003313 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003314 case CK_DerivedToBaseMemberPointer:
3315 case CK_BaseToDerivedMemberPointer:
3316 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003317 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003318 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003319 case CK_ARCProduceObject:
3320 case CK_ARCConsumeObject:
3321 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003322 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003323 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003324 case CK_AddressSpaceConversion:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003325 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3326
3327 case CK_Dependent:
3328 llvm_unreachable("dependent cast kind in IR gen!");
3329
3330 case CK_BuiltinFnToFnPtr:
3331 llvm_unreachable("builtin functions are handled elsewhere");
3332
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003333 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003334 case CK_NonAtomicToAtomic:
3335 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003336 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00003337
Anders Carlsson8a01a752011-04-11 02:03:26 +00003338 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00003339 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003340 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003341 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00003342 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00003343 }
3344
John McCalle3027922010-08-25 11:45:40 +00003345 case CK_ConstructorConversion:
3346 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00003347 case CK_CPointerToObjCPointerCast:
3348 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003349 case CK_NoOp:
3350 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003351 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00003352
John McCalle3027922010-08-25 11:45:40 +00003353 case CK_UncheckedDerivedToBase:
3354 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00003355 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00003356 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003357 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003358
Anders Carlssond95f9602009-09-12 16:16:49 +00003359 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003360 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00003361
Anders Carlssond95f9602009-09-12 16:16:49 +00003362 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00003363 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00003364 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3365 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00003366
John McCall7f416cc2015-09-08 08:05:57 +00003367 return MakeAddrLValue(Base, E->getType(), LV.getAlignmentSource());
Anders Carlssond95f9602009-09-12 16:16:49 +00003368 }
John McCalle3027922010-08-25 11:45:40 +00003369 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00003370 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00003371 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00003372 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003373 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003374
Anders Carlsson8c793172009-11-23 17:57:54 +00003375 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00003376
Anders Carlsson8c793172009-11-23 17:57:54 +00003377 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00003378 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00003379 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00003380 E->path_begin(), E->path_end(),
3381 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00003382
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003383 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3384 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00003385 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003386 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00003387 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003388
Peter Collingbourned2926c92015-03-14 02:42:25 +00003389 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003390 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3391 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003392 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003393
John McCall7f416cc2015-09-08 08:05:57 +00003394 return MakeAddrLValue(Derived, E->getType(), LV.getAlignmentSource());
Eli Friedman8c98dff2009-11-16 05:48:01 +00003395 }
John McCalle3027922010-08-25 11:45:40 +00003396 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00003397 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003398 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00003399
Anders Carlsson50cb3212009-11-14 21:21:42 +00003400 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003401 Address V = Builder.CreateBitCast(LV.getAddress(),
3402 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00003403
3404 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003405 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3406 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003407 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003408
John McCall7f416cc2015-09-08 08:05:57 +00003409 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Anders Carlsson50cb3212009-11-14 21:21:42 +00003410 }
John McCalle3027922010-08-25 11:45:40 +00003411 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003412 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003413 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3414 ConvertType(E->getType()));
3415 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003416 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003417 case CK_ZeroToOCLEvent:
3418 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00003419 }
Craig Topper99e79272013-07-26 05:59:26 +00003420
Douglas Gregorcdb466e2010-07-15 18:58:16 +00003421 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003422}
3423
John McCall1bf58462011-02-16 08:02:54 +00003424LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00003425 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00003426 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00003427}
3428
Eli Friedman7f1ff602012-04-16 03:54:45 +00003429RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003430 const FieldDecl *FD,
3431 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003432 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003433 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00003434 switch (getEvaluationKind(FT)) {
3435 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003436 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00003437 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00003438 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00003439 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003440 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00003441 }
3442 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003443}
Douglas Gregorfe314812011-06-21 17:03:29 +00003444
Chris Lattnere47e4402007-06-01 18:02:12 +00003445//===--------------------------------------------------------------------===//
3446// Expression Emission
3447//===--------------------------------------------------------------------===//
3448
Craig Topper99e79272013-07-26 05:59:26 +00003449RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00003450 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003451 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003452 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00003453 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003454
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003455 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003456 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003457
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003458 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00003459 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3460
Douglas Gregore0e96302011-09-06 21:41:04 +00003461 const Decl *TargetDecl = E->getCalleeDecl();
3462 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
3463 if (unsigned builtinID = FD->getBuiltinID())
Peter Collingbournef7706832014-12-12 23:41:25 +00003464 return EmitBuiltinExpr(FD, builtinID, E, ReturnValue);
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003465 }
3466
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003467 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
Anders Carlsson4034a952009-05-27 04:18:27 +00003468 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003469 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003470
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003471 if (const auto *PseudoDtor =
3472 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
John McCall31168b02011-06-15 23:02:42 +00003473 QualType DestroyedType = PseudoDtor->getDestroyedType();
Richard Smith9c6890a2012-11-01 22:30:59 +00003474 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003475 DestroyedType->isObjCLifetimeType() &&
3476 (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong ||
3477 DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) {
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003478 // Automatic Reference Counting:
3479 // If the pseudo-expression names a retainable object with weak or
3480 // strong lifetime, the object shall be released.
John McCall31168b02011-06-15 23:02:42 +00003481 Expr *BaseExpr = PseudoDtor->getBase();
John McCall7f416cc2015-09-08 08:05:57 +00003482 Address BaseValue = Address::invalid();
John McCall31168b02011-06-15 23:02:42 +00003483 Qualifiers BaseQuals;
Craig Topper99e79272013-07-26 05:59:26 +00003484
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003485 // 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 +00003486 if (PseudoDtor->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00003487 BaseValue = EmitPointerWithAlignment(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00003488 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
3489 BaseQuals = PTy->getPointeeType().getQualifiers();
3490 } else {
3491 LValue BaseLV = EmitLValue(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00003492 BaseValue = BaseLV.getAddress();
3493 QualType BaseTy = BaseExpr->getType();
3494 BaseQuals = BaseTy.getQualifiers();
3495 }
Craig Topper99e79272013-07-26 05:59:26 +00003496
John McCall31168b02011-06-15 23:02:42 +00003497 switch (PseudoDtor->getDestroyedType().getObjCLifetime()) {
3498 case Qualifiers::OCL_None:
3499 case Qualifiers::OCL_ExplicitNone:
3500 case Qualifiers::OCL_Autoreleasing:
3501 break;
Craig Topper99e79272013-07-26 05:59:26 +00003502
John McCall31168b02011-06-15 23:02:42 +00003503 case Qualifiers::OCL_Strong:
Craig Topper99e79272013-07-26 05:59:26 +00003504 EmitARCRelease(Builder.CreateLoad(BaseValue,
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003505 PseudoDtor->getDestroyedType().isVolatileQualified()),
John McCallcdda29c2013-03-13 03:10:54 +00003506 ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00003507 break;
3508
3509 case Qualifiers::OCL_Weak:
3510 EmitARCDestroyWeak(BaseValue);
3511 break;
3512 }
3513 } else {
3514 // C++ [expr.pseudo]p1:
3515 // The result shall only be used as the operand for the function call
3516 // operator (), and the result of such a call has type void. The only
3517 // effect is the evaluation of the postfix-expression before the dot or
Craig Topper99e79272013-07-26 05:59:26 +00003518 // arrow.
John McCall31168b02011-06-15 23:02:42 +00003519 EmitScalarExpr(E->getCallee());
3520 }
Craig Topper99e79272013-07-26 05:59:26 +00003521
Craig Topper8a13c412014-05-21 05:09:00 +00003522 return RValue::get(nullptr);
Douglas Gregorad8a3362009-09-04 17:36:40 +00003523 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003524
Chris Lattner2da04b32007-08-24 05:35:26 +00003525 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003526 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
3527 TargetDecl);
Chris Lattner9e47ead2007-08-31 04:44:06 +00003528}
3529
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003530LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00003531 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00003532 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00003533 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00003534 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00003535 return EmitLValue(E->getRHS());
3536 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003537
John McCalle3027922010-08-25 11:45:40 +00003538 if (E->getOpcode() == BO_PtrMemD ||
3539 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003540 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003541
John McCalla2342eb2010-12-05 02:00:02 +00003542 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00003543
3544 // Note that in all of these cases, __block variables need the RHS
3545 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00003546
3547 switch (getEvaluationKind(E->getType())) {
3548 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00003549 switch (E->getLHS()->getType().getObjCLifetime()) {
3550 case Qualifiers::OCL_Strong:
3551 return EmitARCStoreStrong(E, /*ignored*/ false).first;
3552
3553 case Qualifiers::OCL_Autoreleasing:
3554 return EmitARCStoreAutoreleasing(E).first;
3555
3556 // No reason to do any of these differently.
3557 case Qualifiers::OCL_None:
3558 case Qualifiers::OCL_ExplicitNone:
3559 case Qualifiers::OCL_Weak:
3560 break;
3561 }
3562
John McCalld0a30012010-12-06 06:10:02 +00003563 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00003564 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
John McCall55e1fbc2011-06-25 02:11:03 +00003565 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00003566 return LV;
3567 }
John McCall4f29b492010-11-16 23:07:28 +00003568
John McCall47fb9502013-03-07 21:37:08 +00003569 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00003570 return EmitComplexAssignmentLValue(E);
3571
John McCall47fb9502013-03-07 21:37:08 +00003572 case TEK_Aggregate:
3573 return EmitAggExprToLValue(E);
3574 }
3575 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003576}
3577
Christopher Lambd91c3d42007-12-29 05:02:41 +00003578LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00003579 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00003580
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003581 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00003582 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3583 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00003584
David Majnemerced8bdf2015-02-25 17:36:15 +00003585 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003586 "Can't have a scalar return unless the return type is a "
3587 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00003588
John McCall7f416cc2015-09-08 08:05:57 +00003589 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00003590}
3591
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003592LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
3593 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00003594 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003595}
3596
Anders Carlsson3be22e22009-05-30 23:23:33 +00003597LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003598 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
3599 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00003600 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00003601 EmitCXXConstructExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003602 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3603 AlignmentSource::Decl);
Anders Carlsson3be22e22009-05-30 23:23:33 +00003604}
3605
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003606LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00003607CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003608 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00003609}
3610
John McCall7f416cc2015-09-08 08:05:57 +00003611Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
3612 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
3613 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00003614}
3615
3616LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003617 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
3618 AlignmentSource::Decl);
Nico Webercf4ff5862012-10-11 10:13:44 +00003619}
3620
Mike Stumpc9b231c2009-11-15 08:09:41 +00003621LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003622CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003623 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00003624 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00003625 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003626 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
3627 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3628 AlignmentSource::Decl);
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003629}
3630
Eli Friedman5bc17122012-02-08 05:34:55 +00003631LValue
3632CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00003633 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00003634 EmitLambdaExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003635 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3636 AlignmentSource::Decl);
Eli Friedman5bc17122012-02-08 05:34:55 +00003637}
3638
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003639LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003640 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00003641
Anders Carlsson280e61f12010-06-21 20:59:55 +00003642 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00003643 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3644 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00003645
Alp Toker314cc812014-01-25 16:55:45 +00003646 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00003647 "Can't have a scalar return unless the return type is a "
3648 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00003649
John McCall7f416cc2015-09-08 08:05:57 +00003650 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003651}
3652
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003653LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003654 Address V =
3655 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
3656 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003657}
3658
Daniel Dunbar722f4242009-04-22 05:08:15 +00003659llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003660 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00003661 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003662}
3663
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003664LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
3665 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003666 const ObjCIvarDecl *Ivar,
3667 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00003668 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00003669 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003670}
3671
3672LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003673 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00003674 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003675 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00003676 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003677 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003678 if (E->isArrow()) {
3679 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003680 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00003681 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003682 } else {
3683 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00003684 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003685 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00003686 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003687 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003688
Craig Topper99e79272013-07-26 05:59:26 +00003689 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00003690 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
3691 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00003692 setObjCGCLValueClass(getContext(), E, LV);
3693 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00003694}
3695
Chris Lattnera4185c52009-04-25 19:35:26 +00003696LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00003697 // Can only get l-value for message expression returning aggregate type
3698 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00003699 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3700 AlignmentSource::Decl);
Chris Lattnera4185c52009-04-25 19:35:26 +00003701}
3702
Anders Carlsson0435ed52009-12-24 19:08:58 +00003703RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003704 const CallExpr *E, ReturnValueSlot ReturnValue,
Peter Collingbournef7706832014-12-12 23:41:25 +00003705 const Decl *TargetDecl, llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00003706 // Get the actual function type. The callee type will always be a pointer to
3707 // function type or a block pointer type.
3708 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00003709 "Call must have function pointer type!");
3710
John McCall6fd4c232009-10-23 08:22:42 +00003711 CalleeType = getContext().getCanonicalType(CalleeType);
3712
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003713 const auto *FnType =
3714 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00003715
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003716 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003717 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
3718 if (llvm::Constant *PrefixSig =
3719 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003720 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003721 llvm::Constant *FTRTTIConst =
3722 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
3723 llvm::Type *PrefixStructTyElems[] = {
3724 PrefixSig->getType(),
3725 FTRTTIConst->getType()
3726 };
3727 llvm::StructType *PrefixStructTy = llvm::StructType::get(
3728 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
3729
3730 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
3731 Callee, llvm::PointerType::getUnqual(PrefixStructTy));
3732 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00003733 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00003734 llvm::Value *CalleeSig =
3735 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003736 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
3737
3738 llvm::BasicBlock *Cont = createBasicBlock("cont");
3739 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
3740 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
3741
3742 EmitBlock(TypeCheck);
3743 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00003744 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003745 llvm::Value *CalleeRTTI =
3746 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003747 llvm::Value *CalleeRTTIMatch =
3748 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
3749 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003750 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003751 EmitCheckTypeDescriptor(CalleeType)
3752 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003753 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
3754 "function_type_mismatch", StaticData, Callee);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003755
3756 Builder.CreateBr(Cont);
3757 EmitBlock(Cont);
3758 }
3759 }
3760
Daniel Dunbarc722b852008-08-30 03:02:31 +00003761 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00003762 if (Chain)
3763 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
3764 CGM.getContext().VoidPtrTy);
David Blaikief05779e2015-07-21 18:37:18 +00003765 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
3766 E->getDirectCallee(), /*ParamsToSkip*/ 0);
Daniel Dunbarc722b852008-08-30 03:02:31 +00003767
Peter Collingbournef7706832014-12-12 23:41:25 +00003768 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
3769 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00003770
3771 // C99 6.5.2.2p6:
3772 // If the expression that denotes the called function has a type
3773 // that does not include a prototype, [the default argument
3774 // promotions are performed]. If the number of arguments does not
3775 // equal the number of parameters, the behavior is undefined. If
3776 // the function is defined with a type that includes a prototype,
3777 // and either the prototype ends with an ellipsis (, ...) or the
3778 // types of the arguments after promotion are not compatible with
3779 // the types of the parameters, the behavior is undefined. If the
3780 // function is defined with a type that does not include a
3781 // prototype, and the types of the arguments after promotion are
3782 // not compatible with those of the parameters after promotion,
3783 // the behavior is undefined [except in some trivial cases].
3784 // That is, in the general case, we should assume that a call
3785 // through an unprototyped function type works like a *non-variadic*
3786 // call. The way we make this work is to cast to the exact type
3787 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00003788 //
3789 // Chain calls use this same code path to add the invisible chain parameter
3790 // to the function type.
3791 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00003792 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00003793 CalleeTy = CalleeTy->getPointerTo();
3794 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
3795 }
3796
3797 return EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00003798}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003799
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003800LValue CodeGenFunction::
3801EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003802 Address BaseAddr = Address::invalid();
3803 if (E->getOpcode() == BO_PtrMemI) {
3804 BaseAddr = EmitPointerWithAlignment(E->getLHS());
3805 } else {
3806 BaseAddr = EmitLValue(E->getLHS()).getAddress();
3807 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003808
John McCallc134eb52010-08-31 21:07:20 +00003809 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
3810
3811 const MemberPointerType *MPT
3812 = E->getRHS()->getType()->getAs<MemberPointerType>();
3813
John McCall7f416cc2015-09-08 08:05:57 +00003814 AlignmentSource AlignSource;
3815 Address MemberAddr =
3816 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT,
3817 &AlignSource);
John McCallc134eb52010-08-31 21:07:20 +00003818
John McCall7f416cc2015-09-08 08:05:57 +00003819 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), AlignSource);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003820}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003821
John McCall47fb9502013-03-07 21:37:08 +00003822/// Given the address of a temporary variable, produce an r-value of
3823/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00003824RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003825 QualType type,
3826 SourceLocation loc) {
John McCall7f416cc2015-09-08 08:05:57 +00003827 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
John McCall47fb9502013-03-07 21:37:08 +00003828 switch (getEvaluationKind(type)) {
3829 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003830 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00003831 case TEK_Aggregate:
3832 return lvalue.asAggregateRValue();
3833 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003834 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00003835 }
3836 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003837}
3838
Duncan Sandse81111c2012-04-10 08:23:07 +00003839void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003840 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00003841 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003842 return;
3843
Duncan Sands65229ed2012-04-16 16:29:47 +00003844 llvm::MDBuilder MDHelper(getLLVMContext());
3845 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003846
Duncan Sands6fc46192012-04-14 12:37:26 +00003847 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003848}
John McCallfe96e0b2011-11-06 09:01:30 +00003849
3850namespace {
3851 struct LValueOrRValue {
3852 LValue LV;
3853 RValue RV;
3854 };
3855}
3856
3857static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
3858 const PseudoObjectExpr *E,
3859 bool forLValue,
3860 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003861 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00003862
3863 // Find the result expression, if any.
3864 const Expr *resultExpr = E->getResultExpr();
3865 LValueOrRValue result;
3866
3867 for (PseudoObjectExpr::const_semantics_iterator
3868 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3869 const Expr *semantic = *i;
3870
3871 // If this semantic expression is an opaque value, bind it
3872 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003873 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00003874
3875 // If this is the result expression, we may need to evaluate
3876 // directly into the slot.
3877 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
3878 OVMA opaqueData;
3879 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00003880 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00003881 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
3882
John McCall7f416cc2015-09-08 08:05:57 +00003883 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
3884 AlignmentSource::Decl);
John McCallfe96e0b2011-11-06 09:01:30 +00003885 opaqueData = OVMA::bind(CGF, ov, LV);
3886 result.RV = slot.asRValue();
3887
3888 // Otherwise, emit as normal.
3889 } else {
3890 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
3891
3892 // If this is the result, also evaluate the result now.
3893 if (ov == resultExpr) {
3894 if (forLValue)
3895 result.LV = CGF.EmitLValue(ov);
3896 else
3897 result.RV = CGF.EmitAnyExpr(ov, slot);
3898 }
3899 }
3900
3901 opaques.push_back(opaqueData);
3902
3903 // Otherwise, if the expression is the result, evaluate it
3904 // and remember the result.
3905 } else if (semantic == resultExpr) {
3906 if (forLValue)
3907 result.LV = CGF.EmitLValue(semantic);
3908 else
3909 result.RV = CGF.EmitAnyExpr(semantic, slot);
3910
3911 // Otherwise, evaluate the expression in an ignored context.
3912 } else {
3913 CGF.EmitIgnoredExpr(semantic);
3914 }
3915 }
3916
3917 // Unbind all the opaques now.
3918 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
3919 opaques[i].unbind(CGF);
3920
3921 return result;
3922}
3923
3924RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
3925 AggValueSlot slot) {
3926 return emitPseudoObjectExpr(*this, E, false, slot).RV;
3927}
3928
3929LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
3930 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
3931}