blob: ece83371db9473ab8e8e292fcfcddcc05a4b265c [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) &&
John McCall7f416cc2015-09-08 08:05:57 +0000817 InnerSource != AlignmentSource::Decl) {
818 Addr = Address(Addr.getPointer(),
819 getNaturalPointeeTypeAlignment(E->getType(), Source));
820 }
821
Peter Collingbourneee381ff2015-09-09 00:01:31 +0000822 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
823 if (auto PT = E->getType()->getAs<PointerType>())
824 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
825 /*MayBeNull=*/true,
826 CodeGenFunction::CFITCK_UnrelatedCast,
827 CE->getLocStart());
828 }
829
John McCall7f416cc2015-09-08 08:05:57 +0000830 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
831 }
832 break;
833
834 // Array-to-pointer decay.
835 case CK_ArrayToPointerDecay:
836 return EmitArrayToPointerDecay(CE->getSubExpr(), Source);
837
838 // Derived-to-base conversions.
839 case CK_UncheckedDerivedToBase:
840 case CK_DerivedToBase: {
841 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), Source);
842 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
843 return GetAddressOfBaseClass(Addr, Derived,
844 CE->path_begin(), CE->path_end(),
845 ShouldNullCheckClassCastValue(CE),
846 CE->getExprLoc());
847 }
848
849 // TODO: Is there any reason to treat base-to-derived conversions
850 // specially?
851 default:
852 break;
853 }
854 }
855
856 // Unary &.
857 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
858 if (UO->getOpcode() == UO_AddrOf) {
859 LValue LV = EmitLValue(UO->getSubExpr());
860 if (Source) *Source = LV.getAlignmentSource();
861 return LV.getAddress();
862 }
863 }
864
865 // TODO: conditional operators, comma.
866
867 // Otherwise, use the alignment of the type.
868 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), Source);
869 return Address(EmitScalarExpr(E), Align);
870}
871
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000872RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000873 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +0000874 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +0000875
876 switch (getEvaluationKind(Ty)) {
877 case TEK_Complex: {
878 llvm::Type *EltTy =
879 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +0000880 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000881 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000882 }
Craig Topper99e79272013-07-26 05:59:26 +0000883
Chris Lattner65526f02010-08-23 05:26:13 +0000884 // If this is a use of an undefined aggregate type, the aggregate must have an
885 // identifiable address. Just because the contents of the value are undefined
886 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +0000887 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000888 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +0000889 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000890 }
John McCall47fb9502013-03-07 21:37:08 +0000891
892 case TEK_Scalar:
893 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
894 }
895 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +0000896}
897
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000898RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
899 const char *Name) {
900 ErrorUnsupported(E, Name);
901 return GetUndefRValue(E->getType());
902}
903
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000904LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
905 const char *Name) {
906 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000907 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +0000908 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
909 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000910}
911
Richard Smith4d1458e2012-09-08 02:08:36 +0000912LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +0000913 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000914 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +0000915 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
916 else
917 LV = EmitLValue(E);
Daniel Dunbardc406b82010-04-05 21:36:35 +0000918 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
John McCall7f416cc2015-09-08 08:05:57 +0000919 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
Richard Smithe30752c2012-10-09 19:52:38 +0000920 E->getType(), LV.getAlignment());
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000921 return LV;
922}
923
Chris Lattner8394d792007-06-05 20:53:16 +0000924/// EmitLValue - Emit code to compute a designator that specifies the location
925/// of the expression.
926///
Mike Stump4a3999f2009-09-09 13:00:44 +0000927/// This can return one of two things: a simple address or a bitfield reference.
928/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
929/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +0000930///
Mike Stump4a3999f2009-09-09 13:00:44 +0000931/// If this returns a bitfield reference, nothing about the pointee type of the
932/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +0000933///
Mike Stump4a3999f2009-09-09 13:00:44 +0000934/// If this returns a normal address, and if the lvalue's C type is fixed size,
935/// this method guarantees that the returned pointer type will point to an LLVM
936/// type of the same size of the lvalue's type. If the lvalue has a variable
937/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +0000938///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000939LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +0000940 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +0000941 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000942 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000943
John McCallc109a252011-11-07 03:59:57 +0000944 case Expr::ObjCPropertyRefExprClass:
945 llvm_unreachable("cannot emit a property reference directly");
946
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000947 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +0000948 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000949 case Expr::ObjCIsaExprClass:
950 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000951 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +0000952 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +0000953 case Expr::CompoundAssignOperatorClass: {
954 QualType Ty = E->getType();
955 if (const AtomicType *AT = Ty->getAs<AtomicType>())
956 Ty = AT->getValueType();
957 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +0000958 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
959 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +0000960 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000961 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +0000962 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000963 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +0000964 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000965 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +0000966 case Expr::VAArgExprClass:
967 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000968 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000969 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +0000970 case Expr::ParenExprClass:
971 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +0000972 case Expr::GenericSelectionExprClass:
973 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +0000974 case Expr::PredefinedExprClass:
975 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +0000976 case Expr::StringLiteralClass:
977 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +0000978 case Expr::ObjCEncodeExprClass:
979 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +0000980 case Expr::PseudoObjectExprClass:
981 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +0000982 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +0000983 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +0000984 case Expr::CXXTemporaryObjectExprClass:
985 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +0000986 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
987 case Expr::CXXBindTemporaryExprClass:
988 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +0000989 case Expr::CXXUuidofExprClass:
990 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +0000991 case Expr::LambdaExprClass:
992 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +0000993
994 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000995 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +0000996 enterFullExpression(cleanups);
997 RunCleanupsScope Scope(*this);
998 return EmitLValue(cleanups->getSubExpr());
999 }
1000
Anders Carlsson52ce3bb2009-11-14 01:51:50 +00001001 case Expr::CXXDefaultArgExprClass:
1002 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001003 case Expr::CXXDefaultInitExprClass: {
1004 CXXDefaultInitExprScope Scope(*this);
1005 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1006 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001007 case Expr::CXXTypeidExprClass:
1008 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001009
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001010 case Expr::ObjCMessageExprClass:
1011 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001012 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001013 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001014 case Expr::StmtExprClass:
1015 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001016 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001017 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001018 case Expr::ArraySubscriptExprClass:
1019 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001020 case Expr::OMPArraySectionExprClass:
1021 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001022 case Expr::ExtVectorElementExprClass:
1023 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001024 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001025 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001026 case Expr::CompoundLiteralExprClass:
1027 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001028 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001029 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001030 case Expr::BinaryConditionalOperatorClass:
1031 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001032 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001033 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001034 case Expr::OpaqueValueExprClass:
1035 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001036 case Expr::SubstNonTypeTemplateParmExprClass:
1037 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001038 case Expr::ImplicitCastExprClass:
1039 case Expr::CStyleCastExprClass:
1040 case Expr::CXXFunctionalCastExprClass:
1041 case Expr::CXXStaticCastExprClass:
1042 case Expr::CXXDynamicCastExprClass:
1043 case Expr::CXXReinterpretCastExprClass:
1044 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001045 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001046 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001047
Douglas Gregorfe314812011-06-21 17:03:29 +00001048 case Expr::MaterializeTemporaryExprClass:
1049 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001050 }
1051}
1052
John McCall71335052012-03-10 03:05:10 +00001053/// Given an object of the given canonical type, can we safely copy a
1054/// value out of it based on its initializer?
1055static bool isConstantEmittableObjectType(QualType type) {
1056 assert(type.isCanonical());
1057 assert(!type->isReferenceType());
1058
1059 // Must be const-qualified but non-volatile.
1060 Qualifiers qs = type.getLocalQualifiers();
1061 if (!qs.hasConst() || qs.hasVolatile()) return false;
1062
1063 // Otherwise, all object types satisfy this except C++ classes with
1064 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001065 if (const auto *RT = dyn_cast<RecordType>(type))
1066 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001067 if (RD->hasMutableFields() || !RD->isTrivial())
1068 return false;
1069
1070 return true;
1071}
1072
1073/// Can we constant-emit a load of a reference to a variable of the
1074/// given type? This is different from predicates like
1075/// Decl::isUsableInConstantExpressions because we do want it to apply
1076/// in situations that don't necessarily satisfy the language's rules
1077/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1078/// to do this with const float variables even if those variables
1079/// aren't marked 'constexpr'.
1080enum ConstantEmissionKind {
1081 CEK_None,
1082 CEK_AsReferenceOnly,
1083 CEK_AsValueOrReference,
1084 CEK_AsValueOnly
1085};
1086static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1087 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001088 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001089 if (isConstantEmittableObjectType(ref->getPointeeType()))
1090 return CEK_AsValueOrReference;
1091 return CEK_AsReferenceOnly;
1092 }
1093 if (isConstantEmittableObjectType(type))
1094 return CEK_AsValueOnly;
1095 return CEK_None;
1096}
1097
1098/// Try to emit a reference to the given value without producing it as
1099/// an l-value. This is actually more than an optimization: we can't
1100/// produce an l-value for variables that we never actually captured
1101/// in a block or lambda, which means const int variables or constexpr
1102/// literals or similar.
1103CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001104CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1105 ValueDecl *value = refExpr->getDecl();
1106
John McCall71335052012-03-10 03:05:10 +00001107 // The value needs to be an enum constant or a constant variable.
1108 ConstantEmissionKind CEK;
1109 if (isa<ParmVarDecl>(value)) {
1110 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001111 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001112 CEK = checkVarTypeForConstantEmission(var->getType());
1113 } else if (isa<EnumConstantDecl>(value)) {
1114 CEK = CEK_AsValueOnly;
1115 } else {
1116 CEK = CEK_None;
1117 }
1118 if (CEK == CEK_None) return ConstantEmission();
1119
John McCall71335052012-03-10 03:05:10 +00001120 Expr::EvalResult result;
1121 bool resultIsReference;
1122 QualType resultType;
1123
1124 // It's best to evaluate all the way as an r-value if that's permitted.
1125 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001126 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001127 resultIsReference = false;
1128 resultType = refExpr->getType();
1129
1130 // Otherwise, try to evaluate as an l-value.
1131 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001132 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001133 resultIsReference = true;
1134 resultType = value->getType();
1135
1136 // Failure.
1137 } else {
1138 return ConstantEmission();
1139 }
1140
1141 // In any case, if the initializer has side-effects, abandon ship.
1142 if (result.HasSideEffects)
1143 return ConstantEmission();
1144
1145 // Emit as a constant.
1146 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1147
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001148 // Make sure we emit a debug reference to the global variable.
1149 // This should probably fire even for
1150 if (isa<VarDecl>(value)) {
1151 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1152 EmitDeclRefExprDbgValue(refExpr, C);
1153 } else {
1154 assert(isa<EnumConstantDecl>(value));
1155 EmitDeclRefExprDbgValue(refExpr, C);
1156 }
John McCall71335052012-03-10 03:05:10 +00001157
1158 // If we emitted a reference constant, we need to dereference that.
1159 if (resultIsReference)
1160 return ConstantEmission::forReference(C);
1161
1162 return ConstantEmission::forValue(C);
1163}
1164
Nick Lewycky2d84e842013-10-02 02:29:49 +00001165llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1166 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +00001167 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001168 lvalue.getType(), Loc, lvalue.getAlignmentSource(),
1169 lvalue.getTBAAInfo(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001170 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1171 lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001172}
1173
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001174static bool hasBooleanRepresentation(QualType Ty) {
1175 if (Ty->isBooleanType())
1176 return true;
1177
1178 if (const EnumType *ET = Ty->getAs<EnumType>())
1179 return ET->getDecl()->getIntegerType()->isBooleanType();
1180
Douglas Gregor298f43d2012-04-12 20:42:30 +00001181 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1182 return hasBooleanRepresentation(AT->getValueType());
1183
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001184 return false;
1185}
1186
Richard Smith1629da92012-12-13 07:11:50 +00001187static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1188 llvm::APInt &Min, llvm::APInt &End,
1189 bool StrictEnums) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001190 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001191 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1192 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001193 bool IsBool = hasBooleanRepresentation(Ty);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001194 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001195 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001196
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001197 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001198 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1199 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001200 } else {
1201 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001202 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001203 unsigned Bitwidth = LTy->getScalarSizeInBits();
1204 unsigned NumNegativeBits = ED->getNumNegativeBits();
1205 unsigned NumPositiveBits = ED->getNumPositiveBits();
1206
1207 if (NumNegativeBits) {
1208 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1209 assert(NumBits <= Bitwidth);
1210 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1211 Min = -End;
1212 } else {
1213 assert(NumPositiveBits <= Bitwidth);
1214 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1215 Min = llvm::APInt(Bitwidth, 0);
1216 }
1217 }
Richard Smith1629da92012-12-13 07:11:50 +00001218 return true;
1219}
1220
1221llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1222 llvm::APInt Min, End;
1223 if (!getRangeForType(*this, Ty, Min, End,
1224 CGM.getCodeGenOpts().StrictEnums))
Craig Topper8a13c412014-05-21 05:09:00 +00001225 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001226
Duncan Sandsc720e782012-04-15 18:04:54 +00001227 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001228 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001229}
1230
John McCall7f416cc2015-09-08 08:05:57 +00001231llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1232 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001233 SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +00001234 AlignmentSource AlignSource,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001235 llvm::MDNode *TBAAInfo,
1236 QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001237 uint64_t TBAAOffset,
1238 bool isNontemporal) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001239 // For better performance, handle vector loads differently.
1240 if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001241 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001242
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001243 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001244
John McCall7f416cc2015-09-08 08:05:57 +00001245 // Handle vectors of size 3 like size 4 for better performance.
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001246 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001247
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001248 // Bitcast to vec4 type.
1249 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
1250 4);
John McCall7f416cc2015-09-08 08:05:57 +00001251 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001252 // Now load value.
John McCall7f416cc2015-09-08 08:05:57 +00001253 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001254
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001255 // Shuffle vector to get vec3.
John McCall7f416cc2015-09-08 08:05:57 +00001256 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
Benjamin Kramer99383102015-07-28 16:25:32 +00001257 {0, 1, 2}, "extractVec");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001258 return EmitFromMemory(V, Ty);
1259 }
1260 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001261
1262 // Atomic operations have to be done on integral types.
David Majnemera5b195a2015-02-14 01:35:12 +00001263 if (Ty->isAtomicType() || typeIsSuitableForInlineAtomic(Ty, Volatile)) {
John McCall7f416cc2015-09-08 08:05:57 +00001264 LValue lvalue =
1265 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
David Majnemereeaec262015-02-14 02:18:14 +00001266 return EmitAtomicLoad(lvalue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001267 }
Craig Topper99e79272013-07-26 05:59:26 +00001268
John McCall7f416cc2015-09-08 08:05:57 +00001269 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001270 if (isNontemporal) {
1271 llvm::MDNode *Node = llvm::MDNode::get(
1272 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1273 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1274 }
Manman Renc451e572013-04-04 21:53:22 +00001275 if (TBAAInfo) {
1276 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1277 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001278 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001279 CGM.DecorateInstructionWithTBAA(Load, TBAAPath,
1280 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001281 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001282
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00001283 bool NeedsBoolCheck =
1284 SanOpts.has(SanitizerKind::Bool) && hasBooleanRepresentation(Ty);
1285 bool NeedsEnumCheck =
1286 SanOpts.has(SanitizerKind::Enum) && Ty->getAs<EnumType>();
1287 if (NeedsBoolCheck || NeedsEnumCheck) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00001288 SanitizerScope SanScope(this);
Richard Smith1629da92012-12-13 07:11:50 +00001289 llvm::APInt Min, End;
1290 if (getRangeForType(*this, Ty, Min, End, true)) {
1291 --End;
1292 llvm::Value *Check;
1293 if (!Min)
1294 Check = Builder.CreateICmpULE(
1295 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1296 else {
1297 llvm::Value *Upper = Builder.CreateICmpSLE(
1298 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1299 llvm::Value *Lower = Builder.CreateICmpSGE(
1300 Load, llvm::ConstantInt::get(getLLVMContext(), Min));
1301 Check = Builder.CreateAnd(Upper, Lower);
1302 }
Nick Lewycky2d84e842013-10-02 02:29:49 +00001303 llvm::Constant *StaticArgs[] = {
1304 EmitCheckSourceLocation(Loc),
1305 EmitCheckTypeDescriptor(Ty)
1306 };
Peter Collingbourne3eea6772015-05-11 21:39:14 +00001307 SanitizerMask Kind = NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
Alexey Samsonove396bfc2014-11-11 22:03:54 +00001308 EmitCheck(std::make_pair(Check, Kind), "load_invalid_value", StaticArgs,
1309 EmitCheckValue(Load));
Richard Smith1629da92012-12-13 07:11:50 +00001310 }
1311 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001312 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1313 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001314
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001315 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001316}
1317
John McCall3a7f6922010-10-27 20:58:56 +00001318llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1319 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001320 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001321 // This should really always be an i1, but sometimes it's already
1322 // an i8, and it's awkward to track those cases down.
1323 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001324 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1325 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1326 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001327 }
1328
1329 return Value;
1330}
1331
1332llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1333 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001334 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001335 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1336 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001337 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1338 }
1339
1340 return Value;
1341}
1342
John McCall7f416cc2015-09-08 08:05:57 +00001343void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1344 bool Volatile, QualType Ty,
1345 AlignmentSource AlignSource,
1346 llvm::MDNode *TBAAInfo,
Manman Renc451e572013-04-04 21:53:22 +00001347 bool isInit, QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001348 uint64_t TBAAOffset,
1349 bool isNontemporal) {
Craig Topper99e79272013-07-26 05:59:26 +00001350
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001351 // Handle vectors differently to get better performance.
1352 if (Ty->isVectorType()) {
1353 llvm::Type *SrcTy = Value->getType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001354 auto *VecTy = cast<llvm::VectorType>(SrcTy);
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001355 // Handle vec3 special.
1356 if (VecTy->getNumElements() == 3) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001357 // Our source is a vec3, do a shuffle vector to make it a vec4.
Benjamin Kramer99383102015-07-28 16:25:32 +00001358 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1359 Builder.getInt32(2),
1360 llvm::UndefValue::get(Builder.getInt32Ty())};
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001361 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1362 Value = Builder.CreateShuffleVector(Value,
1363 llvm::UndefValue::get(VecTy),
1364 MaskV, "extractVec");
1365 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1366 }
John McCall7f416cc2015-09-08 08:05:57 +00001367 if (Addr.getElementType() != SrcTy) {
1368 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001369 }
1370 }
Craig Topper99e79272013-07-26 05:59:26 +00001371
John McCall3a7f6922010-10-27 20:58:56 +00001372 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001373
David Majnemera5b195a2015-02-14 01:35:12 +00001374 if (Ty->isAtomicType() ||
1375 (!isInit && typeIsSuitableForInlineAtomic(Ty, Volatile))) {
John McCalla8ec7eb2013-03-07 21:37:17 +00001376 EmitAtomicStore(RValue::get(Value),
John McCall7f416cc2015-09-08 08:05:57 +00001377 LValue::MakeAddr(Addr, Ty, getContext(),
1378 AlignSource, TBAAInfo),
John McCalla8ec7eb2013-03-07 21:37:17 +00001379 isInit);
1380 return;
1381 }
1382
Daniel Dunbar03816342010-08-21 02:24:36 +00001383 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001384 if (isNontemporal) {
1385 llvm::MDNode *Node =
1386 llvm::MDNode::get(Store->getContext(),
1387 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1388 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1389 }
Manman Renc451e572013-04-04 21:53:22 +00001390 if (TBAAInfo) {
1391 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1392 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001393 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001394 CGM.DecorateInstructionWithTBAA(Store, TBAAPath,
1395 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001396 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001397}
1398
David Chisnallfa35df62012-01-16 17:27:18 +00001399void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001400 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001401 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001402 lvalue.getType(), lvalue.getAlignmentSource(),
Manman Renc451e572013-04-04 21:53:22 +00001403 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001404 lvalue.getTBAAOffset(), lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001405}
1406
Mike Stump4a3999f2009-09-09 13:00:44 +00001407/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1408/// method emits the address of the lvalue, then loads the result as an rvalue,
1409/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001410RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001411 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001412 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001413 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001414 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1415 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001416 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001417 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1418 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1419 Object = EmitObjCConsumeObject(LV.getType(), Object);
1420 return RValue::get(Object);
1421 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001422
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001423 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001424 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001425
John McCalla1dee5302010-08-22 10:59:02 +00001426 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001427 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001428 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001429
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001430 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001431 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001432 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001433 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001434 "vecext"));
1435 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001436
1437 // If this is a reference to a subset of the elements of a vector, either
1438 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001439 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001440 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001441
Renato Golin230c5eb2014-05-19 18:15:42 +00001442 // Global Register variables always invoke intrinsics
1443 if (LV.isGlobalReg())
1444 return EmitLoadOfGlobalRegLValue(LV);
1445
John McCallc109a252011-11-07 03:59:57 +00001446 assert(LV.isBitField() && "Unknown LValue type!");
1447 return EmitLoadOfBitfieldLValue(LV);
Chris Lattner8394d792007-06-05 20:53:16 +00001448}
1449
John McCall55e1fbc2011-06-25 02:11:03 +00001450RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001451 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001452
Daniel Dunbar3447a022010-04-13 23:34:15 +00001453 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001454 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001455
John McCall7f416cc2015-09-08 08:05:57 +00001456 Address Ptr = LV.getBitFieldAddress();
1457 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001458
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001459 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001460 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001461 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1462 if (HighBits)
1463 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1464 if (Info.Offset + HighBits)
1465 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1466 } else {
1467 if (Info.Offset)
1468 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001469 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001470 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1471 Info.Size),
1472 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001473 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001474 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001475
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001476 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001477}
1478
Nate Begemanb699c9b2009-01-18 06:42:49 +00001479// If this is a reference to a subset of the elements of a vector, create an
1480// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001481RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001482 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1483 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001484
Nate Begemanf322eab2008-05-09 06:41:27 +00001485 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001486
1487 // If the result of the expression is a non-vector type, we must be extracting
1488 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001489 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001490 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001491 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001492 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001493 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001494 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001495
1496 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001497 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001498
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001499 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001500 for (unsigned i = 0; i != NumResultElts; ++i)
1501 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001502
Chris Lattner91c08ad2011-02-15 00:14:06 +00001503 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1504 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001505 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001506 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001507}
1508
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001509/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001510Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1511 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001512 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1513 QualType EQT = ExprVT->getElementType();
1514 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001515
John McCall7f416cc2015-09-08 08:05:57 +00001516 Address CastToPointerElement =
1517 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1518 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001519
1520 const llvm::Constant *Elts = LV.getExtVectorElts();
1521 unsigned ix = getAccessedFieldNo(0, Elts);
1522
John McCall7f416cc2015-09-08 08:05:57 +00001523 Address VectorBasePtrPlusIx =
1524 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1525 getContext().getTypeSizeInChars(EQT),
1526 "vector.elt");
1527
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001528 return VectorBasePtrPlusIx;
1529}
1530
Renato Golin230c5eb2014-05-19 18:15:42 +00001531/// @brief Load of global gamed gegisters are always calls to intrinsics.
1532RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001533 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1534 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001535 llvm::MDNode *RegName = cast<llvm::MDNode>(
1536 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001537
1538 // We accept integer and pointer types only
1539 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1540 llvm::Type *Ty = OrigTy;
1541 if (OrigTy->isPointerTy())
1542 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1543 llvm::Type *Types[] = { Ty };
1544
Renato Golin230c5eb2014-05-19 18:15:42 +00001545 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001546 llvm::Value *Call = Builder.CreateCall(
1547 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001548 if (OrigTy->isPointerTy())
1549 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001550 return RValue::get(Call);
1551}
Chris Lattner40ff7012007-08-03 16:18:34 +00001552
Chris Lattner9369a562007-06-29 16:31:29 +00001553
Chris Lattner8394d792007-06-05 20:53:16 +00001554/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1555/// lvalue, where both are guaranteed to the have the same type, and that type
1556/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001557void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001558 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001559 if (!Dst.isSimple()) {
1560 if (Dst.isVectorElt()) {
1561 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001562 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1563 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001564 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001565 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001566 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1567 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001568 return;
1569 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001570
Nate Begemance4d7fc2008-04-18 23:10:10 +00001571 // If this is an update of extended vector elements, insert them as
1572 // appropriate.
1573 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001574 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001575
Renato Golin230c5eb2014-05-19 18:15:42 +00001576 if (Dst.isGlobalReg())
1577 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1578
John McCallc109a252011-11-07 03:59:57 +00001579 assert(Dst.isBitField() && "Unknown LValue type");
1580 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001581 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001582
John McCall31168b02011-06-15 23:02:42 +00001583 // There's special magic for assigning into an ARC-qualified l-value.
1584 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1585 switch (Lifetime) {
1586 case Qualifiers::OCL_None:
1587 llvm_unreachable("present but none");
1588
1589 case Qualifiers::OCL_ExplicitNone:
1590 // nothing special
1591 break;
1592
1593 case Qualifiers::OCL_Strong:
John McCall55e1fbc2011-06-25 02:11:03 +00001594 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001595 return;
1596
1597 case Qualifiers::OCL_Weak:
1598 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1599 return;
1600
1601 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001602 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1603 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001604 // fall into the normal path
1605 break;
1606 }
1607 }
1608
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001609 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001610 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001611 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001612 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001613 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001614 return;
1615 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001616
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001617 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001618 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001619 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001620 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001621 if (Dst.isObjCIvar()) {
1622 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001623 llvm::Type *ResultType = IntPtrTy;
1624 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1625 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001626 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001627 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001628 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1629 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001630 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001631 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001632 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001633 } else if (Dst.isGlobalObjCRef()) {
1634 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1635 Dst.isThreadLocalRef());
1636 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001637 else
1638 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001639 return;
1640 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001641
Chris Lattner6278e6a2007-08-11 00:04:45 +00001642 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001643 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001644}
1645
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001646void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001647 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001648 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001649 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001650 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001651
Daniel Dunbar67aba792010-04-15 03:47:33 +00001652 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001653 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001654
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001655 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001656 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001657 /*IsSigned=*/false);
1658 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001659
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001660 // See if there are other bits in the bitfield's storage we'll need to load
1661 // and mask together with source before storing.
1662 if (Info.StorageSize != Info.Size) {
1663 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001664 llvm::Value *Val =
1665 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001666
1667 // Mask the source value as needed.
1668 if (!hasBooleanRepresentation(Dst.getType()))
1669 SrcVal = Builder.CreateAnd(SrcVal,
1670 llvm::APInt::getLowBitsSet(Info.StorageSize,
1671 Info.Size),
1672 "bf.value");
1673 MaskedVal = SrcVal;
1674 if (Info.Offset)
1675 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1676
1677 // Mask out the original value.
1678 Val = Builder.CreateAnd(Val,
1679 ~llvm::APInt::getBitsSet(Info.StorageSize,
1680 Info.Offset,
1681 Info.Offset + Info.Size),
1682 "bf.clear");
1683
1684 // Or together the unchanged values and the source value.
1685 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1686 } else {
1687 assert(Info.Offset == 0);
1688 }
1689
1690 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001691 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001692
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001693 // Return the new value of the bit-field, if requested.
1694 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001695 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001696
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001697 // Sign extend the value if needed.
1698 if (Info.IsSigned) {
1699 assert(Info.Size <= Info.StorageSize);
1700 unsigned HighBits = Info.StorageSize - Info.Size;
1701 if (HighBits) {
1702 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1703 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1704 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001705 }
1706
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001707 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1708 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001709 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001710 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001711}
1712
Nate Begemance4d7fc2008-04-18 23:10:10 +00001713void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001714 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001715 // This access turns into a read/modify/write of the vector. Load the input
1716 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001717 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1718 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001719 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001720
Chris Lattner4647a212007-08-31 22:49:20 +00001721 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001722
John McCall55e1fbc2011-06-25 02:11:03 +00001723 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001724 unsigned NumSrcElts = VTy->getNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001725 unsigned NumDstElts =
1726 cast<llvm::VectorType>(Vec->getType())->getNumElements();
1727 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001728 // Use shuffle vector is the src and destination are the same number of
1729 // elements and restore the vector mask since it is on the side it will be
1730 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001731 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001732 for (unsigned i = 0; i != NumSrcElts; ++i)
1733 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001734
Chris Lattner91c08ad2011-02-15 00:14:06 +00001735 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001736 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001737 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001738 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001739 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001740 // Extended the source vector to the same length and then shuffle it
1741 // into the destination.
1742 // FIXME: since we're shuffling with undef, can we just use the indices
1743 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001744 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001745 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001746 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001747 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001748 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001749 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001750 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001751 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001752 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001753 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001754 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001755 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001756 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001757
Joey Goulycf4143b2013-11-21 17:09:05 +00001758 // When the vector size is odd and .odd or .hi is used, the last element
1759 // of the Elts constant array will be one past the size of the vector.
1760 // Ignore the last element here, if it is greater than the mask size.
1761 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1762 NumSrcElts--;
1763
Nate Begemanb699c9b2009-01-18 06:42:49 +00001764 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001765 for (unsigned i = 0; i != NumSrcElts; ++i)
1766 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001767 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001768 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001769 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001770 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001771 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001772 }
1773 } else {
1774 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001775 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001776 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001777 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001778 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001779
John McCall7f416cc2015-09-08 08:05:57 +00001780 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1781 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001782}
1783
Renato Golin230c5eb2014-05-19 18:15:42 +00001784/// @brief Store of global named registers are always calls to intrinsics.
1785void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001786 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1787 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001788 llvm::MDNode *RegName = cast<llvm::MDNode>(
1789 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00001790 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00001791
1792 // We accept integer and pointer types only
1793 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1794 llvm::Type *Ty = OrigTy;
1795 if (OrigTy->isPointerTy())
1796 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1797 llvm::Type *Types[] = { Ty };
1798
Renato Golin230c5eb2014-05-19 18:15:42 +00001799 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1800 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00001801 if (OrigTy->isPointerTy())
1802 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00001803 Builder.CreateCall(
1804 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00001805}
1806
Eric Christopherc9e2a682014-05-20 17:10:39 +00001807// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001808// generating write-barries API. It is currently a global, ivar,
1809// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001810static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001811 LValue &LV,
1812 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001813 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001814 return;
Craig Topper99e79272013-07-26 05:59:26 +00001815
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001816 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001817 QualType ExpTy = E->getType();
1818 if (IsMemberAccess && ExpTy->isPointerType()) {
1819 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00001820 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001821 // writer-barrier conservatively.
1822 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1823 if (ExpTy->isRecordType()) {
1824 LV.setObjCIvar(false);
1825 return;
1826 }
1827 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001828 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001829 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001830 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001831 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001832 return;
1833 }
Craig Topper99e79272013-07-26 05:59:26 +00001834
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001835 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1836 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001837 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001838 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00001839 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001840 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001841 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001842 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001843 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001844 }
Craig Topper99e79272013-07-26 05:59:26 +00001845
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001846 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001847 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001848 return;
1849 }
Craig Topper99e79272013-07-26 05:59:26 +00001850
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001851 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001852 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001853 if (LV.isObjCIvar()) {
1854 // If cast is to a structure pointer, follow gcc's behavior and make it
1855 // a non-ivar write-barrier.
1856 QualType ExpTy = E->getType();
1857 if (ExpTy->isPointerType())
1858 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1859 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00001860 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001861 }
1862 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001863 }
Peter Collingbourne91147592011-04-15 00:35:48 +00001864
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001865 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001866 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1867 return;
1868 }
1869
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001870 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001871 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001872 return;
1873 }
Craig Topper99e79272013-07-26 05:59:26 +00001874
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001875 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001876 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001877 return;
1878 }
John McCall31168b02011-06-15 23:02:42 +00001879
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001880 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001881 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00001882 return;
1883 }
1884
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001885 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001886 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00001887 if (LV.isObjCIvar() && !LV.isObjCArray())
1888 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001889 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00001890 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001891 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00001892 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001893 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001894 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001895 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001896 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001897
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001898 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001899 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001900 // We don't know if member is an 'ivar', but this flag is looked at
1901 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001902 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001903 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001904 }
1905}
1906
Chris Lattner3f32d692011-07-12 06:52:18 +00001907static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00001908EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00001909 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001910 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00001911 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00001912 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00001913}
1914
Alexey Bataev97720002014-11-11 04:05:39 +00001915static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00001916 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
1917 llvm::Type *RealVarTy, SourceLocation Loc) {
1918 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
1919 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
1920 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
1921}
1922
1923Address CodeGenFunction::EmitLoadOfReference(Address Addr,
1924 const ReferenceType *RefTy,
1925 AlignmentSource *Source) {
1926 llvm::Value *Ptr = Builder.CreateLoad(Addr);
1927 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
1928 Source, /*forPointee*/ true));
1929
1930}
1931
1932LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
1933 const ReferenceType *RefTy) {
1934 AlignmentSource Source;
1935 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &Source);
1936 return MakeAddrLValue(Addr, RefTy->getPointeeType(), Source);
Alexey Bataev97720002014-11-11 04:05:39 +00001937}
1938
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001939static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1940 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00001941 QualType T = E->getType();
1942
1943 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00001944 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1945 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00001946 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
1947
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001948 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001949 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
1950 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00001951 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00001952 Address Addr(V, Alignment);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001953 LValue LV;
Alexey Bataev97720002014-11-11 04:05:39 +00001954 // Emit reference to the private copy of the variable if it is an OpenMP
1955 // threadprivate variable.
1956 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001957 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001958 E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001959 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
1960 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001961 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001962 LV = CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001963 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001964 setObjCGCLValueClass(CGF.getContext(), E, LV);
1965 return LV;
1966}
1967
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001968static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
Chris Lattner13ee4f42011-07-10 05:34:54 +00001969 const Expr *E, const FunctionDecl *FD) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00001970 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001971 if (!FD->hasPrototype()) {
1972 if (const FunctionProtoType *Proto =
1973 FD->getType()->getAs<FunctionProtoType>()) {
1974 // Ugly case: for a K&R-style definition, the type of the definition
1975 // isn't the same as the type of a use. Correct for this with a
1976 // bitcast.
1977 QualType NoProtoType =
Alp Toker314cc812014-01-25 16:55:45 +00001978 CGF.getContext().getFunctionNoProtoType(Proto->getReturnType());
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001979 NoProtoType = CGF.getContext().getPointerType(NoProtoType);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001980 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001981 }
1982 }
Eli Friedmana0544d62011-12-03 04:14:32 +00001983 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
John McCall7f416cc2015-09-08 08:05:57 +00001984 return CGF.MakeAddrLValue(V, E->getType(), Alignment, AlignmentSource::Decl);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001985}
1986
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00001987static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
1988 llvm::Value *ThisValue) {
1989 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
1990 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
1991 return CGF.EmitLValueForField(LV, FD);
1992}
1993
Renato Golin230c5eb2014-05-19 18:15:42 +00001994/// Named Registers are named metadata pointing to the register name
1995/// which will be read from/written to as an argument to the intrinsic
1996/// @llvm.read/write_register.
1997/// So far, only the name is being passed down, but other options such as
1998/// register type, allocation type or even optimization options could be
1999/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002000static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002001 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002002 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002003 assert(Asm->getLabel().size() < 64-Name.size() &&
2004 "Register name too big");
2005 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002006 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002007 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002008 if (M->getNumOperands() == 0) {
2009 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2010 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002011 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002012 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2013 }
John McCall7f416cc2015-09-08 08:05:57 +00002014
2015 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2016
2017 llvm::Value *Ptr =
2018 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2019 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002020}
2021
Chris Lattnerd7f58862007-06-02 05:24:33 +00002022LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002023 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002024 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002025
Renato Goline7b3d5d2014-05-27 16:46:27 +00002026 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2027 // Global Named registers access via intrinsics only
2028 if (VD->getStorageClass() == SC_Register &&
2029 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002030 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002031
Renato Goline7b3d5d2014-05-27 16:46:27 +00002032 // A DeclRefExpr for a reference initialized by a constant expression can
2033 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002034 const Expr *Init = VD->getAnyInitializer(VD);
2035 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2036 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002037 VD->checkInitIsICE() &&
2038 // Do not emit if it is private OpenMP variable.
2039 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2040 LocalDeclMap.count(VD))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002041 llvm::Constant *Val =
2042 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2043 assert(Val && "failed to emit reference constant expression");
2044 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002045
2046 // Should we be using the alignment of the constant pointer we emitted?
2047 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2048 /*pointee*/ true);
2049
2050 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
Richard Smith5a1104b2012-10-20 01:38:33 +00002051 }
David Majnemer602cfe72015-01-01 09:49:44 +00002052
2053 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002054 if (E->refersToEnclosingVariableOrCapture()) {
David Majnemer602cfe72015-01-01 09:49:44 +00002055 if (auto *FD = LambdaCaptureFields.lookup(VD))
2056 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2057 else if (CapturedStmtInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002058 auto it = LocalDeclMap.find(VD);
2059 if (it != LocalDeclMap.end()) {
2060 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2061 return EmitLoadOfReferenceLValue(it->second, RefTy);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002062 }
John McCall7f416cc2015-09-08 08:05:57 +00002063 return MakeAddrLValue(it->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002064 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002065 LValue CapLVal =
2066 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2067 CapturedStmtInfo->getContextValue());
2068 return MakeAddrLValue(
2069 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2070 CapLVal.getType(), AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002071 }
John McCall7f416cc2015-09-08 08:05:57 +00002072
David Majnemer602cfe72015-01-01 09:49:44 +00002073 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002074 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2075 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002076 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002077 }
2078
Eli Friedman5720e342012-01-21 04:52:58 +00002079 // FIXME: We should be able to assert this for FunctionDecls as well!
2080 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2081 // those with a valid source location.
2082 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2083 !E->getLocation().isValid()) &&
2084 "Should not use decl without marking it used!");
2085
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002086 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002087 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002088 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2089 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002090 }
2091
Renato Goline7b3d5d2014-05-27 16:46:27 +00002092 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002093 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002094 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002095 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002096
John McCall7f416cc2015-09-08 08:05:57 +00002097 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002098
John McCall7f416cc2015-09-08 08:05:57 +00002099 // The variable should generally be present in the local decl map.
2100 auto iter = LocalDeclMap.find(VD);
2101 if (iter != LocalDeclMap.end()) {
2102 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002103
John McCall7f416cc2015-09-08 08:05:57 +00002104 // Otherwise, it might be static local we haven't emitted yet for
2105 // some reason; most likely, because it's in an outer function.
2106 } else if (VD->isStaticLocal()) {
2107 addr = Address(CGM.getOrCreateStaticVarDecl(
2108 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2109 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002110
John McCall7f416cc2015-09-08 08:05:57 +00002111 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002112 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002113 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2114 }
2115
2116
2117 // Check for OpenMP threadprivate variables.
2118 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2119 return EmitThreadPrivateVarDeclLValue(
2120 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2121 E->getExprLoc());
2122 }
2123
2124 // Drill into block byref variables.
2125 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2126 if (isBlockByref) {
2127 addr = emitBlockByrefAddress(addr, VD);
2128 }
2129
2130 // Drill into reference types.
2131 LValue LV;
2132 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2133 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2134 } else {
2135 LV = MakeAddrLValue(addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002136 }
Chris Lattner3f32d692011-07-12 06:52:18 +00002137
John McCallcdda29c2013-03-13 03:10:54 +00002138 bool isLocalStorage = VD->hasLocalStorage();
2139
2140 bool NonGCable = isLocalStorage &&
2141 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002142 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002143 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002144 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002145 LV.setNonGC(true);
2146 }
John McCallcdda29c2013-03-13 03:10:54 +00002147
2148 bool isImpreciseLifetime =
2149 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2150 if (isImpreciseLifetime)
2151 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002152 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002153 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002154 }
John McCallf3a88602011-02-03 08:15:49 +00002155
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002156 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002157 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002158
David Blaikie83d382b2011-09-23 05:06:16 +00002159 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002160}
Chris Lattnere47e4402007-06-01 18:02:12 +00002161
Chris Lattner8394d792007-06-05 20:53:16 +00002162LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2163 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002164 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002165 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002166
Chris Lattner0f398c42008-07-26 22:37:01 +00002167 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002168 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002169 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002170 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002171 QualType T = E->getSubExpr()->getType()->getPointeeType();
2172 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002173
John McCall7f416cc2015-09-08 08:05:57 +00002174 AlignmentSource AlignSource;
2175 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &AlignSource);
2176 LValue LV = MakeAddrLValue(Addr, T, AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002177 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002178
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002179 // We should not generate __weak write barrier on indirect reference
2180 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2181 // But, we continue to generate __strong write barrier on indirect write
2182 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002183 if (getLangOpts().ObjC1 &&
2184 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002185 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002186 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002187 return LV;
2188 }
John McCalle3027922010-08-25 11:45:40 +00002189 case UO_Real:
2190 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002191 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002192 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002193
Richard Smith0b6b8e42012-02-18 20:53:32 +00002194 // __real is valid on scalars. This is a faster way of testing that.
2195 // __imag can only produce an rvalue on scalars.
2196 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002197 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002198 assert(E->getSubExpr()->getType()->isArithmeticType());
2199 return LV;
2200 }
2201
2202 assert(E->getSubExpr()->getType()->isAnyComplexType());
2203
John McCall7f416cc2015-09-08 08:05:57 +00002204 Address Component =
2205 (E->getOpcode() == UO_Real
2206 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2207 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
2208 return MakeAddrLValue(Component, ExprTy, LV.getAlignmentSource());
Chris Lattner595db862007-10-30 22:53:42 +00002209 }
John McCalle3027922010-08-25 11:45:40 +00002210 case UO_PreInc:
2211 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002212 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002213 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002214
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002215 if (E->getType()->isAnyComplexType())
2216 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2217 else
2218 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2219 return LV;
2220 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002221 }
Chris Lattner8394d792007-06-05 20:53:16 +00002222}
2223
Chris Lattner4347e3692007-06-06 04:54:52 +00002224LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002225 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
John McCall7f416cc2015-09-08 08:05:57 +00002226 E->getType(), AlignmentSource::Decl);
Chris Lattner4347e3692007-06-06 04:54:52 +00002227}
2228
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002229LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002230 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
John McCall7f416cc2015-09-08 08:05:57 +00002231 E->getType(), AlignmentSource::Decl);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002232}
2233
Mike Stump4a3999f2009-09-09 13:00:44 +00002234LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002235 auto SL = E->getFunctionName();
2236 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2237 StringRef FnName = CurFn->getName();
2238 if (FnName.startswith("\01"))
2239 FnName = FnName.substr(1);
2240 StringRef NameItems[] = {
2241 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2242 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002243 if (CurCodeDecl && isa<BlockDecl>(CurCodeDecl)) {
John McCall7f416cc2015-09-08 08:05:57 +00002244 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2245 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002246 }
Alexey Bataevec474782014-10-09 08:45:04 +00002247 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
John McCall7f416cc2015-09-08 08:05:57 +00002248 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002249}
2250
Richard Smithe30752c2012-10-09 19:52:38 +00002251/// Emit a type description suitable for use by a runtime sanitizer library. The
2252/// format of a type descriptor is
2253///
2254/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002255/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002256/// \endcode
2257///
Richard Smith683398a2012-10-09 23:55:19 +00002258/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2259/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002260llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002261 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002262 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002263 return C;
2264
Richard Smithe30752c2012-10-09 19:52:38 +00002265 uint16_t TypeKind = -1;
2266 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002267
Richard Smithe30752c2012-10-09 19:52:38 +00002268 if (T->isIntegerType()) {
2269 TypeKind = 0;
2270 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002271 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002272 } else if (T->isFloatingType()) {
2273 TypeKind = 1;
2274 TypeInfo = getContext().getTypeSize(T);
2275 }
2276
2277 // Format the type name as if for a diagnostic, including quotes and
2278 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002279 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002280 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2281 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002282 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002283 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002284
2285 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002286 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2287 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002288 };
2289 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2290
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002291 auto *GV = new llvm::GlobalVariable(
2292 CGM.getModule(), Descriptor->getType(),
2293 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Richard Smithe30752c2012-10-09 19:52:38 +00002294 GV->setUnnamedAddr(true);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002295 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002296
2297 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002298 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002299
Richard Smithe30752c2012-10-09 19:52:38 +00002300 return GV;
2301}
2302
2303llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2304 llvm::Type *TargetTy = IntPtrTy;
2305
Richard Smith48366f72013-03-22 00:47:07 +00002306 // Floating-point types which fit into intptr_t are bitcast to integers
2307 // and then passed directly (after zero-extension, if necessary).
2308 if (V->getType()->isFloatingPointTy()) {
2309 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2310 if (Bits <= TargetTy->getIntegerBitWidth())
2311 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2312 Bits));
2313 }
2314
Richard Smithe30752c2012-10-09 19:52:38 +00002315 // Integers which fit in intptr_t are zero-extended and passed directly.
2316 if (V->getType()->isIntegerTy() &&
2317 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2318 return Builder.CreateZExt(V, TargetTy);
2319
2320 // Pointers are passed directly, everything else is passed by address.
2321 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002322 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002323 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002324 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002325 }
2326 return Builder.CreatePtrToInt(V, TargetTy);
2327}
2328
2329/// \brief Emit a representation of a SourceLocation for passing to a handler
2330/// in a sanitizer runtime library. The format for this data is:
2331/// \code
2332/// struct SourceLocation {
2333/// const char *Filename;
2334/// int32_t Line, Column;
2335/// };
2336/// \endcode
2337/// For an invalid SourceLocation, the Filename pointer is null.
2338llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002339 llvm::Constant *Filename;
2340 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002341
Alexey Samsonov6c124142014-07-18 17:50:06 +00002342 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2343 if (PLoc.isValid()) {
2344 auto FilenameGV = CGM.GetAddrOfConstantCString(PLoc.getFilename(), ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002345 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2346 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2347 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002348 Line = PLoc.getLine();
2349 Column = PLoc.getColumn();
2350 } else {
2351 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2352 Line = Column = 0;
2353 }
2354
2355 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2356 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002357
2358 return llvm::ConstantStruct::getAnon(Data);
2359}
2360
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002361namespace {
2362/// \brief Specify under what conditions this check can be recovered
2363enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002364 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002365 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002366 /// Check supports recovering, runtime has both fatal (noreturn) and
2367 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002368 Recoverable,
2369 /// Runtime conditionally aborts, always need to support recovery.
2370 AlwaysRecoverable
2371};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002372}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002373
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002374static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2375 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002376 switch (Kind) {
2377 case SanitizerKind::Vptr:
2378 return CheckRecoverableKind::AlwaysRecoverable;
2379 case SanitizerKind::Return:
2380 case SanitizerKind::Unreachable:
2381 return CheckRecoverableKind::Unrecoverable;
2382 default:
2383 return CheckRecoverableKind::Recoverable;
2384 }
2385}
2386
Alexey Samsonov88459522015-01-12 22:39:12 +00002387static void emitCheckHandlerCall(CodeGenFunction &CGF,
2388 llvm::FunctionType *FnType,
2389 ArrayRef<llvm::Value *> FnArgs,
2390 StringRef CheckName,
2391 CheckRecoverableKind RecoverKind, bool IsFatal,
2392 llvm::BasicBlock *ContBB) {
2393 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2394 bool NeedsAbortSuffix =
2395 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2396 std::string FnName = ("__ubsan_handle_" + CheckName +
2397 (NeedsAbortSuffix ? "_abort" : "")).str();
2398 bool MayReturn =
2399 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2400
2401 llvm::AttrBuilder B;
2402 if (!MayReturn) {
2403 B.addAttribute(llvm::Attribute::NoReturn)
2404 .addAttribute(llvm::Attribute::NoUnwind);
2405 }
2406 B.addAttribute(llvm::Attribute::UWTable);
2407
2408 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2409 FnType, FnName,
2410 llvm::AttributeSet::get(CGF.getLLVMContext(),
2411 llvm::AttributeSet::FunctionIndex, B));
2412 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2413 if (!MayReturn) {
2414 HandlerCall->setDoesNotReturn();
2415 CGF.Builder.CreateUnreachable();
2416 } else {
2417 CGF.Builder.CreateBr(ContBB);
2418 }
2419}
2420
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002421void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002422 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002423 StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
2424 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002425 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002426 assert(Checked.size() > 0);
Alexey Samsonov88459522015-01-12 22:39:12 +00002427
2428 llvm::Value *FatalCond = nullptr;
2429 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002430 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002431 for (int i = 0, n = Checked.size(); i < n; ++i) {
2432 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002433 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002434 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002435 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2436 ? TrapCond
2437 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2438 ? RecoverableCond
2439 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002440 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2441 }
2442
Peter Collingbourne9881b782015-06-18 23:59:22 +00002443 if (TrapCond)
2444 EmitTrapCheck(TrapCond);
2445 if (!FatalCond && !RecoverableCond)
2446 return;
2447
Alexey Samsonov88459522015-01-12 22:39:12 +00002448 llvm::Value *JointCond;
2449 if (FatalCond && RecoverableCond)
2450 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2451 else
2452 JointCond = FatalCond ? FatalCond : RecoverableCond;
2453 assert(JointCond);
2454
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002455 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
2456 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002457#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002458 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002459 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002460 "All recoverable kinds in a single check must be same!");
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002461 assert(SanOpts.has(Checked[i].second));
2462 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002463#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002464
Richard Smith4d1458e2012-09-08 02:08:36 +00002465 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002466 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2467 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002468 // Give hint that we very much don't expect to execute the handler
2469 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2470 llvm::MDBuilder MDHelper(getLLVMContext());
2471 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2472 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002473 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002474
Alexey Samsonov88459522015-01-12 22:39:12 +00002475 // Emit handler arguments and create handler function type.
Richard Smithe30752c2012-10-09 19:52:38 +00002476 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002477 auto *InfoPtr =
Will Dietz450f1a12013-01-09 03:39:41 +00002478 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
Richard Smithe30752c2012-10-09 19:52:38 +00002479 llvm::GlobalVariable::PrivateLinkage, Info);
2480 InfoPtr->setUnnamedAddr(true);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002481 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
Richard Smithe30752c2012-10-09 19:52:38 +00002482
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002483 SmallVector<llvm::Value *, 4> Args;
2484 SmallVector<llvm::Type *, 4> ArgTypes;
Richard Smithe30752c2012-10-09 19:52:38 +00002485 Args.reserve(DynamicArgs.size() + 1);
2486 ArgTypes.reserve(DynamicArgs.size() + 1);
2487
2488 // Handler functions take an i8* pointing to the (handler-specific) static
2489 // information block, followed by a sequence of intptr_t arguments
2490 // representing operand values.
2491 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2492 ArgTypes.push_back(Int8PtrTy);
2493 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2494 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2495 ArgTypes.push_back(IntPtrTy);
2496 }
2497
2498 llvm::FunctionType *FnType =
2499 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002500
Alexey Samsonov88459522015-01-12 22:39:12 +00002501 if (!FatalCond || !RecoverableCond) {
2502 // Simple case: we need to generate a single handler call, either
2503 // fatal, or non-fatal.
2504 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind,
2505 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002506 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002507 // Emit two handler calls: first one for set of unrecoverable checks,
2508 // another one for recoverable.
2509 llvm::BasicBlock *NonFatalHandlerBB =
2510 createBasicBlock("non_fatal." + CheckName);
2511 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2512 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2513 EmitBlock(FatalHandlerBB);
2514 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, true,
2515 NonFatalHandlerBB);
2516 EmitBlock(NonFatalHandlerBB);
2517 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, false,
2518 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002519 }
Richard Smithe30752c2012-10-09 19:52:38 +00002520
Richard Smith4d1458e2012-09-08 02:08:36 +00002521 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002522}
2523
Chad Rosierae229d52013-01-29 23:31:22 +00002524void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00002525 llvm::BasicBlock *Cont = createBasicBlock("cont");
2526
2527 // If we're optimizing, collapse all calls to trap down to just one per
2528 // function to save on code size.
2529 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2530 TrapBB = createBasicBlock("trap");
2531 Builder.CreateCondBr(Checked, Cont, TrapBB);
2532 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002533 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00002534 TrapCall->setDoesNotReturn();
2535 TrapCall->setDoesNotThrow();
2536 Builder.CreateUnreachable();
2537 } else {
2538 Builder.CreateCondBr(Checked, Cont, TrapBB);
2539 }
2540
2541 EmitBlock(Cont);
2542}
2543
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002544llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00002545 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002546
2547 if (!CGM.getCodeGenOpts().TrapFuncName.empty())
2548 TrapCall->addAttribute(llvm::AttributeSet::FunctionIndex,
2549 "trap-func-name",
2550 CGM.getCodeGenOpts().TrapFuncName);
2551
2552 return TrapCall;
2553}
2554
John McCall7f416cc2015-09-08 08:05:57 +00002555Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
2556 AlignmentSource *AlignSource) {
2557 assert(E->getType()->isArrayType() &&
2558 "Array to pointer decay must have array source type!");
2559
2560 // Expressions of array type can't be bitfields or vector elements.
2561 LValue LV = EmitLValue(E);
2562 Address Addr = LV.getAddress();
2563 if (AlignSource) *AlignSource = LV.getAlignmentSource();
2564
2565 // If the array type was an incomplete type, we need to make sure
2566 // the decay ends up being the right type.
2567 llvm::Type *NewTy = ConvertType(E->getType());
2568 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2569
2570 // Note that VLA pointers are always decayed, so we don't need to do
2571 // anything here.
2572 if (!E->getType()->isVariableArrayType()) {
2573 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2574 "Expected pointer to array");
2575 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2576 }
2577
2578 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2579 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2580}
2581
Chris Lattner6c5abe82010-06-26 23:03:20 +00002582/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2583/// array to pointer, return the array subexpression.
2584static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2585 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002586 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00002587 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00002588 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002589
Chris Lattner6c5abe82010-06-26 23:03:20 +00002590 // If this is a decay from variable width array, bail out.
2591 const Expr *SubExpr = CE->getSubExpr();
2592 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00002593 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002594
Chris Lattner6c5abe82010-06-26 23:03:20 +00002595 return SubExpr;
2596}
2597
John McCall7f416cc2015-09-08 08:05:57 +00002598static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
2599 llvm::Value *ptr,
2600 ArrayRef<llvm::Value*> indices,
2601 bool inbounds,
2602 const llvm::Twine &name = "arrayidx") {
2603 if (inbounds) {
2604 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name);
2605 } else {
2606 return CGF.Builder.CreateGEP(ptr, indices, name);
2607 }
2608}
2609
2610static CharUnits getArrayElementAlign(CharUnits arrayAlign,
2611 llvm::Value *idx,
2612 CharUnits eltSize) {
2613 // If we have a constant index, we can use the exact offset of the
2614 // element we're accessing.
2615 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
2616 CharUnits offset = constantIdx->getZExtValue() * eltSize;
2617 return arrayAlign.alignmentAtOffset(offset);
2618
2619 // Otherwise, use the worst-case alignment for any element.
2620 } else {
2621 return arrayAlign.alignmentOfArrayElement(eltSize);
2622 }
2623}
2624
2625static QualType getFixedSizeElementType(const ASTContext &ctx,
2626 const VariableArrayType *vla) {
2627 QualType eltType;
2628 do {
2629 eltType = vla->getElementType();
2630 } while ((vla = ctx.getAsVariableArrayType(eltType)));
2631 return eltType;
2632}
2633
2634static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
2635 ArrayRef<llvm::Value*> indices,
2636 QualType eltType, bool inbounds,
2637 const llvm::Twine &name = "arrayidx") {
2638 // All the indices except that last must be zero.
2639#ifndef NDEBUG
2640 for (auto idx : indices.drop_back())
2641 assert(isa<llvm::ConstantInt>(idx) &&
2642 cast<llvm::ConstantInt>(idx)->isZero());
2643#endif
2644
2645 // Determine the element size of the statically-sized base. This is
2646 // the thing that the indices are expressed in terms of.
2647 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
2648 eltType = getFixedSizeElementType(CGF.getContext(), vla);
2649 }
2650
2651 // We can use that to compute the best alignment of the element.
2652 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
2653 CharUnits eltAlign =
2654 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
2655
2656 llvm::Value *eltPtr =
2657 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name);
2658 return Address(eltPtr, eltAlign);
2659}
2660
Richard Smith539e4a72013-02-23 02:53:19 +00002661LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2662 bool Accessed) {
Ted Kremenekc81614d2007-08-20 16:18:38 +00002663 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner2da04b32007-08-24 05:35:26 +00002664 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Eli Friedman07bbeca2009-06-06 19:09:26 +00002665 QualType IdxTy = E->getIdx()->getType();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002666 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Eli Friedman07bbeca2009-06-06 19:09:26 +00002667
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002668 if (SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00002669 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
2670
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002671 // If the base is a vector type, then we are forming a vector element lvalue
2672 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002673 if (E->getBase()->getType()->isVectorType() &&
2674 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002675 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00002676 LValue LHS = EmitLValue(E->getBase());
Ted Kremenekc81614d2007-08-20 16:18:38 +00002677 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Eli Friedman327944b2008-06-13 23:01:12 +00002678 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
John McCall7f416cc2015-09-08 08:05:57 +00002679 E->getBase()->getType(),
2680 LHS.getAlignmentSource());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002681 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002682
John McCall7f416cc2015-09-08 08:05:57 +00002683 // All the other cases basically behave like simple offsetting.
2684
Ted Kremenekc81614d2007-08-20 16:18:38 +00002685 // Extend or truncate the index type to 32 or 64-bits.
John McCalle3dc1702011-02-15 09:22:45 +00002686 if (Idx->getType() != IntPtrTy)
2687 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
Mike Stumpd9546382009-12-12 01:27:46 +00002688
John McCall7f416cc2015-09-08 08:05:57 +00002689 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002690 if (isa<ExtVectorElementExpr>(E->getBase())) {
2691 LValue LV = EmitLValue(E->getBase());
John McCall7f416cc2015-09-08 08:05:57 +00002692 Address Addr = EmitExtVectorElementLValue(LV);
2693
2694 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
2695 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true);
2696 return MakeAddrLValue(Addr, EltType, LV.getAlignmentSource());
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002697 }
John McCall7f416cc2015-09-08 08:05:57 +00002698
2699 AlignmentSource AlignSource;
2700 Address Addr = Address::invalid();
2701 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002702 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00002703 // The base must be a pointer, which is not an aggregate. Emit
2704 // it. It needs to be emitted first in case it's what captures
2705 // the VLA bounds.
John McCall7f416cc2015-09-08 08:05:57 +00002706 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00002707
John McCall23c29fe2011-06-24 21:55:10 +00002708 // The element count here is the total number of non-VLA elements.
2709 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00002710
John McCall77527a82011-06-25 01:32:37 +00002711 // Effectively, the multiply by the VLA size is part of the GEP.
2712 // GEP indexes are signed, and scaling an index isn't permitted to
2713 // signed-overflow, so we use the same semantics for our explicit
2714 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002715 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00002716 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00002717 } else {
2718 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00002719 }
John McCall7f416cc2015-09-08 08:05:57 +00002720
2721 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
2722 !getLangOpts().isSignedOverflowDefined());
2723
Chris Lattner6c5abe82010-06-26 23:03:20 +00002724 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
2725 // Indexing over an interface, as in "NSString *P; P[4];"
John McCall7f416cc2015-09-08 08:05:57 +00002726 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
2727 llvm::Value *InterfaceSizeVal =
2728 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());;
Mike Stump4a3999f2009-09-09 13:00:44 +00002729
John McCall7f416cc2015-09-08 08:05:57 +00002730 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002731
John McCall7f416cc2015-09-08 08:05:57 +00002732 // Emit the base pointer.
2733 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
2734
2735 // We don't necessarily build correct LLVM struct types for ObjC
2736 // interfaces, so we can't rely on GEP to do this scaling
2737 // correctly, so we need to cast to i8*. FIXME: is this actually
2738 // true? A lot of other things in the fragile ABI would break...
2739 llvm::Type *OrigBaseTy = Addr.getType();
2740 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
2741
2742 // Do the GEP.
2743 CharUnits EltAlign =
2744 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
2745 llvm::Value *EltPtr =
2746 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false);
2747 Addr = Address(EltPtr, EltAlign);
2748
2749 // Cast back.
2750 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00002751 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
2752 // If this is A[i] where A is an array, the frontend will have decayed the
2753 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
2754 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
2755 // "gep x, i" here. Emit one "gep A, 0, i".
2756 assert(Array->getType()->isArrayType() &&
2757 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00002758 LValue ArrayLV;
2759 // For simple multidimensional array indexing, set the 'accessed' flag for
2760 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002761 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00002762 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
2763 else
2764 ArrayLV = EmitLValue(Array);
Craig Topper99e79272013-07-26 05:59:26 +00002765
Daniel Dunbar82634272011-04-01 00:49:43 +00002766 // Propagate the alignment from the array itself to the result.
John McCall7f416cc2015-09-08 08:05:57 +00002767 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
2768 {CGM.getSize(CharUnits::Zero()), Idx},
2769 E->getType(),
2770 !getLangOpts().isSignedOverflowDefined());
2771 AlignSource = ArrayLV.getAlignmentSource();
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002772 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002773 // The base must be a pointer; emit it with an estimate of its alignment.
2774 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
2775 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
2776 !getLangOpts().isSignedOverflowDefined());
Anders Carlsson3d312f82008-12-21 00:11:23 +00002777 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002778
John McCall7f416cc2015-09-08 08:05:57 +00002779 LValue LV = MakeAddrLValue(Addr, E->getType(), AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00002780
John McCall7f416cc2015-09-08 08:05:57 +00002781 // TODO: Preserve/extend path TBAA metadata?
John McCall8ccfcb52009-09-24 19:53:00 +00002782
Richard Smith9c6890a2012-11-01 22:30:59 +00002783 if (getLangOpts().ObjC1 &&
2784 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00002785 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002786 setObjCGCLValueClass(getContext(), E, LV);
2787 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00002788 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00002789}
2790
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002791LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
2792 bool IsLowerBound) {
2793 LValue Base;
2794 if (auto *ASE =
2795 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
2796 Base = EmitOMPArraySectionExpr(ASE, IsLowerBound);
2797 else
2798 Base = EmitLValue(E->getBase());
2799 QualType BaseTy = Base.getType();
2800 llvm::Value *Idx = nullptr;
2801 QualType ResultExprTy;
2802 if (auto *AT = getContext().getAsArrayType(BaseTy))
2803 ResultExprTy = AT->getElementType();
2804 else
2805 ResultExprTy = BaseTy->getPointeeType();
2806 if (IsLowerBound || (!IsLowerBound && E->getColonLoc().isInvalid())) {
2807 // Requesting lower bound or upper bound, but without provided length and
2808 // without ':' symbol for the default length -> length = 1.
2809 // Idx = LowerBound ?: 0;
2810 if (auto *LowerBound = E->getLowerBound()) {
2811 Idx = Builder.CreateIntCast(
2812 EmitScalarExpr(LowerBound), IntPtrTy,
2813 LowerBound->getType()->hasSignedIntegerRepresentation());
2814 } else
2815 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
2816 } else {
2817 // Try to emit length or lower bound as constant. If this is possible, 1 is
2818 // subtracted from constant length or lower bound. Otherwise, emit LLVM IR
2819 // (LB + Len) - 1.
2820 auto &C = CGM.getContext();
2821 auto *Length = E->getLength();
2822 llvm::APSInt ConstLength;
2823 if (Length) {
2824 // Idx = LowerBound + Length - 1;
2825 if (Length->isIntegerConstantExpr(ConstLength, C)) {
2826 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
2827 Length = nullptr;
2828 }
2829 auto *LowerBound = E->getLowerBound();
2830 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
2831 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
2832 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
2833 LowerBound = nullptr;
2834 }
2835 if (!Length)
2836 --ConstLength;
2837 else if (!LowerBound)
2838 --ConstLowerBound;
2839
2840 if (Length || LowerBound) {
2841 auto *LowerBoundVal =
2842 LowerBound
2843 ? Builder.CreateIntCast(
2844 EmitScalarExpr(LowerBound), IntPtrTy,
2845 LowerBound->getType()->hasSignedIntegerRepresentation())
2846 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
2847 auto *LengthVal =
2848 Length
2849 ? Builder.CreateIntCast(
2850 EmitScalarExpr(Length), IntPtrTy,
2851 Length->getType()->hasSignedIntegerRepresentation())
2852 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
2853 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
2854 /*HasNUW=*/false,
2855 !getLangOpts().isSignedOverflowDefined());
2856 if (Length && LowerBound) {
2857 Idx = Builder.CreateSub(
2858 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
2859 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
2860 }
2861 } else
2862 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
2863 } else {
2864 // Idx = ArraySize - 1;
2865 if (auto *VAT = C.getAsVariableArrayType(BaseTy)) {
2866 Length = VAT->getSizeExpr();
2867 if (Length->isIntegerConstantExpr(ConstLength, C))
2868 Length = nullptr;
2869 } else {
2870 auto *CAT = C.getAsConstantArrayType(BaseTy);
2871 ConstLength = CAT->getSize();
2872 }
2873 if (Length) {
2874 auto *LengthVal = Builder.CreateIntCast(
2875 EmitScalarExpr(Length), IntPtrTy,
2876 Length->getType()->hasSignedIntegerRepresentation());
2877 Idx = Builder.CreateSub(
2878 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
2879 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
2880 } else {
2881 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
2882 --ConstLength;
2883 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
2884 }
2885 }
2886 }
2887 assert(Idx);
2888
John McCall7f416cc2015-09-08 08:05:57 +00002889 llvm::Value *EltPtr;
2890 QualType FixedSizeEltType = ResultExprTy;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002891 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
2892 // The element count here is the total number of non-VLA elements.
2893 llvm::Value *numElements = getVLASize(VLA).first;
John McCall7f416cc2015-09-08 08:05:57 +00002894 FixedSizeEltType = getFixedSizeElementType(getContext(), VLA);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002895
2896 // Effectively, the multiply by the VLA size is part of the GEP.
2897 // GEP indexes are signed, and scaling an index isn't permitted to
2898 // signed-overflow, so we use the same semantics for our explicit
2899 // multiply. We suppress this if overflow is not undefined behavior.
2900 if (getLangOpts().isSignedOverflowDefined()) {
2901 Idx = Builder.CreateMul(Idx, numElements);
John McCall7f416cc2015-09-08 08:05:57 +00002902 EltPtr = Builder.CreateGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002903 } else {
2904 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall7f416cc2015-09-08 08:05:57 +00002905 EltPtr = Builder.CreateInBoundsGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002906 }
2907 } else if (BaseTy->isConstantArrayType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002908 llvm::Value *ArrayPtr = Base.getPointer();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002909 llvm::Value *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
2910 llvm::Value *Args[] = {Zero, Idx};
2911
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002912 if (getLangOpts().isSignedOverflowDefined())
John McCall7f416cc2015-09-08 08:05:57 +00002913 EltPtr = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002914 else
John McCall7f416cc2015-09-08 08:05:57 +00002915 EltPtr = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002916 } else {
2917 // The base must be a pointer, which is not an aggregate. Emit it.
2918 if (getLangOpts().isSignedOverflowDefined())
John McCall7f416cc2015-09-08 08:05:57 +00002919 EltPtr = Builder.CreateGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002920 else
John McCall7f416cc2015-09-08 08:05:57 +00002921 EltPtr = Builder.CreateInBoundsGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002922 }
2923
John McCall7f416cc2015-09-08 08:05:57 +00002924 CharUnits EltAlign =
2925 Base.getAlignment().alignmentOfArrayElement(
2926 getContext().getTypeSizeInChars(FixedSizeEltType));
2927
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002928 // Limit the alignment to that of the result type.
John McCall7f416cc2015-09-08 08:05:57 +00002929 LValue LV = MakeAddrLValue(Address(EltPtr, EltAlign), ResultExprTy,
2930 Base.getAlignmentSource());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002931
2932 LV.getQuals().setAddressSpace(BaseTy.getAddressSpace());
2933
2934 return LV;
2935}
2936
Chris Lattner9e751ca2007-08-02 23:37:31 +00002937LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002938EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00002939 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00002940 LValue Base;
2941
2942 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00002943 if (E->isArrow()) {
2944 // If it is a pointer to a vector, emit the address and form an lvalue with
2945 // it.
John McCall7f416cc2015-09-08 08:05:57 +00002946 AlignmentSource AlignSource;
2947 Address Ptr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Chris Lattner4e1a3232009-12-23 21:31:11 +00002948 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
John McCall7f416cc2015-09-08 08:05:57 +00002949 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002950 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00002951 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00002952 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
2953 // emit the base as an lvalue.
2954 assert(E->getBase()->getType()->isVectorType());
2955 Base = EmitLValue(E->getBase());
2956 } else {
2957 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00002958 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00002959 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00002960 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00002961
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00002962 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00002963 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002964 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00002965 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
2966 AlignmentSource::Decl);
Chris Lattner4e1a3232009-12-23 21:31:11 +00002967 }
John McCall1553b192011-06-16 04:16:24 +00002968
2969 QualType type =
2970 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00002971
Nate Begemand3862152008-05-13 21:03:02 +00002972 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00002973 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00002974 E->getEncodedElementAccess(Indices);
2975
2976 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00002977 llvm::Constant *CV =
2978 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00002979 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
John McCall7f416cc2015-09-08 08:05:57 +00002980 Base.getAlignmentSource());
Nate Begemand3862152008-05-13 21:03:02 +00002981 }
2982 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
2983
2984 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002985 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00002986
Chris Lattner595ba3a2012-01-30 06:20:36 +00002987 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
2988 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00002989 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00002990 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
2991 Base.getAlignmentSource());
Chris Lattner9e751ca2007-08-02 23:37:31 +00002992}
2993
Devang Patel30efa2e2007-10-23 20:28:39 +00002994LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00002995 Expr *BaseExpr = E->getBase();
Eli Friedman327944b2008-06-13 23:01:12 +00002996
Chris Lattner4e4186b2007-12-02 18:52:07 +00002997 // 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 +00002998 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00002999 if (E->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00003000 AlignmentSource AlignSource;
3001 Address Addr = EmitPointerWithAlignment(BaseExpr, &AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003002 QualType PtrTy = BaseExpr->getType()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003003 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy);
3004 BaseLV = MakeAddrLValue(Addr, PtrTy, AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003005 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003006 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003007
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003008 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003009 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003010 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003011 setObjCGCLValueClass(getContext(), E, LV);
3012 return LV;
3013 }
Craig Topper99e79272013-07-26 05:59:26 +00003014
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003015 if (auto *VD = dyn_cast<VarDecl>(ND))
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00003016 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003017
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003018 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003019 return EmitFunctionDeclLValue(*this, E, FD);
3020
David Blaikie83d382b2011-09-23 05:06:16 +00003021 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003022}
Devang Patel30efa2e2007-10-23 20:28:39 +00003023
John McCalldec348f72013-05-03 07:33:41 +00003024/// Given that we are currently emitting a lambda, emit an l-value for
3025/// one of its members.
3026LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3027 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3028 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3029 QualType LambdaTagType =
3030 getContext().getTagDeclType(Field->getParent());
3031 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3032 return EmitLValueForField(LambdaLV, Field);
3033}
3034
John McCall7f416cc2015-09-08 08:05:57 +00003035/// Drill down to the storage of a field without walking into
3036/// reference types.
3037///
3038/// The resulting address doesn't necessarily have the right type.
3039static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3040 const FieldDecl *field) {
3041 const RecordDecl *rec = field->getParent();
3042
3043 unsigned idx =
3044 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3045
3046 CharUnits offset;
3047 // Adjust the alignment down to the given offset.
3048 // As a special case, if the LLVM field index is 0, we know that this
3049 // is zero.
3050 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3051 .getFieldOffset(field->getFieldIndex()) == 0) &&
3052 "LLVM field at index zero had non-zero offset?");
3053 if (idx != 0) {
3054 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3055 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3056 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3057 }
3058
3059 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3060}
3061
Eli Friedman7f1ff602012-04-16 03:54:45 +00003062LValue CodeGenFunction::EmitLValueForField(LValue base,
3063 const FieldDecl *field) {
John McCall7f416cc2015-09-08 08:05:57 +00003064 AlignmentSource fieldAlignSource =
3065 getFieldAlignmentSource(base.getAlignmentSource());
3066
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003067 if (field->isBitField()) {
3068 const CGRecordLayout &RL =
3069 CGM.getTypes().getCGRecordLayout(field->getParent());
3070 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003071 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003072 unsigned Idx = RL.getLLVMFieldNo(field);
3073 if (Idx != 0)
3074 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003075 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3076 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003077 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003078 llvm::Type *FieldIntTy =
3079 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3080 if (Addr.getElementType() != FieldIntTy)
3081 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003082
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003083 QualType fieldType =
3084 field->getType().withCVRQualifiers(base.getVRQualifiers());
John McCall7f416cc2015-09-08 08:05:57 +00003085 return LValue::MakeBitfield(Addr, Info, fieldType, fieldAlignSource);
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003086 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003087
John McCall53fcbd22011-02-26 08:07:02 +00003088 const RecordDecl *rec = field->getParent();
3089 QualType type = field->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003090
John McCall53fcbd22011-02-26 08:07:02 +00003091 bool mayAlias = rec->hasAttr<MayAliasAttr>();
3092
John McCall7f416cc2015-09-08 08:05:57 +00003093 Address addr = base.getAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003094 unsigned cvr = base.getVRQualifiers();
Manman Renc451e572013-04-04 21:53:22 +00003095 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
John McCall53fcbd22011-02-26 08:07:02 +00003096 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003097 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00003098 assert(!type->isReferenceType() && "union has reference member");
Manman Renc451e572013-04-04 21:53:22 +00003099 // TODO: handle path-aware TBAA for union.
3100 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003101 } else {
3102 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003103 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003104
3105 // If this is a reference field, load the reference right now.
3106 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3107 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3108 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3109
Manman Renc451e572013-04-04 21:53:22 +00003110 // Loading the reference will disable path-aware TBAA.
3111 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003112 if (CGM.shouldUseTBAA()) {
3113 llvm::MDNode *tbaa;
3114 if (mayAlias)
3115 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3116 else
3117 tbaa = CGM.getTBAAInfo(type);
Manman Ren4f755de2013-10-08 00:08:49 +00003118 if (tbaa)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00003119 CGM.DecorateInstructionWithTBAA(load, tbaa);
John McCall53fcbd22011-02-26 08:07:02 +00003120 }
3121
John McCall53fcbd22011-02-26 08:07:02 +00003122 mayAlias = false;
3123 type = refType->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003124
3125 CharUnits alignment =
3126 getNaturalTypeAlignment(type, &fieldAlignSource, /*pointee*/ true);
3127 addr = Address(load, alignment);
3128
3129 // Qualifiers on the struct don't apply to the referencee, and
3130 // we'll pick up CVR from the actual type later, so reset these
3131 // additional qualifiers now.
3132 cvr = 0;
John McCall53fcbd22011-02-26 08:07:02 +00003133 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003134 }
Craig Topper99e79272013-07-26 05:59:26 +00003135
Chris Lattner13ee4f42011-07-10 05:34:54 +00003136 // Make sure that the address is pointing to the right type. This is critical
3137 // for both unions and structs. A union needs a bitcast, a struct element
3138 // will need a bitcast if the LLVM type laid out doesn't match the desired
3139 // type.
John McCall7f416cc2015-09-08 08:05:57 +00003140 addr = Builder.CreateElementBitCast(addr,
3141 CGM.getTypes().ConvertTypeForMem(type),
3142 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003143
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003144 if (field->hasAttr<AnnotateAttr>())
3145 addr = EmitFieldAnnotations(field, addr);
3146
John McCall7f416cc2015-09-08 08:05:57 +00003147 LValue LV = MakeAddrLValue(addr, type, fieldAlignSource);
John McCall53fcbd22011-02-26 08:07:02 +00003148 LV.getQuals().addCVRQualifiers(cvr);
Manman Renc451e572013-04-04 21:53:22 +00003149 if (TBAAPath) {
3150 const ASTRecordLayout &Layout =
3151 getContext().getASTRecordLayout(field->getParent());
3152 // Set the base type to be the base type of the base LValue and
3153 // update offset to be relative to the base type.
Manman Ren0e521662013-04-27 00:39:37 +00003154 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3155 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
Manman Renc451e572013-04-04 21:53:22 +00003156 Layout.getFieldOffset(field->getFieldIndex()) /
3157 getContext().getCharWidth());
3158 }
Daniel Dunbarf166a522010-08-21 03:44:13 +00003159
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003160 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003161 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3162 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003163
3164 // Fields of may_alias structs act like 'char' for TBAA purposes.
3165 // FIXME: this should get propagated down through anonymous structs
3166 // and unions.
3167 if (mayAlias && LV.getTBAAInfo())
3168 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3169
Daniel Dunbarf166a522010-08-21 03:44:13 +00003170 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003171}
3172
Craig Topper99e79272013-07-26 05:59:26 +00003173LValue
3174CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003175 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003176 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003177
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003178 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003179 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003180
John McCall7f416cc2015-09-08 08:05:57 +00003181 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003182
John McCall7f416cc2015-09-08 08:05:57 +00003183 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003184 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003185 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003186
John McCall7f416cc2015-09-08 08:05:57 +00003187 // TODO: access-path TBAA?
3188 auto FieldAlignSource = getFieldAlignmentSource(Base.getAlignmentSource());
3189 return MakeAddrLValue(V, FieldType, FieldAlignSource);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003190}
3191
Chris Lattnerf53c0962010-09-06 00:11:41 +00003192LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00003193 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003194 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3195 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
Richard Smith2d988f02011-11-22 22:48:32 +00003196 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003197 if (E->getType()->isVariablyModifiedType())
3198 // make sure to emit the VLA size.
3199 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003200
John McCall7f416cc2015-09-08 08:05:57 +00003201 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003202 const Expr *InitExpr = E->getInitializer();
John McCall7f416cc2015-09-08 08:05:57 +00003203 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003204
Chad Rosier615ed1a2012-03-29 17:37:10 +00003205 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3206 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003207
3208 return Result;
3209}
3210
Richard Smithbb653bd2012-05-14 21:57:21 +00003211LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3212 if (!E->isGLValue())
3213 // Initializing an aggregate temporary in C++11: T{...}.
3214 return EmitAggExprToLValue(E);
3215
3216 // An lvalue initializer list must be initializing a reference.
3217 assert(E->getNumInits() == 1 && "reference init with multiple values");
3218 return EmitLValue(E->getInit(0));
3219}
3220
Richard Smithf3076ff2014-06-20 18:43:47 +00003221/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3222/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3223/// LValue is returned and the current block has been terminated.
3224static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3225 const Expr *Operand) {
3226 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3227 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3228 return None;
3229 }
3230
3231 return CGF.EmitLValue(Operand);
3232}
3233
John McCallc07a0c72011-02-17 10:25:35 +00003234LValue CodeGenFunction::
3235EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3236 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003237 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003238 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003239 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003240 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003241 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003242
Eli Friedman59954892012-01-25 05:04:17 +00003243 OpaqueValueMapping binding(*this, expr);
3244
John McCallc07a0c72011-02-17 10:25:35 +00003245 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003246 bool CondExprBool;
3247 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003248 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003249 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003250
Justin Bogneref512b92014-01-06 22:27:43 +00003251 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003252 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003253 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003254 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003255 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003256 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003257 }
3258
John McCallc07a0c72011-02-17 10:25:35 +00003259 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3260 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3261 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003262
3263 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003264 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003265
John McCall0a6bf2e2011-01-26 19:21:13 +00003266 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003267 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003268 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003269 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003270 Optional<LValue> lhs =
3271 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003272 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003273
Richard Smithf3076ff2014-06-20 18:43:47 +00003274 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003275 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003276
John McCallc07a0c72011-02-17 10:25:35 +00003277 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003278 if (lhs)
3279 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003280
John McCall0a6bf2e2011-01-26 19:21:13 +00003281 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003282 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003283 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003284 Optional<LValue> rhs =
3285 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003286 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003287 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003288 return EmitUnsupportedLValue(expr, "conditional operator");
3289 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003290
John McCallc07a0c72011-02-17 10:25:35 +00003291 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003292
Richard Smithf3076ff2014-06-20 18:43:47 +00003293 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003294 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003295 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003296 phi->addIncoming(lhs->getPointer(), lhsBlock);
3297 phi->addIncoming(rhs->getPointer(), rhsBlock);
3298 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3299 AlignmentSource alignSource =
3300 std::max(lhs->getAlignmentSource(), rhs->getAlignmentSource());
3301 return MakeAddrLValue(result, expr->getType(), alignSource);
Richard Smithf3076ff2014-06-20 18:43:47 +00003302 } else {
3303 assert((lhs || rhs) &&
3304 "both operands of glvalue conditional are throw-expressions?");
3305 return lhs ? *lhs : *rhs;
3306 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003307}
3308
Richard Smithbb653bd2012-05-14 21:57:21 +00003309/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3310/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003311/// otherwise if a cast is needed by the code generator in an lvalue context,
3312/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003313/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003314/// are permitted with aggregate result, including noop aggregate casts, and
3315/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003316LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003317 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003318 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003319 case CK_BitCast:
3320 case CK_ArrayToPointerDecay:
3321 case CK_FunctionToPointerDecay:
3322 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003323 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003324 case CK_IntegralToPointer:
3325 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003326 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003327 case CK_VectorSplat:
3328 case CK_IntegralCast:
John McCall8cb679e2010-11-15 09:13:47 +00003329 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003330 case CK_IntegralToFloating:
3331 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003332 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003333 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003334 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003335 case CK_FloatingComplexToReal:
3336 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003337 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003338 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003339 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003340 case CK_IntegralComplexToReal:
3341 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003342 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003343 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003344 case CK_DerivedToBaseMemberPointer:
3345 case CK_BaseToDerivedMemberPointer:
3346 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003347 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003348 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003349 case CK_ARCProduceObject:
3350 case CK_ARCConsumeObject:
3351 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003352 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003353 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003354 case CK_AddressSpaceConversion:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003355 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3356
3357 case CK_Dependent:
3358 llvm_unreachable("dependent cast kind in IR gen!");
3359
3360 case CK_BuiltinFnToFnPtr:
3361 llvm_unreachable("builtin functions are handled elsewhere");
3362
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003363 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003364 case CK_NonAtomicToAtomic:
3365 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003366 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00003367
Anders Carlsson8a01a752011-04-11 02:03:26 +00003368 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00003369 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003370 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003371 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00003372 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00003373 }
3374
John McCalle3027922010-08-25 11:45:40 +00003375 case CK_ConstructorConversion:
3376 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00003377 case CK_CPointerToObjCPointerCast:
3378 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003379 case CK_NoOp:
3380 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003381 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00003382
John McCalle3027922010-08-25 11:45:40 +00003383 case CK_UncheckedDerivedToBase:
3384 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00003385 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00003386 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003387 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003388
Anders Carlssond95f9602009-09-12 16:16:49 +00003389 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003390 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00003391
Anders Carlssond95f9602009-09-12 16:16:49 +00003392 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00003393 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00003394 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3395 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00003396
John McCall7f416cc2015-09-08 08:05:57 +00003397 return MakeAddrLValue(Base, E->getType(), LV.getAlignmentSource());
Anders Carlssond95f9602009-09-12 16:16:49 +00003398 }
John McCalle3027922010-08-25 11:45:40 +00003399 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00003400 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00003401 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00003402 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003403 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003404
Anders Carlsson8c793172009-11-23 17:57:54 +00003405 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00003406
Anders Carlsson8c793172009-11-23 17:57:54 +00003407 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00003408 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00003409 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00003410 E->path_begin(), E->path_end(),
3411 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00003412
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003413 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3414 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00003415 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003416 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00003417 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003418
Peter Collingbourned2926c92015-03-14 02:42:25 +00003419 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003420 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3421 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003422 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003423
John McCall7f416cc2015-09-08 08:05:57 +00003424 return MakeAddrLValue(Derived, E->getType(), LV.getAlignmentSource());
Eli Friedman8c98dff2009-11-16 05:48:01 +00003425 }
John McCalle3027922010-08-25 11:45:40 +00003426 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00003427 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003428 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00003429
Anders Carlsson50cb3212009-11-14 21:21:42 +00003430 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003431 Address V = Builder.CreateBitCast(LV.getAddress(),
3432 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00003433
3434 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003435 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3436 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003437 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003438
John McCall7f416cc2015-09-08 08:05:57 +00003439 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Anders Carlsson50cb3212009-11-14 21:21:42 +00003440 }
John McCalle3027922010-08-25 11:45:40 +00003441 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003442 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003443 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3444 ConvertType(E->getType()));
3445 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003446 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003447 case CK_ZeroToOCLEvent:
3448 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00003449 }
Craig Topper99e79272013-07-26 05:59:26 +00003450
Douglas Gregorcdb466e2010-07-15 18:58:16 +00003451 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003452}
3453
John McCall1bf58462011-02-16 08:02:54 +00003454LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00003455 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00003456 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00003457}
3458
Eli Friedman7f1ff602012-04-16 03:54:45 +00003459RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003460 const FieldDecl *FD,
3461 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003462 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003463 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00003464 switch (getEvaluationKind(FT)) {
3465 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003466 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00003467 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00003468 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00003469 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003470 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00003471 }
3472 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003473}
Douglas Gregorfe314812011-06-21 17:03:29 +00003474
Chris Lattnere47e4402007-06-01 18:02:12 +00003475//===--------------------------------------------------------------------===//
3476// Expression Emission
3477//===--------------------------------------------------------------------===//
3478
Craig Topper99e79272013-07-26 05:59:26 +00003479RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00003480 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003481 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003482 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00003483 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003484
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003485 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003486 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003487
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003488 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00003489 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3490
Douglas Gregore0e96302011-09-06 21:41:04 +00003491 const Decl *TargetDecl = E->getCalleeDecl();
3492 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
3493 if (unsigned builtinID = FD->getBuiltinID())
Peter Collingbournef7706832014-12-12 23:41:25 +00003494 return EmitBuiltinExpr(FD, builtinID, E, ReturnValue);
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003495 }
3496
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003497 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
Anders Carlsson4034a952009-05-27 04:18:27 +00003498 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003499 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003500
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003501 if (const auto *PseudoDtor =
3502 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
John McCall31168b02011-06-15 23:02:42 +00003503 QualType DestroyedType = PseudoDtor->getDestroyedType();
Richard Smith9c6890a2012-11-01 22:30:59 +00003504 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003505 DestroyedType->isObjCLifetimeType() &&
3506 (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong ||
3507 DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) {
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003508 // Automatic Reference Counting:
3509 // If the pseudo-expression names a retainable object with weak or
3510 // strong lifetime, the object shall be released.
John McCall31168b02011-06-15 23:02:42 +00003511 Expr *BaseExpr = PseudoDtor->getBase();
John McCall7f416cc2015-09-08 08:05:57 +00003512 Address BaseValue = Address::invalid();
John McCall31168b02011-06-15 23:02:42 +00003513 Qualifiers BaseQuals;
Craig Topper99e79272013-07-26 05:59:26 +00003514
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003515 // 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 +00003516 if (PseudoDtor->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00003517 BaseValue = EmitPointerWithAlignment(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00003518 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
3519 BaseQuals = PTy->getPointeeType().getQualifiers();
3520 } else {
3521 LValue BaseLV = EmitLValue(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00003522 BaseValue = BaseLV.getAddress();
3523 QualType BaseTy = BaseExpr->getType();
3524 BaseQuals = BaseTy.getQualifiers();
3525 }
Craig Topper99e79272013-07-26 05:59:26 +00003526
John McCall31168b02011-06-15 23:02:42 +00003527 switch (PseudoDtor->getDestroyedType().getObjCLifetime()) {
3528 case Qualifiers::OCL_None:
3529 case Qualifiers::OCL_ExplicitNone:
3530 case Qualifiers::OCL_Autoreleasing:
3531 break;
Craig Topper99e79272013-07-26 05:59:26 +00003532
John McCall31168b02011-06-15 23:02:42 +00003533 case Qualifiers::OCL_Strong:
Craig Topper99e79272013-07-26 05:59:26 +00003534 EmitARCRelease(Builder.CreateLoad(BaseValue,
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003535 PseudoDtor->getDestroyedType().isVolatileQualified()),
John McCallcdda29c2013-03-13 03:10:54 +00003536 ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00003537 break;
3538
3539 case Qualifiers::OCL_Weak:
3540 EmitARCDestroyWeak(BaseValue);
3541 break;
3542 }
3543 } else {
3544 // C++ [expr.pseudo]p1:
3545 // The result shall only be used as the operand for the function call
3546 // operator (), and the result of such a call has type void. The only
3547 // effect is the evaluation of the postfix-expression before the dot or
Craig Topper99e79272013-07-26 05:59:26 +00003548 // arrow.
John McCall31168b02011-06-15 23:02:42 +00003549 EmitScalarExpr(E->getCallee());
3550 }
Craig Topper99e79272013-07-26 05:59:26 +00003551
Craig Topper8a13c412014-05-21 05:09:00 +00003552 return RValue::get(nullptr);
Douglas Gregorad8a3362009-09-04 17:36:40 +00003553 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003554
Chris Lattner2da04b32007-08-24 05:35:26 +00003555 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003556 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
3557 TargetDecl);
Chris Lattner9e47ead2007-08-31 04:44:06 +00003558}
3559
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003560LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00003561 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00003562 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00003563 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00003564 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00003565 return EmitLValue(E->getRHS());
3566 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003567
John McCalle3027922010-08-25 11:45:40 +00003568 if (E->getOpcode() == BO_PtrMemD ||
3569 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003570 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003571
John McCalla2342eb2010-12-05 02:00:02 +00003572 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00003573
3574 // Note that in all of these cases, __block variables need the RHS
3575 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00003576
3577 switch (getEvaluationKind(E->getType())) {
3578 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00003579 switch (E->getLHS()->getType().getObjCLifetime()) {
3580 case Qualifiers::OCL_Strong:
3581 return EmitARCStoreStrong(E, /*ignored*/ false).first;
3582
3583 case Qualifiers::OCL_Autoreleasing:
3584 return EmitARCStoreAutoreleasing(E).first;
3585
3586 // No reason to do any of these differently.
3587 case Qualifiers::OCL_None:
3588 case Qualifiers::OCL_ExplicitNone:
3589 case Qualifiers::OCL_Weak:
3590 break;
3591 }
3592
John McCalld0a30012010-12-06 06:10:02 +00003593 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00003594 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
John McCall55e1fbc2011-06-25 02:11:03 +00003595 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00003596 return LV;
3597 }
John McCall4f29b492010-11-16 23:07:28 +00003598
John McCall47fb9502013-03-07 21:37:08 +00003599 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00003600 return EmitComplexAssignmentLValue(E);
3601
John McCall47fb9502013-03-07 21:37:08 +00003602 case TEK_Aggregate:
3603 return EmitAggExprToLValue(E);
3604 }
3605 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003606}
3607
Christopher Lambd91c3d42007-12-29 05:02:41 +00003608LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00003609 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00003610
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003611 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00003612 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3613 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00003614
David Majnemerced8bdf2015-02-25 17:36:15 +00003615 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003616 "Can't have a scalar return unless the return type is a "
3617 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00003618
John McCall7f416cc2015-09-08 08:05:57 +00003619 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00003620}
3621
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003622LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
3623 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00003624 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003625}
3626
Anders Carlsson3be22e22009-05-30 23:23:33 +00003627LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003628 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
3629 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00003630 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00003631 EmitCXXConstructExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003632 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3633 AlignmentSource::Decl);
Anders Carlsson3be22e22009-05-30 23:23:33 +00003634}
3635
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003636LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00003637CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003638 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00003639}
3640
John McCall7f416cc2015-09-08 08:05:57 +00003641Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
3642 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
3643 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00003644}
3645
3646LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003647 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
3648 AlignmentSource::Decl);
Nico Webercf4ff5862012-10-11 10:13:44 +00003649}
3650
Mike Stumpc9b231c2009-11-15 08:09:41 +00003651LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003652CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003653 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00003654 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00003655 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003656 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
3657 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3658 AlignmentSource::Decl);
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003659}
3660
Eli Friedman5bc17122012-02-08 05:34:55 +00003661LValue
3662CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00003663 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00003664 EmitLambdaExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003665 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3666 AlignmentSource::Decl);
Eli Friedman5bc17122012-02-08 05:34:55 +00003667}
3668
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003669LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003670 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00003671
Anders Carlsson280e61f12010-06-21 20:59:55 +00003672 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00003673 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3674 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00003675
Alp Toker314cc812014-01-25 16:55:45 +00003676 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00003677 "Can't have a scalar return unless the return type is a "
3678 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00003679
John McCall7f416cc2015-09-08 08:05:57 +00003680 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003681}
3682
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003683LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003684 Address V =
3685 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
3686 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003687}
3688
Daniel Dunbar722f4242009-04-22 05:08:15 +00003689llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003690 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00003691 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003692}
3693
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003694LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
3695 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003696 const ObjCIvarDecl *Ivar,
3697 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00003698 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00003699 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003700}
3701
3702LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003703 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00003704 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003705 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00003706 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003707 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003708 if (E->isArrow()) {
3709 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003710 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00003711 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003712 } else {
3713 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00003714 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003715 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00003716 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003717 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003718
Craig Topper99e79272013-07-26 05:59:26 +00003719 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00003720 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
3721 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00003722 setObjCGCLValueClass(getContext(), E, LV);
3723 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00003724}
3725
Chris Lattnera4185c52009-04-25 19:35:26 +00003726LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00003727 // Can only get l-value for message expression returning aggregate type
3728 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00003729 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3730 AlignmentSource::Decl);
Chris Lattnera4185c52009-04-25 19:35:26 +00003731}
3732
Anders Carlsson0435ed52009-12-24 19:08:58 +00003733RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003734 const CallExpr *E, ReturnValueSlot ReturnValue,
Peter Collingbournef7706832014-12-12 23:41:25 +00003735 const Decl *TargetDecl, llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00003736 // Get the actual function type. The callee type will always be a pointer to
3737 // function type or a block pointer type.
3738 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00003739 "Call must have function pointer type!");
3740
John McCall6fd4c232009-10-23 08:22:42 +00003741 CalleeType = getContext().getCanonicalType(CalleeType);
3742
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003743 const auto *FnType =
3744 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00003745
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003746 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003747 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
3748 if (llvm::Constant *PrefixSig =
3749 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003750 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003751 llvm::Constant *FTRTTIConst =
3752 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
3753 llvm::Type *PrefixStructTyElems[] = {
3754 PrefixSig->getType(),
3755 FTRTTIConst->getType()
3756 };
3757 llvm::StructType *PrefixStructTy = llvm::StructType::get(
3758 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
3759
3760 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
3761 Callee, llvm::PointerType::getUnqual(PrefixStructTy));
3762 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00003763 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00003764 llvm::Value *CalleeSig =
3765 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003766 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
3767
3768 llvm::BasicBlock *Cont = createBasicBlock("cont");
3769 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
3770 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
3771
3772 EmitBlock(TypeCheck);
3773 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00003774 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003775 llvm::Value *CalleeRTTI =
3776 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003777 llvm::Value *CalleeRTTIMatch =
3778 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
3779 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003780 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003781 EmitCheckTypeDescriptor(CalleeType)
3782 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003783 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
3784 "function_type_mismatch", StaticData, Callee);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003785
3786 Builder.CreateBr(Cont);
3787 EmitBlock(Cont);
3788 }
3789 }
3790
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00003791 // If we are checking indirect calls and this call is indirect, check that the
3792 // function pointer is a member of the bit set for the function type.
3793 if (SanOpts.has(SanitizerKind::CFIICall) &&
3794 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
3795 SanitizerScope SanScope(this);
3796
3797 llvm::Value *BitSetName = llvm::MetadataAsValue::get(
3798 getLLVMContext(),
3799 CGM.CreateMetadataIdentifierForType(QualType(FnType, 0)));
3800
3801 llvm::Value *CastedCallee = Builder.CreateBitCast(Callee, Int8PtrTy);
3802 llvm::Value *BitSetTest =
3803 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::bitset_test),
3804 {CastedCallee, BitSetName});
3805
3806 llvm::Constant *StaticData[] = {
3807 EmitCheckSourceLocation(E->getLocStart()),
3808 EmitCheckTypeDescriptor(QualType(FnType, 0)),
3809 };
3810 EmitCheck(std::make_pair(BitSetTest, SanitizerKind::CFIICall),
3811 "cfi_bad_icall", StaticData, CastedCallee);
3812 }
3813
Daniel Dunbarc722b852008-08-30 03:02:31 +00003814 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00003815 if (Chain)
3816 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
3817 CGM.getContext().VoidPtrTy);
David Blaikief05779e2015-07-21 18:37:18 +00003818 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
3819 E->getDirectCallee(), /*ParamsToSkip*/ 0);
Daniel Dunbarc722b852008-08-30 03:02:31 +00003820
Peter Collingbournef7706832014-12-12 23:41:25 +00003821 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
3822 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00003823
3824 // C99 6.5.2.2p6:
3825 // If the expression that denotes the called function has a type
3826 // that does not include a prototype, [the default argument
3827 // promotions are performed]. If the number of arguments does not
3828 // equal the number of parameters, the behavior is undefined. If
3829 // the function is defined with a type that includes a prototype,
3830 // and either the prototype ends with an ellipsis (, ...) or the
3831 // types of the arguments after promotion are not compatible with
3832 // the types of the parameters, the behavior is undefined. If the
3833 // function is defined with a type that does not include a
3834 // prototype, and the types of the arguments after promotion are
3835 // not compatible with those of the parameters after promotion,
3836 // the behavior is undefined [except in some trivial cases].
3837 // That is, in the general case, we should assume that a call
3838 // through an unprototyped function type works like a *non-variadic*
3839 // call. The way we make this work is to cast to the exact type
3840 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00003841 //
3842 // Chain calls use this same code path to add the invisible chain parameter
3843 // to the function type.
3844 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00003845 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00003846 CalleeTy = CalleeTy->getPointerTo();
3847 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
3848 }
3849
3850 return EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00003851}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003852
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003853LValue CodeGenFunction::
3854EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003855 Address BaseAddr = Address::invalid();
3856 if (E->getOpcode() == BO_PtrMemI) {
3857 BaseAddr = EmitPointerWithAlignment(E->getLHS());
3858 } else {
3859 BaseAddr = EmitLValue(E->getLHS()).getAddress();
3860 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003861
John McCallc134eb52010-08-31 21:07:20 +00003862 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
3863
3864 const MemberPointerType *MPT
3865 = E->getRHS()->getType()->getAs<MemberPointerType>();
3866
John McCall7f416cc2015-09-08 08:05:57 +00003867 AlignmentSource AlignSource;
3868 Address MemberAddr =
3869 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT,
3870 &AlignSource);
John McCallc134eb52010-08-31 21:07:20 +00003871
John McCall7f416cc2015-09-08 08:05:57 +00003872 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), AlignSource);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003873}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003874
John McCall47fb9502013-03-07 21:37:08 +00003875/// Given the address of a temporary variable, produce an r-value of
3876/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00003877RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003878 QualType type,
3879 SourceLocation loc) {
John McCall7f416cc2015-09-08 08:05:57 +00003880 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
John McCall47fb9502013-03-07 21:37:08 +00003881 switch (getEvaluationKind(type)) {
3882 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003883 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00003884 case TEK_Aggregate:
3885 return lvalue.asAggregateRValue();
3886 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003887 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00003888 }
3889 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003890}
3891
Duncan Sandse81111c2012-04-10 08:23:07 +00003892void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003893 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00003894 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003895 return;
3896
Duncan Sands65229ed2012-04-16 16:29:47 +00003897 llvm::MDBuilder MDHelper(getLLVMContext());
3898 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003899
Duncan Sands6fc46192012-04-14 12:37:26 +00003900 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003901}
John McCallfe96e0b2011-11-06 09:01:30 +00003902
3903namespace {
3904 struct LValueOrRValue {
3905 LValue LV;
3906 RValue RV;
3907 };
3908}
3909
3910static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
3911 const PseudoObjectExpr *E,
3912 bool forLValue,
3913 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003914 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00003915
3916 // Find the result expression, if any.
3917 const Expr *resultExpr = E->getResultExpr();
3918 LValueOrRValue result;
3919
3920 for (PseudoObjectExpr::const_semantics_iterator
3921 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3922 const Expr *semantic = *i;
3923
3924 // If this semantic expression is an opaque value, bind it
3925 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003926 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00003927
3928 // If this is the result expression, we may need to evaluate
3929 // directly into the slot.
3930 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
3931 OVMA opaqueData;
3932 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00003933 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00003934 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
3935
John McCall7f416cc2015-09-08 08:05:57 +00003936 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
3937 AlignmentSource::Decl);
John McCallfe96e0b2011-11-06 09:01:30 +00003938 opaqueData = OVMA::bind(CGF, ov, LV);
3939 result.RV = slot.asRValue();
3940
3941 // Otherwise, emit as normal.
3942 } else {
3943 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
3944
3945 // If this is the result, also evaluate the result now.
3946 if (ov == resultExpr) {
3947 if (forLValue)
3948 result.LV = CGF.EmitLValue(ov);
3949 else
3950 result.RV = CGF.EmitAnyExpr(ov, slot);
3951 }
3952 }
3953
3954 opaques.push_back(opaqueData);
3955
3956 // Otherwise, if the expression is the result, evaluate it
3957 // and remember the result.
3958 } else if (semantic == resultExpr) {
3959 if (forLValue)
3960 result.LV = CGF.EmitLValue(semantic);
3961 else
3962 result.RV = CGF.EmitAnyExpr(semantic, slot);
3963
3964 // Otherwise, evaluate the expression in an ignored context.
3965 } else {
3966 CGF.EmitIgnoredExpr(semantic);
3967 }
3968 }
3969
3970 // Unbind all the opaques now.
3971 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
3972 opaques[i].unbind(CGF);
3973
3974 return result;
3975}
3976
3977RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
3978 AggValueSlot slot) {
3979 return emitPseudoObjectExpr(*this, E, false, slot).RV;
3980}
3981
3982LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
3983 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
3984}