blob: 3ecd8e3f0f6c1d7437824400e67106e5ef39e8a1 [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"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +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"
Peter Collingbournedc134532016-01-16 00:31:22 +000035#include "llvm/Transforms/Utils/SanitizerStats.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000036
Chris Lattnere47e4402007-06-01 18:02:12 +000037using namespace clang;
38using namespace CodeGen;
39
Chris Lattnerd7f58862007-06-02 05:24:33 +000040//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000041// Miscellaneous Helper Methods
42//===--------------------------------------------------------------------===//
43
John McCallad7c5c12011-02-08 08:22:06 +000044llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
45 unsigned addressSpace =
46 cast<llvm::PointerType>(value->getType())->getAddressSpace();
47
Chris Lattner2192fe52011-07-18 04:24:23 +000048 llvm::PointerType *destType = Int8PtrTy;
John McCallad7c5c12011-02-08 08:22:06 +000049 if (addressSpace)
50 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
51
52 if (value->getType() == destType) return value;
53 return Builder.CreateBitCast(value, destType);
54}
55
Chris Lattnere9a64532007-06-22 21:44:33 +000056/// CreateTempAlloca - This creates a alloca and inserts it into the entry
57/// block.
John McCall7f416cc2015-09-08 08:05:57 +000058Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
59 const Twine &Name) {
60 auto Alloca = CreateTempAlloca(Ty, Name);
61 Alloca->setAlignment(Align.getQuantity());
62 return Address(Alloca, Align);
63}
64
65/// CreateTempAlloca - This creates a alloca and inserts it into the entry
66/// block.
Chris Lattner2192fe52011-07-18 04:24:23 +000067llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000068 const Twine &Name) {
Craig Topper8a13c412014-05-21 05:09:00 +000069 return new llvm::AllocaInst(Ty, nullptr, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +000070}
Chris Lattner8394d792007-06-05 20:53:16 +000071
John McCall7f416cc2015-09-08 08:05:57 +000072/// CreateDefaultAlignTempAlloca - This creates an alloca with the
73/// default alignment of the corresponding LLVM type, which is *not*
74/// guaranteed to be related in any way to the expected alignment of
75/// an AST type that might have been lowered to Ty.
76Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
77 const Twine &Name) {
78 CharUnits Align =
79 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
80 return CreateTempAlloca(Ty, Align, Name);
81}
82
83void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
84 assert(isa<llvm::AllocaInst>(Var.getPointer()));
85 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
86 Store->setAlignment(Var.getAlignment().getQuantity());
John McCall2e6567a2010-04-22 01:10:34 +000087 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +000088 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
John McCall2e6567a2010-04-22 01:10:34 +000089}
90
John McCall7f416cc2015-09-08 08:05:57 +000091Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +000092 CharUnits Align = getContext().getTypeAlignInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +000093 return CreateTempAlloca(ConvertType(Ty), Align, Name);
Daniel Dunbard0049182010-02-16 19:44:13 +000094}
95
John McCall7f416cc2015-09-08 08:05:57 +000096Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name) {
Daniel Dunbara7566f12010-02-09 02:48:28 +000097 // FIXME: Should we prefer the preferred type alignment here?
John McCall7f416cc2015-09-08 08:05:57 +000098 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name);
99}
100
101Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
102 const Twine &Name) {
103 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name);
Daniel Dunbara7566f12010-02-09 02:48:28 +0000104}
105
Chris Lattner8394d792007-06-05 20:53:16 +0000106/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
107/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000108llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000109 PGO.setCurrentStmt(E);
John McCall7a9aac22010-08-23 01:21:21 +0000110 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +0000111 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +0000112 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +0000113 }
John McCall7a9aac22010-08-23 01:21:21 +0000114
115 QualType BoolTy = getContext().BoolTy;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000116 SourceLocation Loc = E->getExprLoc();
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000117 if (!E->getType()->isAnyComplexType())
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000118 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +0000119
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000120 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
121 Loc);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000122}
123
John McCalla2342eb2010-12-05 02:00:02 +0000124/// EmitIgnoredExpr - Emit code to compute the specified expression,
125/// ignoring the result.
126void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
127 if (E->isRValue())
128 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
129
130 // Just emit it as an l-value and drop the result.
131 EmitLValue(E);
132}
133
John McCall7a626f62010-09-15 10:14:12 +0000134/// EmitAnyExpr - Emit code to compute the specified expression which
135/// can have any type. The result is returned as an RValue struct.
136/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000137/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000138RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
139 AggValueSlot aggSlot,
140 bool ignoreResult) {
John McCall47fb9502013-03-07 21:37:08 +0000141 switch (getEvaluationKind(E->getType())) {
142 case TEK_Scalar:
John McCall4e8ca4f2012-07-02 23:58:38 +0000143 return RValue::get(EmitScalarExpr(E, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000144 case TEK_Complex:
John McCall4e8ca4f2012-07-02 23:58:38 +0000145 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000146 case TEK_Aggregate:
147 if (!ignoreResult && aggSlot.isIgnored())
148 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
149 EmitAggExpr(E, aggSlot);
150 return aggSlot.asRValue();
151 }
152 llvm_unreachable("bad evaluation kind");
Chris Lattner4647a212007-08-31 22:49:20 +0000153}
154
Mike Stump4a3999f2009-09-09 13:00:44 +0000155/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
156/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000157RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
158 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000159
John McCall47fb9502013-03-07 21:37:08 +0000160 if (hasAggregateEvaluationKind(E->getType()))
John McCall7a626f62010-09-15 10:14:12 +0000161 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
162 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000163}
164
John McCall21886962010-04-21 10:05:39 +0000165/// EmitAnyExprToMem - Evaluate an expression into a given memory
166/// location.
167void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000168 Address Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000169 Qualifiers Quals,
170 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000171 // FIXME: This function should take an LValue as an argument.
John McCall47fb9502013-03-07 21:37:08 +0000172 switch (getEvaluationKind(E->getType())) {
173 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000174 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
John McCall47fb9502013-03-07 21:37:08 +0000175 /*isInit*/ false);
176 return;
177
178 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000179 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000180 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000181 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000182 AggValueSlot::IsAliased_t(!IsInit)));
John McCall47fb9502013-03-07 21:37:08 +0000183 return;
184 }
185
186 case TEK_Scalar: {
John McCall21886962010-04-21 10:05:39 +0000187 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000188 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000189 EmitStoreThroughLValue(RV, LV);
John McCall47fb9502013-03-07 21:37:08 +0000190 return;
John McCall21886962010-04-21 10:05:39 +0000191 }
John McCall47fb9502013-03-07 21:37:08 +0000192 }
193 llvm_unreachable("bad evaluation kind");
John McCall21886962010-04-21 10:05:39 +0000194}
195
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000196static void
197pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
John McCall7f416cc2015-09-08 08:05:57 +0000198 const Expr *E, Address ReferenceTemporary) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000199 // Objective-C++ ARC:
200 // If we are binding a reference to a temporary that has ownership, we
201 // need to perform retain/release operations on the temporary.
Richard Smith736a9472013-06-12 20:42:33 +0000202 //
203 // FIXME: This should be looking at E, not M.
John McCall460ce582015-10-22 18:38:17 +0000204 if (auto Lifetime = M->getType().getObjCLifetime()) {
205 switch (Lifetime) {
Richard Smith736a9472013-06-12 20:42:33 +0000206 case Qualifiers::OCL_None:
207 case Qualifiers::OCL_ExplicitNone:
208 // Carry on to normal cleanup handling.
209 break;
Sebastian Redl29526f02011-11-27 16:50:07 +0000210
Richard Smith736a9472013-06-12 20:42:33 +0000211 case Qualifiers::OCL_Autoreleasing:
212 // Nothing to do; cleaned up by an autorelease pool.
213 return;
214
215 case Qualifiers::OCL_Strong:
216 case Qualifiers::OCL_Weak:
217 switch (StorageDuration Duration = M->getStorageDuration()) {
218 case SD_Static:
219 // Note: we intentionally do not register a cleanup to release
220 // the object on program termination.
221 return;
222
223 case SD_Thread:
224 // FIXME: We should probably register a cleanup in this case.
225 return;
226
227 case SD_Automatic:
228 case SD_FullExpression:
Richard Smith736a9472013-06-12 20:42:33 +0000229 CodeGenFunction::Destroyer *Destroy;
230 CleanupKind CleanupKind;
231 if (Lifetime == Qualifiers::OCL_Strong) {
232 const ValueDecl *VD = M->getExtendingDecl();
233 bool Precise =
234 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
235 CleanupKind = CGF.getARCCleanupKind();
236 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
237 : &CodeGenFunction::destroyARCStrongImprecise;
238 } else {
239 // __weak objects always get EH cleanups; otherwise, exceptions
240 // could cause really nasty crashes instead of mere leaks.
241 CleanupKind = NormalAndEHCleanup;
242 Destroy = &CodeGenFunction::destroyARCWeak;
243 }
244 if (Duration == SD_FullExpression)
245 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000246 M->getType(), *Destroy,
Richard Smith736a9472013-06-12 20:42:33 +0000247 CleanupKind & EHCleanup);
248 else
249 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000250 M->getType(),
Richard Smith736a9472013-06-12 20:42:33 +0000251 *Destroy, CleanupKind & EHCleanup);
252 return;
253
254 case SD_Dynamic:
255 llvm_unreachable("temporary cannot have dynamic storage duration");
256 }
257 llvm_unreachable("unknown storage duration");
258 }
259 }
260
Craig Topper8a13c412014-05-21 05:09:00 +0000261 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
Richard Smith736a9472013-06-12 20:42:33 +0000262 if (const RecordType *RT =
263 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
264 // Get the destructor for the reference temporary.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000265 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith736a9472013-06-12 20:42:33 +0000266 if (!ClassDecl->hasTrivialDestructor())
267 ReferenceTemporaryDtor = ClassDecl->getDestructor();
268 }
269
270 if (!ReferenceTemporaryDtor)
271 return;
272
273 // Call the destructor for the temporary.
274 switch (M->getStorageDuration()) {
275 case SD_Static:
276 case SD_Thread: {
277 llvm::Constant *CleanupFn;
278 llvm::Constant *CleanupArg;
279 if (E->getType()->isArrayType()) {
280 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
John McCall7f416cc2015-09-08 08:05:57 +0000281 ReferenceTemporary, E->getType(),
David Blaikieebe87e12013-08-27 23:57:18 +0000282 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
283 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
Richard Smith736a9472013-06-12 20:42:33 +0000284 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
285 } else {
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000286 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
287 StructorType::Complete);
John McCall7f416cc2015-09-08 08:05:57 +0000288 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
Richard Smith736a9472013-06-12 20:42:33 +0000289 }
290 CGF.CGM.getCXXABI().registerGlobalDtor(
291 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
292 break;
293 }
294
295 case SD_FullExpression:
296 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
297 CodeGenFunction::destroyCXXObject,
298 CGF.getLangOpts().Exceptions);
299 break;
300
301 case SD_Automatic:
302 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
303 ReferenceTemporary, E->getType(),
304 CodeGenFunction::destroyCXXObject,
305 CGF.getLangOpts().Exceptions);
306 break;
307
308 case SD_Dynamic:
309 llvm_unreachable("temporary cannot have dynamic storage duration");
310 }
311}
312
John McCall7f416cc2015-09-08 08:05:57 +0000313static Address
Richard Smith736a9472013-06-12 20:42:33 +0000314createReferenceTemporary(CodeGenFunction &CGF,
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000315 const MaterializeTemporaryExpr *M, const Expr *Inner) {
Richard Smith736a9472013-06-12 20:42:33 +0000316 switch (M->getStorageDuration()) {
317 case SD_FullExpression:
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000318 case SD_Automatic: {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000319 // If we have a constant temporary array or record try to promote it into a
320 // constant global under the same rules a normal constant would've been
321 // promoted. This is easier on the optimizer and generally emits fewer
322 // instructions.
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000323 QualType Ty = Inner->getType();
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000324 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000325 (Ty->isArrayType() || Ty->isRecordType()) &&
326 CGF.CGM.isTypeConstant(Ty, true))
327 if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000328 auto *GV = new llvm::GlobalVariable(
329 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
330 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp");
John McCall7f416cc2015-09-08 08:05:57 +0000331 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
332 GV->setAlignment(alignment.getQuantity());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000333 // FIXME: Should we put the new global into a COMDAT?
John McCall7f416cc2015-09-08 08:05:57 +0000334 return Address(GV, alignment);
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000335 }
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000336 return CGF.CreateMemTemp(Ty, "ref.tmp");
337 }
Richard Smith736a9472013-06-12 20:42:33 +0000338 case SD_Thread:
339 case SD_Static:
Hans Wennborgf9d865b2015-03-17 16:38:58 +0000340 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
Richard Smith736a9472013-06-12 20:42:33 +0000341
342 case SD_Dynamic:
343 llvm_unreachable("temporary can't have dynamic storage duration");
344 }
345 llvm_unreachable("unknown storage duration");
346}
347
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000348LValue CodeGenFunction::
349EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000350 const Expr *E = M->GetTemporaryExpr();
Richard Smith7c5d4dc2013-06-11 02:41:00 +0000351
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000352 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
353 // as that will cause the lifetime adjustment to be lost for ARC
John McCall460ce582015-10-22 18:38:17 +0000354 auto ownership = M->getType().getObjCLifetime();
355 if (ownership != Qualifiers::OCL_None &&
356 ownership != Qualifiers::OCL_ExplicitNone) {
John McCall7f416cc2015-09-08 08:05:57 +0000357 Address Object = createReferenceTemporary(*this, M, E);
358 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
359 Object = Address(llvm::ConstantExpr::getBitCast(Var,
360 ConvertTypeForMem(E->getType())
361 ->getPointerTo(Object.getAddressSpace())),
362 Object.getAlignment());
Richard Smitha509f2f2013-06-14 03:07:01 +0000363 // We should not have emitted the initializer for this temporary as a
364 // constant.
365 assert(!Var->hasInitializer());
366 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
367 }
John McCall7f416cc2015-09-08 08:05:57 +0000368 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
369 AlignmentSource::Decl);
Richard Smitha509f2f2013-06-14 03:07:01 +0000370
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000371 switch (getEvaluationKind(E->getType())) {
372 default: llvm_unreachable("expected scalar or aggregate expression");
373 case TEK_Scalar:
374 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
375 break;
376 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000377 EmitAggExpr(E, AggValueSlot::forAddr(Object,
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000378 E->getType().getQualifiers(),
379 AggValueSlot::IsDestructed,
380 AggValueSlot::DoesNotNeedGCBarriers,
381 AggValueSlot::IsNotAliased));
382 break;
383 }
384 }
Richard Smith736a9472013-06-12 20:42:33 +0000385
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000386 pushTemporaryCleanup(*this, M, E, Object);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000387 return RefTempDst;
Jordan Roseb1312a52013-04-11 00:58:58 +0000388 }
389
Richard Smithf3fabd22013-06-03 00:17:11 +0000390 SmallVector<const Expr *, 2> CommaLHSs;
Jordan Roseb1312a52013-04-11 00:58:58 +0000391 SmallVector<SubobjectAdjustment, 2> Adjustments;
Richard Smithf3fabd22013-06-03 00:17:11 +0000392 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
393
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000394 for (const auto &Ignored : CommaLHSs)
395 EmitIgnoredExpr(Ignored);
Richard Smithf3fabd22013-06-03 00:17:11 +0000396
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000397 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
Richard Smith736a9472013-06-12 20:42:33 +0000398 if (opaque->getType()->isRecordType()) {
399 assert(Adjustments.empty());
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000400 return EmitOpaqueValueLValue(opaque);
Jordan Roseb1312a52013-04-11 00:58:58 +0000401 }
402 }
403
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000404 // Create and initialize the reference temporary.
John McCall7f416cc2015-09-08 08:05:57 +0000405 Address Object = createReferenceTemporary(*this, M, E);
406 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
407 Object = Address(llvm::ConstantExpr::getBitCast(
408 Var, ConvertTypeForMem(E->getType())->getPointerTo()),
409 Object.getAlignment());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000410 // If the temporary is a global and has a constant initializer or is a
411 // constant temporary that we promoted to a global, we may have already
412 // initialized it.
Richard Smitha509f2f2013-06-14 03:07:01 +0000413 if (!Var->hasInitializer()) {
414 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
415 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
416 }
417 } else {
418 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
419 }
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000420 pushTemporaryCleanup(*this, M, E, Object);
Jordan Roseb1312a52013-04-11 00:58:58 +0000421
Richard Smith736a9472013-06-12 20:42:33 +0000422 // Perform derived-to-base casts and/or field accesses, to get from the
423 // temporary object we created (and, potentially, for which we extended
424 // the lifetime) to the subobject we're binding the reference to.
425 for (unsigned I = Adjustments.size(); I != 0; --I) {
426 SubobjectAdjustment &Adjustment = Adjustments[I-1];
427 switch (Adjustment.Kind) {
428 case SubobjectAdjustment::DerivedToBaseAdjustment:
429 Object =
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000430 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
431 Adjustment.DerivedToBase.BasePath->path_begin(),
432 Adjustment.DerivedToBase.BasePath->path_end(),
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000433 /*NullCheckValue=*/ false, E->getExprLoc());
Richard Smith736a9472013-06-12 20:42:33 +0000434 break;
Richard Smithf3fabd22013-06-03 00:17:11 +0000435
Richard Smith736a9472013-06-12 20:42:33 +0000436 case SubobjectAdjustment::FieldAdjustment: {
John McCall7f416cc2015-09-08 08:05:57 +0000437 LValue LV = MakeAddrLValue(Object, E->getType(),
438 AlignmentSource::Decl);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000439 LV = EmitLValueForField(LV, Adjustment.Field);
Richard Smith736a9472013-06-12 20:42:33 +0000440 assert(LV.isSimple() &&
441 "materialized temporary field is not a simple lvalue");
442 Object = LV.getAddress();
443 break;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000444 }
445
Richard Smith736a9472013-06-12 20:42:33 +0000446 case SubobjectAdjustment::MemberPointerAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000447 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
John McCall7f416cc2015-09-08 08:05:57 +0000448 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
449 Adjustment.Ptr.MPT);
Richard Smith736a9472013-06-12 20:42:33 +0000450 break;
451 }
452 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000453 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000454
John McCall7f416cc2015-09-08 08:05:57 +0000455 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000456}
457
458RValue
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000459CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
460 // Emit the expression as an lvalue.
461 LValue LV = EmitLValue(E);
462 assert(LV.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000463 llvm::Value *Value = LV.getPointer();
Richard Smith736a9472013-06-12 20:42:33 +0000464
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000465 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000466 // C++11 [dcl.ref]p5 (as amended by core issue 453):
467 // If a glvalue to which a reference is directly bound designates neither
468 // an existing object or function of an appropriate type nor a region of
469 // storage of suitable size and alignment to contain an object of the
470 // reference's type, the behavior is undefined.
471 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000472 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000473 }
John McCall8680f872010-07-21 06:29:51 +0000474
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000475 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000476}
477
478
Mike Stump4a3999f2009-09-09 13:00:44 +0000479/// getAccessedFieldNo - Given an encoded value and a result number, return the
480/// input field number being accessed.
481unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000482 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000483 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
484 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000485}
486
Richard Smith4d3110a2012-10-25 02:14:12 +0000487/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
488static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
489 llvm::Value *High) {
490 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
491 llvm::Value *K47 = Builder.getInt64(47);
492 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
493 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
494 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
495 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
496 return Builder.CreateMul(B1, KMul);
497}
498
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000499bool CodeGenFunction::sanitizePerformTypeCheck() const {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000500 return SanOpts.has(SanitizerKind::Null) |
501 SanOpts.has(SanitizerKind::Alignment) |
502 SanOpts.has(SanitizerKind::ObjectSize) |
503 SanOpts.has(SanitizerKind::Vptr);
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000504}
505
Richard Smithe30752c2012-10-09 19:52:38 +0000506void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +0000507 llvm::Value *Ptr, QualType Ty,
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000508 CharUnits Alignment, bool SkipNullCheck) {
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000509 if (!sanitizePerformTypeCheck())
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000510 return;
511
Richard Smith2d8b2942012-11-01 07:22:08 +0000512 // Don't check pointers outside the default address space. The null check
513 // isn't correct, the object-size check isn't supported by LLVM, and we can't
514 // communicate the addresses to the runtime handler for the vptr check.
John McCall7f416cc2015-09-08 08:05:57 +0000515 if (Ptr->getType()->getPointerAddressSpace())
Richard Smith2d8b2942012-11-01 07:22:08 +0000516 return;
517
Alexey Samsonov24cad992014-07-17 18:46:27 +0000518 SanitizerScope SanScope(this);
519
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000520 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
Craig Topper8a13c412014-05-21 05:09:00 +0000521 llvm::BasicBlock *Done = nullptr;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000522
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000523 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
524 TCK == TCK_UpcastToVirtualBase;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000525 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
526 !SkipNullCheck) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000527 // The glvalue must not be an empty glvalue.
John McCall7f416cc2015-09-08 08:05:57 +0000528 llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr);
Richard Smith2c5868c2013-02-13 21:18:23 +0000529
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000530 if (AllowNullPointers) {
531 // When performing pointer casts, it's OK if the value is null.
Richard Smith2c5868c2013-02-13 21:18:23 +0000532 // Skip the remaining checks in that case.
533 Done = createBasicBlock("null");
534 llvm::BasicBlock *Rest = createBasicBlock("not.null");
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000535 Builder.CreateCondBr(IsNonNull, Rest, Done);
Richard Smith2c5868c2013-02-13 21:18:23 +0000536 EmitBlock(Rest);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +0000537 } else {
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000538 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
Richard Smith2c5868c2013-02-13 21:18:23 +0000539 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000540 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000541
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000542 if (SanOpts.has(SanitizerKind::ObjectSize) && !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000543 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000544
Richard Smith69d0d262012-08-24 00:54:33 +0000545 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000546 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000547 // to check this.
Matt Arsenault2f152632013-10-07 19:00:18 +0000548 // FIXME: Get object address space
549 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
550 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smith69d0d262012-08-24 00:54:33 +0000551 llvm::Value *Min = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +0000552 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
Richard Smith69d0d262012-08-24 00:54:33 +0000553 llvm::Value *LargeEnough =
David Blaikie43f9bb72015-05-18 22:14:03 +0000554 Builder.CreateICmpUGE(Builder.CreateCall(F, {CastAddr, Min}),
Richard Smith69d0d262012-08-24 00:54:33 +0000555 llvm::ConstantInt::get(IntPtrTy, Size));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000556 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
Richard Smithe30752c2012-10-09 19:52:38 +0000557 }
Richard Smith69d0d262012-08-24 00:54:33 +0000558
Richard Smithb1b0ab42012-11-05 22:21:05 +0000559 uint64_t AlignVal = 0;
560
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000561 if (SanOpts.has(SanitizerKind::Alignment)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000562 AlignVal = Alignment.getQuantity();
563 if (!Ty->isIncompleteType() && !AlignVal)
564 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
565
Richard Smith69d0d262012-08-24 00:54:33 +0000566 // The glvalue must be suitably aligned.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000567 if (AlignVal) {
568 llvm::Value *Align =
John McCall7f416cc2015-09-08 08:05:57 +0000569 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
Richard Smithb1b0ab42012-11-05 22:21:05 +0000570 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
571 llvm::Value *Aligned =
572 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000573 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000574 }
Richard Smith69d0d262012-08-24 00:54:33 +0000575 }
576
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000577 if (Checks.size() > 0) {
Richard Smithe30752c2012-10-09 19:52:38 +0000578 llvm::Constant *StaticData[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +0000579 EmitCheckSourceLocation(Loc),
Richard Smithe30752c2012-10-09 19:52:38 +0000580 EmitCheckTypeDescriptor(Ty),
581 llvm::ConstantInt::get(SizeTy, AlignVal),
582 llvm::ConstantInt::get(Int8Ty, TCK)
583 };
John McCall7f416cc2015-09-08 08:05:57 +0000584 EmitCheck(Checks, "type_mismatch", StaticData, Ptr);
Richard Smithe30752c2012-10-09 19:52:38 +0000585 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000586
Richard Smithb1b0ab42012-11-05 22:21:05 +0000587 // If possible, check that the vptr indicates that there is a subobject of
588 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000589 //
590 // C++11 [basic.life]p5,6:
591 // [For storage which does not refer to an object within its lifetime]
592 // The program has undefined behavior if:
593 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000594 // or call a non-static member function
Richard Smith4d3110a2012-10-25 02:14:12 +0000595 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000596 if (SanOpts.has(SanitizerKind::Vptr) &&
Richard Smith2c5868c2013-02-13 21:18:23 +0000597 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000598 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
599 TCK == TCK_UpcastToVirtualBase) &&
Richard Smith4d3110a2012-10-25 02:14:12 +0000600 RD && RD->hasDefinition() && RD->isDynamicClass()) {
Richard Smith4d3110a2012-10-25 02:14:12 +0000601 // Compute a hash of the mangled name of the type.
602 //
603 // FIXME: This is not guaranteed to be deterministic! Move to a
604 // fingerprinting mechanism once LLVM provides one. For the time
605 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000606 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000607 llvm::raw_svector_ostream Out(MangledName);
608 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
609 Out);
Richard Smith4d3110a2012-10-25 02:14:12 +0000610
Alexey Samsonov84856012014-07-10 22:34:19 +0000611 // Blacklist based on the mangled type.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000612 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
613 Out.str())) {
Alexey Samsonov84856012014-07-10 22:34:19 +0000614 llvm::hash_code TypeHash = hash_value(Out.str());
Richard Smith4d3110a2012-10-25 02:14:12 +0000615
Alexey Samsonov84856012014-07-10 22:34:19 +0000616 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
617 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
618 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
John McCall7f416cc2015-09-08 08:05:57 +0000619 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000620 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
621 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
Richard Smith4d3110a2012-10-25 02:14:12 +0000622
Alexey Samsonov84856012014-07-10 22:34:19 +0000623 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
624 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
Richard Smith4d3110a2012-10-25 02:14:12 +0000625
Alexey Samsonov84856012014-07-10 22:34:19 +0000626 // Look the hash up in our cache.
627 const int CacheSize = 128;
628 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
629 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
630 "__ubsan_vptr_type_cache");
631 llvm::Value *Slot = Builder.CreateAnd(Hash,
632 llvm::ConstantInt::get(IntPtrTy,
633 CacheSize-1));
634 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
635 llvm::Value *CacheVal =
John McCall7f416cc2015-09-08 08:05:57 +0000636 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
637 getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000638
639 // If the hash isn't in the cache, call a runtime handler to perform the
640 // hard work of checking whether the vptr is for an object of the right
641 // type. This will either fill in the cache and return, or produce a
642 // diagnostic.
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000643 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
Alexey Samsonov84856012014-07-10 22:34:19 +0000644 llvm::Constant *StaticData[] = {
645 EmitCheckSourceLocation(Loc),
646 EmitCheckTypeDescriptor(Ty),
647 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
648 llvm::ConstantInt::get(Int8Ty, TCK)
649 };
John McCall7f416cc2015-09-08 08:05:57 +0000650 llvm::Value *DynamicData[] = { Ptr, Hash };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000651 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
652 "dynamic_type_cache_miss", StaticData, DynamicData);
Alexey Samsonov84856012014-07-10 22:34:19 +0000653 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000654 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000655
656 if (Done) {
657 Builder.CreateBr(Done);
658 EmitBlock(Done);
659 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000660}
Chris Lattner4647a212007-08-31 22:49:20 +0000661
Richard Smith539e4a72013-02-23 02:53:19 +0000662/// Determine whether this expression refers to a flexible array member in a
663/// struct. We disable array bounds checks for such members.
664static bool isFlexibleArrayMemberExpr(const Expr *E) {
665 // For compatibility with existing code, we treat arrays of length 0 or
666 // 1 as flexible array members.
667 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000668 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000669 if (CAT->getSize().ugt(1))
670 return false;
671 } else if (!isa<IncompleteArrayType>(AT))
672 return false;
673
674 E = E->IgnoreParens();
675
676 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000677 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000678 // FIXME: If the base type of the member expr is not FD->getParent(),
679 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000680 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith539e4a72013-02-23 02:53:19 +0000681 RecordDecl::field_iterator FI(
682 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
683 return ++FI == FD->getParent()->field_end();
684 }
685 }
686
687 return false;
688}
689
690/// If Base is known to point to the start of an array, return the length of
691/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000692static llvm::Value *getArrayIndexingBound(
693 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000694 // For the vector indexing extension, the bound is the number of elements.
695 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
696 IndexedType = Base->getType();
697 return CGF.Builder.getInt32(VT->getNumElements());
698 }
699
700 Base = Base->IgnoreParens();
701
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000702 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000703 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
704 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
705 IndexedType = CE->getSubExpr()->getType();
706 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000707 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000708 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000709 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000710 return CGF.getVLASize(VAT).first;
711 }
712 }
713
Craig Topper8a13c412014-05-21 05:09:00 +0000714 return nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000715}
716
717void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
718 llvm::Value *Index, QualType IndexType,
719 bool Accessed) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000720 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
Richard Smith6b53e222013-10-22 22:51:04 +0000721 "should not be called unless adding bounds checks");
Alexey Samsonov24cad992014-07-17 18:46:27 +0000722 SanitizerScope SanScope(this);
Richard Smith2847b222013-02-24 01:56:24 +0000723
Richard Smith539e4a72013-02-23 02:53:19 +0000724 QualType IndexedType;
725 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
726 if (!Bound)
727 return;
728
729 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
730 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
731 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
732
733 llvm::Constant *StaticData[] = {
734 EmitCheckSourceLocation(E->getExprLoc()),
735 EmitCheckTypeDescriptor(IndexedType),
736 EmitCheckTypeDescriptor(IndexType)
737 };
738 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
739 : Builder.CreateICmpULE(IndexVal, BoundVal);
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000740 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds), "out_of_bounds",
741 StaticData, Index);
Richard Smith539e4a72013-02-23 02:53:19 +0000742}
743
Chris Lattner116ce8f2010-01-09 21:40:03 +0000744
Chris Lattner116ce8f2010-01-09 21:40:03 +0000745CodeGenFunction::ComplexPairTy CodeGenFunction::
746EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
747 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000748 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +0000749
Chris Lattner116ce8f2010-01-09 21:40:03 +0000750 llvm::Value *NextVal;
751 if (isa<llvm::IntegerType>(InVal.first->getType())) {
752 uint64_t AmountVal = isInc ? 1 : -1;
753 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +0000754
Chris Lattner116ce8f2010-01-09 21:40:03 +0000755 // Add the inc/dec to the real part.
756 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
757 } else {
758 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
759 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
760 if (!isInc)
761 FVal.changeSign();
762 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
Craig Topper99e79272013-07-26 05:59:26 +0000763
Chris Lattner116ce8f2010-01-09 21:40:03 +0000764 // Add the inc/dec to the real part.
765 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
766 }
Craig Topper99e79272013-07-26 05:59:26 +0000767
Chris Lattner116ce8f2010-01-09 21:40:03 +0000768 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +0000769
Chris Lattner116ce8f2010-01-09 21:40:03 +0000770 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +0000771 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Craig Topper99e79272013-07-26 05:59:26 +0000772
Chris Lattner116ce8f2010-01-09 21:40:03 +0000773 // If this is a postinc, return the value read from memory, otherwise use the
774 // updated value.
775 return isPre ? IncVal : InVal;
776}
777
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000778void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
779 CodeGenFunction *CGF) {
780 // Bind VLAs in the cast type.
781 if (CGF && E->getType()->isVariablyModifiedType())
782 CGF->EmitVariablyModifiedType(E->getType());
783
784 if (CGDebugInfo *DI = getModuleDebugInfo())
785 DI->EmitExplicitCastType(E->getType());
786}
787
Chris Lattnera45c5af2007-06-02 19:47:04 +0000788//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000789// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000790//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000791
John McCall7f416cc2015-09-08 08:05:57 +0000792/// EmitPointerWithAlignment - Given an expression of pointer type, try to
793/// derive a more accurate bound on the alignment of the pointer.
794Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
795 AlignmentSource *Source) {
796 // We allow this with ObjC object pointers because of fragile ABIs.
797 assert(E->getType()->isPointerType() ||
798 E->getType()->isObjCObjectPointerType());
799 E = E->IgnoreParens();
800
801 // Casts:
802 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000803 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
804 CGM.EmitExplicitCastExprType(ECE, this);
John McCall7f416cc2015-09-08 08:05:57 +0000805
806 switch (CE->getCastKind()) {
807 // Non-converting casts (but not C's implicit conversion from void*).
808 case CK_BitCast:
809 case CK_NoOp:
810 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
811 if (PtrTy->getPointeeType()->isVoidType())
812 break;
813
814 AlignmentSource InnerSource;
815 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerSource);
816 if (Source) *Source = InnerSource;
817
818 // If this is an explicit bitcast, and the source l-value is
819 // opaque, honor the alignment of the casted-to type.
820 if (isa<ExplicitCastExpr>(CE) &&
John McCall7f416cc2015-09-08 08:05:57 +0000821 InnerSource != AlignmentSource::Decl) {
822 Addr = Address(Addr.getPointer(),
823 getNaturalPointeeTypeAlignment(E->getType(), Source));
824 }
825
Peter Collingbourne574975e2016-01-14 02:49:48 +0000826 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
827 CE->getCastKind() == CK_BitCast) {
Peter Collingbourneee381ff2015-09-09 00:01:31 +0000828 if (auto PT = E->getType()->getAs<PointerType>())
829 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
830 /*MayBeNull=*/true,
831 CodeGenFunction::CFITCK_UnrelatedCast,
832 CE->getLocStart());
833 }
834
John McCall7f416cc2015-09-08 08:05:57 +0000835 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
836 }
837 break;
838
839 // Array-to-pointer decay.
840 case CK_ArrayToPointerDecay:
841 return EmitArrayToPointerDecay(CE->getSubExpr(), Source);
842
843 // Derived-to-base conversions.
844 case CK_UncheckedDerivedToBase:
845 case CK_DerivedToBase: {
846 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), Source);
847 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
848 return GetAddressOfBaseClass(Addr, Derived,
849 CE->path_begin(), CE->path_end(),
850 ShouldNullCheckClassCastValue(CE),
851 CE->getExprLoc());
852 }
853
854 // TODO: Is there any reason to treat base-to-derived conversions
855 // specially?
856 default:
857 break;
858 }
859 }
860
861 // Unary &.
862 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
863 if (UO->getOpcode() == UO_AddrOf) {
864 LValue LV = EmitLValue(UO->getSubExpr());
865 if (Source) *Source = LV.getAlignmentSource();
866 return LV.getAddress();
867 }
868 }
869
870 // TODO: conditional operators, comma.
871
872 // Otherwise, use the alignment of the type.
873 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), Source);
874 return Address(EmitScalarExpr(E), Align);
875}
876
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000877RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000878 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +0000879 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +0000880
881 switch (getEvaluationKind(Ty)) {
882 case TEK_Complex: {
883 llvm::Type *EltTy =
884 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +0000885 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000886 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000887 }
Craig Topper99e79272013-07-26 05:59:26 +0000888
Chris Lattner65526f02010-08-23 05:26:13 +0000889 // If this is a use of an undefined aggregate type, the aggregate must have an
890 // identifiable address. Just because the contents of the value are undefined
891 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +0000892 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000893 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +0000894 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000895 }
John McCall47fb9502013-03-07 21:37:08 +0000896
897 case TEK_Scalar:
898 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
899 }
900 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +0000901}
902
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000903RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
904 const char *Name) {
905 ErrorUnsupported(E, Name);
906 return GetUndefRValue(E->getType());
907}
908
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000909LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
910 const char *Name) {
911 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000912 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +0000913 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
914 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000915}
916
Richard Smith4d1458e2012-09-08 02:08:36 +0000917LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +0000918 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000919 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +0000920 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
921 else
922 LV = EmitLValue(E);
Daniel Dunbardc406b82010-04-05 21:36:35 +0000923 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
John McCall7f416cc2015-09-08 08:05:57 +0000924 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
Richard Smithe30752c2012-10-09 19:52:38 +0000925 E->getType(), LV.getAlignment());
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000926 return LV;
927}
928
Chris Lattner8394d792007-06-05 20:53:16 +0000929/// EmitLValue - Emit code to compute a designator that specifies the location
930/// of the expression.
931///
Mike Stump4a3999f2009-09-09 13:00:44 +0000932/// This can return one of two things: a simple address or a bitfield reference.
933/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
934/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +0000935///
Mike Stump4a3999f2009-09-09 13:00:44 +0000936/// If this returns a bitfield reference, nothing about the pointee type of the
937/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +0000938///
Mike Stump4a3999f2009-09-09 13:00:44 +0000939/// If this returns a normal address, and if the lvalue's C type is fixed size,
940/// this method guarantees that the returned pointer type will point to an LLVM
941/// type of the same size of the lvalue's type. If the lvalue has a variable
942/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +0000943///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000944LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +0000945 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +0000946 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000947 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000948
John McCallc109a252011-11-07 03:59:57 +0000949 case Expr::ObjCPropertyRefExprClass:
950 llvm_unreachable("cannot emit a property reference directly");
951
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000952 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +0000953 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000954 case Expr::ObjCIsaExprClass:
955 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000956 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +0000957 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +0000958 case Expr::CompoundAssignOperatorClass: {
959 QualType Ty = E->getType();
960 if (const AtomicType *AT = Ty->getAs<AtomicType>())
961 Ty = AT->getValueType();
962 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +0000963 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
964 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +0000965 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000966 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +0000967 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000968 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +0000969 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000970 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +0000971 case Expr::VAArgExprClass:
972 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000973 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000974 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +0000975 case Expr::ParenExprClass:
976 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +0000977 case Expr::GenericSelectionExprClass:
978 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +0000979 case Expr::PredefinedExprClass:
980 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +0000981 case Expr::StringLiteralClass:
982 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +0000983 case Expr::ObjCEncodeExprClass:
984 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +0000985 case Expr::PseudoObjectExprClass:
986 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +0000987 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +0000988 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +0000989 case Expr::CXXTemporaryObjectExprClass:
990 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +0000991 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
992 case Expr::CXXBindTemporaryExprClass:
993 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +0000994 case Expr::CXXUuidofExprClass:
995 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +0000996 case Expr::LambdaExprClass:
997 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +0000998
999 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001000 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +00001001 enterFullExpression(cleanups);
1002 RunCleanupsScope Scope(*this);
1003 return EmitLValue(cleanups->getSubExpr());
1004 }
1005
Anders Carlsson52ce3bb2009-11-14 01:51:50 +00001006 case Expr::CXXDefaultArgExprClass:
1007 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001008 case Expr::CXXDefaultInitExprClass: {
1009 CXXDefaultInitExprScope Scope(*this);
1010 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1011 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001012 case Expr::CXXTypeidExprClass:
1013 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001014
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001015 case Expr::ObjCMessageExprClass:
1016 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001017 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001018 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001019 case Expr::StmtExprClass:
1020 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001021 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001022 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001023 case Expr::ArraySubscriptExprClass:
1024 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001025 case Expr::OMPArraySectionExprClass:
1026 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001027 case Expr::ExtVectorElementExprClass:
1028 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001029 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001030 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001031 case Expr::CompoundLiteralExprClass:
1032 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001033 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001034 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001035 case Expr::BinaryConditionalOperatorClass:
1036 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001037 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001038 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001039 case Expr::OpaqueValueExprClass:
1040 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001041 case Expr::SubstNonTypeTemplateParmExprClass:
1042 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001043 case Expr::ImplicitCastExprClass:
1044 case Expr::CStyleCastExprClass:
1045 case Expr::CXXFunctionalCastExprClass:
1046 case Expr::CXXStaticCastExprClass:
1047 case Expr::CXXDynamicCastExprClass:
1048 case Expr::CXXReinterpretCastExprClass:
1049 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001050 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001051 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001052
Douglas Gregorfe314812011-06-21 17:03:29 +00001053 case Expr::MaterializeTemporaryExprClass:
1054 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001055 }
1056}
1057
John McCall71335052012-03-10 03:05:10 +00001058/// Given an object of the given canonical type, can we safely copy a
1059/// value out of it based on its initializer?
1060static bool isConstantEmittableObjectType(QualType type) {
1061 assert(type.isCanonical());
1062 assert(!type->isReferenceType());
1063
1064 // Must be const-qualified but non-volatile.
1065 Qualifiers qs = type.getLocalQualifiers();
1066 if (!qs.hasConst() || qs.hasVolatile()) return false;
1067
1068 // Otherwise, all object types satisfy this except C++ classes with
1069 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001070 if (const auto *RT = dyn_cast<RecordType>(type))
1071 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001072 if (RD->hasMutableFields() || !RD->isTrivial())
1073 return false;
1074
1075 return true;
1076}
1077
1078/// Can we constant-emit a load of a reference to a variable of the
1079/// given type? This is different from predicates like
1080/// Decl::isUsableInConstantExpressions because we do want it to apply
1081/// in situations that don't necessarily satisfy the language's rules
1082/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1083/// to do this with const float variables even if those variables
1084/// aren't marked 'constexpr'.
1085enum ConstantEmissionKind {
1086 CEK_None,
1087 CEK_AsReferenceOnly,
1088 CEK_AsValueOrReference,
1089 CEK_AsValueOnly
1090};
1091static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1092 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001093 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001094 if (isConstantEmittableObjectType(ref->getPointeeType()))
1095 return CEK_AsValueOrReference;
1096 return CEK_AsReferenceOnly;
1097 }
1098 if (isConstantEmittableObjectType(type))
1099 return CEK_AsValueOnly;
1100 return CEK_None;
1101}
1102
1103/// Try to emit a reference to the given value without producing it as
1104/// an l-value. This is actually more than an optimization: we can't
1105/// produce an l-value for variables that we never actually captured
1106/// in a block or lambda, which means const int variables or constexpr
1107/// literals or similar.
1108CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001109CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1110 ValueDecl *value = refExpr->getDecl();
1111
John McCall71335052012-03-10 03:05:10 +00001112 // The value needs to be an enum constant or a constant variable.
1113 ConstantEmissionKind CEK;
1114 if (isa<ParmVarDecl>(value)) {
1115 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001116 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001117 CEK = checkVarTypeForConstantEmission(var->getType());
1118 } else if (isa<EnumConstantDecl>(value)) {
1119 CEK = CEK_AsValueOnly;
1120 } else {
1121 CEK = CEK_None;
1122 }
1123 if (CEK == CEK_None) return ConstantEmission();
1124
John McCall71335052012-03-10 03:05:10 +00001125 Expr::EvalResult result;
1126 bool resultIsReference;
1127 QualType resultType;
1128
1129 // It's best to evaluate all the way as an r-value if that's permitted.
1130 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001131 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001132 resultIsReference = false;
1133 resultType = refExpr->getType();
1134
1135 // Otherwise, try to evaluate as an l-value.
1136 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001137 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001138 resultIsReference = true;
1139 resultType = value->getType();
1140
1141 // Failure.
1142 } else {
1143 return ConstantEmission();
1144 }
1145
1146 // In any case, if the initializer has side-effects, abandon ship.
1147 if (result.HasSideEffects)
1148 return ConstantEmission();
1149
1150 // Emit as a constant.
1151 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1152
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001153 // Make sure we emit a debug reference to the global variable.
1154 // This should probably fire even for
1155 if (isa<VarDecl>(value)) {
1156 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1157 EmitDeclRefExprDbgValue(refExpr, C);
1158 } else {
1159 assert(isa<EnumConstantDecl>(value));
1160 EmitDeclRefExprDbgValue(refExpr, C);
1161 }
John McCall71335052012-03-10 03:05:10 +00001162
1163 // If we emitted a reference constant, we need to dereference that.
1164 if (resultIsReference)
1165 return ConstantEmission::forReference(C);
1166
1167 return ConstantEmission::forValue(C);
1168}
1169
Nick Lewycky2d84e842013-10-02 02:29:49 +00001170llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1171 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +00001172 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001173 lvalue.getType(), Loc, lvalue.getAlignmentSource(),
1174 lvalue.getTBAAInfo(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001175 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1176 lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001177}
1178
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001179static bool hasBooleanRepresentation(QualType Ty) {
1180 if (Ty->isBooleanType())
1181 return true;
1182
1183 if (const EnumType *ET = Ty->getAs<EnumType>())
1184 return ET->getDecl()->getIntegerType()->isBooleanType();
1185
Douglas Gregor298f43d2012-04-12 20:42:30 +00001186 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1187 return hasBooleanRepresentation(AT->getValueType());
1188
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001189 return false;
1190}
1191
Richard Smith1629da92012-12-13 07:11:50 +00001192static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1193 llvm::APInt &Min, llvm::APInt &End,
1194 bool StrictEnums) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001195 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001196 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1197 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001198 bool IsBool = hasBooleanRepresentation(Ty);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001199 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001200 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001201
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001202 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001203 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1204 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001205 } else {
1206 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001207 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001208 unsigned Bitwidth = LTy->getScalarSizeInBits();
1209 unsigned NumNegativeBits = ED->getNumNegativeBits();
1210 unsigned NumPositiveBits = ED->getNumPositiveBits();
1211
1212 if (NumNegativeBits) {
1213 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1214 assert(NumBits <= Bitwidth);
1215 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1216 Min = -End;
1217 } else {
1218 assert(NumPositiveBits <= Bitwidth);
1219 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1220 Min = llvm::APInt(Bitwidth, 0);
1221 }
1222 }
Richard Smith1629da92012-12-13 07:11:50 +00001223 return true;
1224}
1225
1226llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1227 llvm::APInt Min, End;
1228 if (!getRangeForType(*this, Ty, Min, End,
1229 CGM.getCodeGenOpts().StrictEnums))
Craig Topper8a13c412014-05-21 05:09:00 +00001230 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001231
Duncan Sandsc720e782012-04-15 18:04:54 +00001232 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001233 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001234}
1235
John McCall7f416cc2015-09-08 08:05:57 +00001236llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1237 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001238 SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +00001239 AlignmentSource AlignSource,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001240 llvm::MDNode *TBAAInfo,
1241 QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001242 uint64_t TBAAOffset,
1243 bool isNontemporal) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001244 // For better performance, handle vector loads differently.
1245 if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001246 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001247
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001248 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001249
John McCall7f416cc2015-09-08 08:05:57 +00001250 // Handle vectors of size 3 like size 4 for better performance.
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001251 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001252
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001253 // Bitcast to vec4 type.
1254 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
1255 4);
John McCall7f416cc2015-09-08 08:05:57 +00001256 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001257 // Now load value.
John McCall7f416cc2015-09-08 08:05:57 +00001258 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001259
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001260 // Shuffle vector to get vec3.
John McCall7f416cc2015-09-08 08:05:57 +00001261 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
Benjamin Kramer99383102015-07-28 16:25:32 +00001262 {0, 1, 2}, "extractVec");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001263 return EmitFromMemory(V, Ty);
1264 }
1265 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001266
1267 // Atomic operations have to be done on integral types.
David Majnemera5b195a2015-02-14 01:35:12 +00001268 if (Ty->isAtomicType() || typeIsSuitableForInlineAtomic(Ty, Volatile)) {
John McCall7f416cc2015-09-08 08:05:57 +00001269 LValue lvalue =
1270 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
David Majnemereeaec262015-02-14 02:18:14 +00001271 return EmitAtomicLoad(lvalue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001272 }
Craig Topper99e79272013-07-26 05:59:26 +00001273
John McCall7f416cc2015-09-08 08:05:57 +00001274 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001275 if (isNontemporal) {
1276 llvm::MDNode *Node = llvm::MDNode::get(
1277 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1278 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1279 }
Manman Renc451e572013-04-04 21:53:22 +00001280 if (TBAAInfo) {
1281 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1282 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001283 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001284 CGM.DecorateInstructionWithTBAA(Load, TBAAPath,
1285 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001286 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001287
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00001288 bool NeedsBoolCheck =
1289 SanOpts.has(SanitizerKind::Bool) && hasBooleanRepresentation(Ty);
1290 bool NeedsEnumCheck =
1291 SanOpts.has(SanitizerKind::Enum) && Ty->getAs<EnumType>();
1292 if (NeedsBoolCheck || NeedsEnumCheck) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00001293 SanitizerScope SanScope(this);
Richard Smith1629da92012-12-13 07:11:50 +00001294 llvm::APInt Min, End;
1295 if (getRangeForType(*this, Ty, Min, End, true)) {
1296 --End;
1297 llvm::Value *Check;
1298 if (!Min)
1299 Check = Builder.CreateICmpULE(
1300 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1301 else {
1302 llvm::Value *Upper = Builder.CreateICmpSLE(
1303 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1304 llvm::Value *Lower = Builder.CreateICmpSGE(
1305 Load, llvm::ConstantInt::get(getLLVMContext(), Min));
1306 Check = Builder.CreateAnd(Upper, Lower);
1307 }
Nick Lewycky2d84e842013-10-02 02:29:49 +00001308 llvm::Constant *StaticArgs[] = {
1309 EmitCheckSourceLocation(Loc),
1310 EmitCheckTypeDescriptor(Ty)
1311 };
Peter Collingbourne3eea6772015-05-11 21:39:14 +00001312 SanitizerMask Kind = NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
Alexey Samsonove396bfc2014-11-11 22:03:54 +00001313 EmitCheck(std::make_pair(Check, Kind), "load_invalid_value", StaticArgs,
1314 EmitCheckValue(Load));
Richard Smith1629da92012-12-13 07:11:50 +00001315 }
1316 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001317 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1318 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001319
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001320 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001321}
1322
John McCall3a7f6922010-10-27 20:58:56 +00001323llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1324 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001325 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001326 // This should really always be an i1, but sometimes it's already
1327 // an i8, and it's awkward to track those cases down.
1328 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001329 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1330 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1331 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001332 }
1333
1334 return Value;
1335}
1336
1337llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1338 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001339 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001340 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1341 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001342 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1343 }
1344
1345 return Value;
1346}
1347
John McCall7f416cc2015-09-08 08:05:57 +00001348void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1349 bool Volatile, QualType Ty,
1350 AlignmentSource AlignSource,
1351 llvm::MDNode *TBAAInfo,
Manman Renc451e572013-04-04 21:53:22 +00001352 bool isInit, QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001353 uint64_t TBAAOffset,
1354 bool isNontemporal) {
Craig Topper99e79272013-07-26 05:59:26 +00001355
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001356 // Handle vectors differently to get better performance.
1357 if (Ty->isVectorType()) {
1358 llvm::Type *SrcTy = Value->getType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001359 auto *VecTy = cast<llvm::VectorType>(SrcTy);
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001360 // Handle vec3 special.
1361 if (VecTy->getNumElements() == 3) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001362 // Our source is a vec3, do a shuffle vector to make it a vec4.
Benjamin Kramer99383102015-07-28 16:25:32 +00001363 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1364 Builder.getInt32(2),
1365 llvm::UndefValue::get(Builder.getInt32Ty())};
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001366 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1367 Value = Builder.CreateShuffleVector(Value,
1368 llvm::UndefValue::get(VecTy),
1369 MaskV, "extractVec");
1370 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1371 }
John McCall7f416cc2015-09-08 08:05:57 +00001372 if (Addr.getElementType() != SrcTy) {
1373 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001374 }
1375 }
Craig Topper99e79272013-07-26 05:59:26 +00001376
John McCall3a7f6922010-10-27 20:58:56 +00001377 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001378
David Majnemera5b195a2015-02-14 01:35:12 +00001379 if (Ty->isAtomicType() ||
1380 (!isInit && typeIsSuitableForInlineAtomic(Ty, Volatile))) {
John McCalla8ec7eb2013-03-07 21:37:17 +00001381 EmitAtomicStore(RValue::get(Value),
John McCall7f416cc2015-09-08 08:05:57 +00001382 LValue::MakeAddr(Addr, Ty, getContext(),
1383 AlignSource, TBAAInfo),
John McCalla8ec7eb2013-03-07 21:37:17 +00001384 isInit);
1385 return;
1386 }
1387
Daniel Dunbar03816342010-08-21 02:24:36 +00001388 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001389 if (isNontemporal) {
1390 llvm::MDNode *Node =
1391 llvm::MDNode::get(Store->getContext(),
1392 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1393 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1394 }
Manman Renc451e572013-04-04 21:53:22 +00001395 if (TBAAInfo) {
1396 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1397 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001398 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001399 CGM.DecorateInstructionWithTBAA(Store, TBAAPath,
1400 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001401 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001402}
1403
David Chisnallfa35df62012-01-16 17:27:18 +00001404void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001405 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001406 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001407 lvalue.getType(), lvalue.getAlignmentSource(),
Manman Renc451e572013-04-04 21:53:22 +00001408 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001409 lvalue.getTBAAOffset(), lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001410}
1411
Mike Stump4a3999f2009-09-09 13:00:44 +00001412/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1413/// method emits the address of the lvalue, then loads the result as an rvalue,
1414/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001415RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001416 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001417 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001418 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001419 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1420 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001421 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001422 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001423 // In MRC mode, we do a load+autorelease.
1424 if (!getLangOpts().ObjCAutoRefCount) {
1425 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1426 }
1427
1428 // In ARC mode, we load retained and then consume the value.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001429 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1430 Object = EmitObjCConsumeObject(LV.getType(), Object);
1431 return RValue::get(Object);
1432 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001433
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001434 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001435 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001436
John McCalla1dee5302010-08-22 10:59:02 +00001437 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001438 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001439 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001440
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001441 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001442 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001443 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001444 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001445 "vecext"));
1446 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001447
1448 // If this is a reference to a subset of the elements of a vector, either
1449 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001450 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001451 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001452
Renato Golin230c5eb2014-05-19 18:15:42 +00001453 // Global Register variables always invoke intrinsics
1454 if (LV.isGlobalReg())
1455 return EmitLoadOfGlobalRegLValue(LV);
1456
John McCallc109a252011-11-07 03:59:57 +00001457 assert(LV.isBitField() && "Unknown LValue type!");
1458 return EmitLoadOfBitfieldLValue(LV);
Chris Lattner8394d792007-06-05 20:53:16 +00001459}
1460
John McCall55e1fbc2011-06-25 02:11:03 +00001461RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001462 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001463
Daniel Dunbar3447a022010-04-13 23:34:15 +00001464 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001465 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001466
John McCall7f416cc2015-09-08 08:05:57 +00001467 Address Ptr = LV.getBitFieldAddress();
1468 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001469
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001470 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001471 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001472 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1473 if (HighBits)
1474 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1475 if (Info.Offset + HighBits)
1476 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1477 } else {
1478 if (Info.Offset)
1479 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001480 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001481 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1482 Info.Size),
1483 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001484 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001485 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001486
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001487 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001488}
1489
Nate Begemanb699c9b2009-01-18 06:42:49 +00001490// If this is a reference to a subset of the elements of a vector, create an
1491// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001492RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001493 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1494 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001495
Nate Begemanf322eab2008-05-09 06:41:27 +00001496 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001497
1498 // If the result of the expression is a non-vector type, we must be extracting
1499 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001500 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001501 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001502 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001503 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001504 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001505 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001506
1507 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001508 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001509
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001510 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001511 for (unsigned i = 0; i != NumResultElts; ++i)
1512 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001513
Chris Lattner91c08ad2011-02-15 00:14:06 +00001514 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1515 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001516 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001517 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001518}
1519
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001520/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001521Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1522 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001523 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1524 QualType EQT = ExprVT->getElementType();
1525 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001526
John McCall7f416cc2015-09-08 08:05:57 +00001527 Address CastToPointerElement =
1528 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1529 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001530
1531 const llvm::Constant *Elts = LV.getExtVectorElts();
1532 unsigned ix = getAccessedFieldNo(0, Elts);
1533
John McCall7f416cc2015-09-08 08:05:57 +00001534 Address VectorBasePtrPlusIx =
1535 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1536 getContext().getTypeSizeInChars(EQT),
1537 "vector.elt");
1538
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001539 return VectorBasePtrPlusIx;
1540}
1541
Renato Golin230c5eb2014-05-19 18:15:42 +00001542/// @brief Load of global gamed gegisters are always calls to intrinsics.
1543RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001544 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1545 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001546 llvm::MDNode *RegName = cast<llvm::MDNode>(
1547 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001548
1549 // We accept integer and pointer types only
1550 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1551 llvm::Type *Ty = OrigTy;
1552 if (OrigTy->isPointerTy())
1553 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1554 llvm::Type *Types[] = { Ty };
1555
Renato Golin230c5eb2014-05-19 18:15:42 +00001556 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001557 llvm::Value *Call = Builder.CreateCall(
1558 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001559 if (OrigTy->isPointerTy())
1560 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001561 return RValue::get(Call);
1562}
Chris Lattner40ff7012007-08-03 16:18:34 +00001563
Chris Lattner9369a562007-06-29 16:31:29 +00001564
Chris Lattner8394d792007-06-05 20:53:16 +00001565/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1566/// lvalue, where both are guaranteed to the have the same type, and that type
1567/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001568void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001569 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001570 if (!Dst.isSimple()) {
1571 if (Dst.isVectorElt()) {
1572 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001573 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1574 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001575 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001576 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001577 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1578 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001579 return;
1580 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001581
Nate Begemance4d7fc2008-04-18 23:10:10 +00001582 // If this is an update of extended vector elements, insert them as
1583 // appropriate.
1584 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001585 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001586
Renato Golin230c5eb2014-05-19 18:15:42 +00001587 if (Dst.isGlobalReg())
1588 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1589
John McCallc109a252011-11-07 03:59:57 +00001590 assert(Dst.isBitField() && "Unknown LValue type");
1591 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001592 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001593
John McCall31168b02011-06-15 23:02:42 +00001594 // There's special magic for assigning into an ARC-qualified l-value.
1595 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1596 switch (Lifetime) {
1597 case Qualifiers::OCL_None:
1598 llvm_unreachable("present but none");
1599
1600 case Qualifiers::OCL_ExplicitNone:
1601 // nothing special
1602 break;
1603
1604 case Qualifiers::OCL_Strong:
John McCall55e1fbc2011-06-25 02:11:03 +00001605 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001606 return;
1607
1608 case Qualifiers::OCL_Weak:
1609 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1610 return;
1611
1612 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001613 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1614 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001615 // fall into the normal path
1616 break;
1617 }
1618 }
1619
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001620 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001621 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001622 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001623 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001624 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001625 return;
1626 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001627
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001628 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001629 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001630 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001631 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001632 if (Dst.isObjCIvar()) {
1633 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001634 llvm::Type *ResultType = IntPtrTy;
1635 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1636 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001637 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001638 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001639 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1640 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001641 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001642 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001643 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001644 } else if (Dst.isGlobalObjCRef()) {
1645 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1646 Dst.isThreadLocalRef());
1647 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001648 else
1649 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001650 return;
1651 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001652
Chris Lattner6278e6a2007-08-11 00:04:45 +00001653 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001654 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001655}
1656
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001657void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001658 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001659 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001660 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001661 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001662
Daniel Dunbar67aba792010-04-15 03:47:33 +00001663 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001664 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001665
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001666 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001667 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001668 /*IsSigned=*/false);
1669 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001670
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001671 // See if there are other bits in the bitfield's storage we'll need to load
1672 // and mask together with source before storing.
1673 if (Info.StorageSize != Info.Size) {
1674 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001675 llvm::Value *Val =
1676 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001677
1678 // Mask the source value as needed.
1679 if (!hasBooleanRepresentation(Dst.getType()))
1680 SrcVal = Builder.CreateAnd(SrcVal,
1681 llvm::APInt::getLowBitsSet(Info.StorageSize,
1682 Info.Size),
1683 "bf.value");
1684 MaskedVal = SrcVal;
1685 if (Info.Offset)
1686 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1687
1688 // Mask out the original value.
1689 Val = Builder.CreateAnd(Val,
1690 ~llvm::APInt::getBitsSet(Info.StorageSize,
1691 Info.Offset,
1692 Info.Offset + Info.Size),
1693 "bf.clear");
1694
1695 // Or together the unchanged values and the source value.
1696 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1697 } else {
1698 assert(Info.Offset == 0);
1699 }
1700
1701 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001702 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001703
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001704 // Return the new value of the bit-field, if requested.
1705 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001706 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001707
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001708 // Sign extend the value if needed.
1709 if (Info.IsSigned) {
1710 assert(Info.Size <= Info.StorageSize);
1711 unsigned HighBits = Info.StorageSize - Info.Size;
1712 if (HighBits) {
1713 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1714 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1715 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001716 }
1717
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001718 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1719 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001720 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001721 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001722}
1723
Nate Begemance4d7fc2008-04-18 23:10:10 +00001724void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001725 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001726 // This access turns into a read/modify/write of the vector. Load the input
1727 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001728 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1729 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001730 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001731
Chris Lattner4647a212007-08-31 22:49:20 +00001732 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001733
John McCall55e1fbc2011-06-25 02:11:03 +00001734 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001735 unsigned NumSrcElts = VTy->getNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001736 unsigned NumDstElts =
1737 cast<llvm::VectorType>(Vec->getType())->getNumElements();
1738 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001739 // Use shuffle vector is the src and destination are the same number of
1740 // elements and restore the vector mask since it is on the side it will be
1741 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001742 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001743 for (unsigned i = 0; i != NumSrcElts; ++i)
1744 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001745
Chris Lattner91c08ad2011-02-15 00:14:06 +00001746 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001747 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001748 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001749 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001750 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001751 // Extended the source vector to the same length and then shuffle it
1752 // into the destination.
1753 // FIXME: since we're shuffling with undef, can we just use the indices
1754 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001755 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001756 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001757 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001758 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001759 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001760 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001761 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001762 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001763 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001764 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001765 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001766 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001767 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001768
Joey Goulycf4143b2013-11-21 17:09:05 +00001769 // When the vector size is odd and .odd or .hi is used, the last element
1770 // of the Elts constant array will be one past the size of the vector.
1771 // Ignore the last element here, if it is greater than the mask size.
1772 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1773 NumSrcElts--;
1774
Nate Begemanb699c9b2009-01-18 06:42:49 +00001775 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001776 for (unsigned i = 0; i != NumSrcElts; ++i)
1777 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001778 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001779 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001780 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001781 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001782 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001783 }
1784 } else {
1785 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001786 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001787 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001788 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001789 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001790
John McCall7f416cc2015-09-08 08:05:57 +00001791 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1792 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001793}
1794
Renato Golin230c5eb2014-05-19 18:15:42 +00001795/// @brief Store of global named registers are always calls to intrinsics.
1796void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001797 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1798 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001799 llvm::MDNode *RegName = cast<llvm::MDNode>(
1800 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00001801 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00001802
1803 // We accept integer and pointer types only
1804 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1805 llvm::Type *Ty = OrigTy;
1806 if (OrigTy->isPointerTy())
1807 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1808 llvm::Type *Types[] = { Ty };
1809
Renato Golin230c5eb2014-05-19 18:15:42 +00001810 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1811 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00001812 if (OrigTy->isPointerTy())
1813 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00001814 Builder.CreateCall(
1815 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00001816}
1817
Eric Christopherc9e2a682014-05-20 17:10:39 +00001818// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001819// generating write-barries API. It is currently a global, ivar,
1820// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001821static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001822 LValue &LV,
1823 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001824 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001825 return;
Craig Topper99e79272013-07-26 05:59:26 +00001826
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001827 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001828 QualType ExpTy = E->getType();
1829 if (IsMemberAccess && ExpTy->isPointerType()) {
1830 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00001831 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001832 // writer-barrier conservatively.
1833 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1834 if (ExpTy->isRecordType()) {
1835 LV.setObjCIvar(false);
1836 return;
1837 }
1838 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001839 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001840 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001841 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001842 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001843 return;
1844 }
Craig Topper99e79272013-07-26 05:59:26 +00001845
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001846 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1847 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001848 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001849 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00001850 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001851 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001852 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001853 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001854 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001855 }
Craig Topper99e79272013-07-26 05:59:26 +00001856
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001857 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001858 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001859 return;
1860 }
Craig Topper99e79272013-07-26 05:59:26 +00001861
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001862 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001863 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001864 if (LV.isObjCIvar()) {
1865 // If cast is to a structure pointer, follow gcc's behavior and make it
1866 // a non-ivar write-barrier.
1867 QualType ExpTy = E->getType();
1868 if (ExpTy->isPointerType())
1869 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1870 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00001871 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001872 }
1873 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001874 }
Peter Collingbourne91147592011-04-15 00:35:48 +00001875
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001876 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001877 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1878 return;
1879 }
1880
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001881 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001882 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001883 return;
1884 }
Craig Topper99e79272013-07-26 05:59:26 +00001885
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001886 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001887 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001888 return;
1889 }
John McCall31168b02011-06-15 23:02:42 +00001890
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001891 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001892 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00001893 return;
1894 }
1895
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001896 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001897 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00001898 if (LV.isObjCIvar() && !LV.isObjCArray())
1899 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001900 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00001901 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001902 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00001903 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001904 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001905 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001906 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001907 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001908
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001909 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001910 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001911 // We don't know if member is an 'ivar', but this flag is looked at
1912 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001913 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001914 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001915 }
1916}
1917
Chris Lattner3f32d692011-07-12 06:52:18 +00001918static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00001919EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00001920 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001921 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00001922 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00001923 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00001924}
1925
Alexey Bataev97720002014-11-11 04:05:39 +00001926static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00001927 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
1928 llvm::Type *RealVarTy, SourceLocation Loc) {
1929 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
1930 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
1931 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
1932}
1933
1934Address CodeGenFunction::EmitLoadOfReference(Address Addr,
1935 const ReferenceType *RefTy,
1936 AlignmentSource *Source) {
1937 llvm::Value *Ptr = Builder.CreateLoad(Addr);
1938 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
1939 Source, /*forPointee*/ true));
1940
1941}
1942
1943LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
1944 const ReferenceType *RefTy) {
1945 AlignmentSource Source;
1946 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &Source);
1947 return MakeAddrLValue(Addr, RefTy->getPointeeType(), Source);
Alexey Bataev97720002014-11-11 04:05:39 +00001948}
1949
Alexey Bataev31300ed2016-02-04 11:27:03 +00001950Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
1951 const PointerType *PtrTy,
1952 AlignmentSource *Source) {
1953 llvm::Value *Addr = Builder.CreateLoad(Ptr);
1954 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(), Source,
1955 /*forPointeeType=*/true));
1956}
1957
1958LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
1959 const PointerType *PtrTy) {
1960 AlignmentSource Source;
1961 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &Source);
1962 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), Source);
1963}
1964
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001965static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1966 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00001967 QualType T = E->getType();
1968
1969 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00001970 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1971 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00001972 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
1973
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001974 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001975 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
1976 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00001977 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00001978 Address Addr(V, Alignment);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001979 LValue LV;
Alexey Bataev97720002014-11-11 04:05:39 +00001980 // Emit reference to the private copy of the variable if it is an OpenMP
1981 // threadprivate variable.
1982 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001983 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001984 E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001985 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
1986 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001987 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001988 LV = CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001989 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001990 setObjCGCLValueClass(CGF.getContext(), E, LV);
1991 return LV;
1992}
1993
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001994static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
Chris Lattner13ee4f42011-07-10 05:34:54 +00001995 const Expr *E, const FunctionDecl *FD) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00001996 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001997 if (!FD->hasPrototype()) {
1998 if (const FunctionProtoType *Proto =
1999 FD->getType()->getAs<FunctionProtoType>()) {
2000 // Ugly case: for a K&R-style definition, the type of the definition
2001 // isn't the same as the type of a use. Correct for this with a
2002 // bitcast.
2003 QualType NoProtoType =
Alp Toker314cc812014-01-25 16:55:45 +00002004 CGF.getContext().getFunctionNoProtoType(Proto->getReturnType());
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002005 NoProtoType = CGF.getContext().getPointerType(NoProtoType);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002006 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002007 }
2008 }
Eli Friedmana0544d62011-12-03 04:14:32 +00002009 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
John McCall7f416cc2015-09-08 08:05:57 +00002010 return CGF.MakeAddrLValue(V, E->getType(), Alignment, AlignmentSource::Decl);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002011}
2012
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00002013static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2014 llvm::Value *ThisValue) {
2015 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2016 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2017 return CGF.EmitLValueForField(LV, FD);
2018}
2019
Renato Golin230c5eb2014-05-19 18:15:42 +00002020/// Named Registers are named metadata pointing to the register name
2021/// which will be read from/written to as an argument to the intrinsic
2022/// @llvm.read/write_register.
2023/// So far, only the name is being passed down, but other options such as
2024/// register type, allocation type or even optimization options could be
2025/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002026static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002027 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002028 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002029 assert(Asm->getLabel().size() < 64-Name.size() &&
2030 "Register name too big");
2031 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002032 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002033 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002034 if (M->getNumOperands() == 0) {
2035 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2036 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002037 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002038 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2039 }
John McCall7f416cc2015-09-08 08:05:57 +00002040
2041 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2042
2043 llvm::Value *Ptr =
2044 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2045 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002046}
2047
Chris Lattnerd7f58862007-06-02 05:24:33 +00002048LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002049 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002050 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002051
Renato Goline7b3d5d2014-05-27 16:46:27 +00002052 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2053 // Global Named registers access via intrinsics only
2054 if (VD->getStorageClass() == SC_Register &&
2055 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002056 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002057
Renato Goline7b3d5d2014-05-27 16:46:27 +00002058 // A DeclRefExpr for a reference initialized by a constant expression can
2059 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002060 const Expr *Init = VD->getAnyInitializer(VD);
2061 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2062 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002063 VD->checkInitIsICE() &&
2064 // Do not emit if it is private OpenMP variable.
2065 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2066 LocalDeclMap.count(VD))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002067 llvm::Constant *Val =
2068 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2069 assert(Val && "failed to emit reference constant expression");
2070 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002071
2072 // Should we be using the alignment of the constant pointer we emitted?
2073 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2074 /*pointee*/ true);
2075
2076 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
Richard Smith5a1104b2012-10-20 01:38:33 +00002077 }
David Majnemer602cfe72015-01-01 09:49:44 +00002078
2079 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002080 if (E->refersToEnclosingVariableOrCapture()) {
David Majnemer602cfe72015-01-01 09:49:44 +00002081 if (auto *FD = LambdaCaptureFields.lookup(VD))
2082 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2083 else if (CapturedStmtInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002084 auto it = LocalDeclMap.find(VD);
2085 if (it != LocalDeclMap.end()) {
2086 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2087 return EmitLoadOfReferenceLValue(it->second, RefTy);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002088 }
John McCall7f416cc2015-09-08 08:05:57 +00002089 return MakeAddrLValue(it->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002090 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002091 LValue CapLVal =
2092 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2093 CapturedStmtInfo->getContextValue());
2094 return MakeAddrLValue(
2095 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2096 CapLVal.getType(), AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002097 }
John McCall7f416cc2015-09-08 08:05:57 +00002098
David Majnemer602cfe72015-01-01 09:49:44 +00002099 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002100 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2101 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002102 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002103 }
2104
Eli Friedman5720e342012-01-21 04:52:58 +00002105 // FIXME: We should be able to assert this for FunctionDecls as well!
2106 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2107 // those with a valid source location.
2108 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2109 !E->getLocation().isValid()) &&
2110 "Should not use decl without marking it used!");
2111
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002112 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002113 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002114 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2115 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002116 }
2117
Renato Goline7b3d5d2014-05-27 16:46:27 +00002118 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002119 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002120 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002121 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002122
John McCall7f416cc2015-09-08 08:05:57 +00002123 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002124
John McCall7f416cc2015-09-08 08:05:57 +00002125 // The variable should generally be present in the local decl map.
2126 auto iter = LocalDeclMap.find(VD);
2127 if (iter != LocalDeclMap.end()) {
2128 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002129
John McCall7f416cc2015-09-08 08:05:57 +00002130 // Otherwise, it might be static local we haven't emitted yet for
2131 // some reason; most likely, because it's in an outer function.
2132 } else if (VD->isStaticLocal()) {
2133 addr = Address(CGM.getOrCreateStaticVarDecl(
2134 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2135 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002136
John McCall7f416cc2015-09-08 08:05:57 +00002137 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002138 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002139 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2140 }
2141
2142
2143 // Check for OpenMP threadprivate variables.
2144 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2145 return EmitThreadPrivateVarDeclLValue(
2146 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2147 E->getExprLoc());
2148 }
2149
2150 // Drill into block byref variables.
2151 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2152 if (isBlockByref) {
2153 addr = emitBlockByrefAddress(addr, VD);
2154 }
2155
2156 // Drill into reference types.
2157 LValue LV;
2158 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2159 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2160 } else {
2161 LV = MakeAddrLValue(addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002162 }
Chris Lattner3f32d692011-07-12 06:52:18 +00002163
John McCallcdda29c2013-03-13 03:10:54 +00002164 bool isLocalStorage = VD->hasLocalStorage();
2165
2166 bool NonGCable = isLocalStorage &&
2167 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002168 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002169 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002170 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002171 LV.setNonGC(true);
2172 }
John McCallcdda29c2013-03-13 03:10:54 +00002173
2174 bool isImpreciseLifetime =
2175 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2176 if (isImpreciseLifetime)
2177 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002178 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002179 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002180 }
John McCallf3a88602011-02-03 08:15:49 +00002181
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002182 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002183 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002184
David Blaikie83d382b2011-09-23 05:06:16 +00002185 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002186}
Chris Lattnere47e4402007-06-01 18:02:12 +00002187
Chris Lattner8394d792007-06-05 20:53:16 +00002188LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2189 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002190 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002191 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002192
Chris Lattner0f398c42008-07-26 22:37:01 +00002193 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002194 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002195 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002196 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002197 QualType T = E->getSubExpr()->getType()->getPointeeType();
2198 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002199
John McCall7f416cc2015-09-08 08:05:57 +00002200 AlignmentSource AlignSource;
2201 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &AlignSource);
2202 LValue LV = MakeAddrLValue(Addr, T, AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002203 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002204
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002205 // We should not generate __weak write barrier on indirect reference
2206 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2207 // But, we continue to generate __strong write barrier on indirect write
2208 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002209 if (getLangOpts().ObjC1 &&
2210 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002211 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002212 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002213 return LV;
2214 }
John McCalle3027922010-08-25 11:45:40 +00002215 case UO_Real:
2216 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002217 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002218 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002219
Richard Smith0b6b8e42012-02-18 20:53:32 +00002220 // __real is valid on scalars. This is a faster way of testing that.
2221 // __imag can only produce an rvalue on scalars.
2222 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002223 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002224 assert(E->getSubExpr()->getType()->isArithmeticType());
2225 return LV;
2226 }
2227
2228 assert(E->getSubExpr()->getType()->isAnyComplexType());
2229
John McCall7f416cc2015-09-08 08:05:57 +00002230 Address Component =
2231 (E->getOpcode() == UO_Real
2232 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2233 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
2234 return MakeAddrLValue(Component, ExprTy, LV.getAlignmentSource());
Chris Lattner595db862007-10-30 22:53:42 +00002235 }
John McCalle3027922010-08-25 11:45:40 +00002236 case UO_PreInc:
2237 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002238 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002239 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002240
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002241 if (E->getType()->isAnyComplexType())
2242 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2243 else
2244 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2245 return LV;
2246 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002247 }
Chris Lattner8394d792007-06-05 20:53:16 +00002248}
2249
Chris Lattner4347e3692007-06-06 04:54:52 +00002250LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002251 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
John McCall7f416cc2015-09-08 08:05:57 +00002252 E->getType(), AlignmentSource::Decl);
Chris Lattner4347e3692007-06-06 04:54:52 +00002253}
2254
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002255LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002256 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
John McCall7f416cc2015-09-08 08:05:57 +00002257 E->getType(), AlignmentSource::Decl);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002258}
2259
Mike Stump4a3999f2009-09-09 13:00:44 +00002260LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002261 auto SL = E->getFunctionName();
2262 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2263 StringRef FnName = CurFn->getName();
2264 if (FnName.startswith("\01"))
2265 FnName = FnName.substr(1);
2266 StringRef NameItems[] = {
2267 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2268 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002269 if (CurCodeDecl && isa<BlockDecl>(CurCodeDecl)) {
John McCall7f416cc2015-09-08 08:05:57 +00002270 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2271 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002272 }
Alexey Bataevec474782014-10-09 08:45:04 +00002273 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
John McCall7f416cc2015-09-08 08:05:57 +00002274 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002275}
2276
Richard Smithe30752c2012-10-09 19:52:38 +00002277/// Emit a type description suitable for use by a runtime sanitizer library. The
2278/// format of a type descriptor is
2279///
2280/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002281/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002282/// \endcode
2283///
Richard Smith683398a2012-10-09 23:55:19 +00002284/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2285/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002286llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002287 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002288 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002289 return C;
2290
Richard Smithe30752c2012-10-09 19:52:38 +00002291 uint16_t TypeKind = -1;
2292 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002293
Richard Smithe30752c2012-10-09 19:52:38 +00002294 if (T->isIntegerType()) {
2295 TypeKind = 0;
2296 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002297 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002298 } else if (T->isFloatingType()) {
2299 TypeKind = 1;
2300 TypeInfo = getContext().getTypeSize(T);
2301 }
2302
2303 // Format the type name as if for a diagnostic, including quotes and
2304 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002305 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002306 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2307 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002308 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002309 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002310
2311 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002312 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2313 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002314 };
2315 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2316
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002317 auto *GV = new llvm::GlobalVariable(
2318 CGM.getModule(), Descriptor->getType(),
2319 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Richard Smithe30752c2012-10-09 19:52:38 +00002320 GV->setUnnamedAddr(true);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002321 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002322
2323 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002324 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002325
Richard Smithe30752c2012-10-09 19:52:38 +00002326 return GV;
2327}
2328
2329llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2330 llvm::Type *TargetTy = IntPtrTy;
2331
Richard Smith48366f72013-03-22 00:47:07 +00002332 // Floating-point types which fit into intptr_t are bitcast to integers
2333 // and then passed directly (after zero-extension, if necessary).
2334 if (V->getType()->isFloatingPointTy()) {
2335 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2336 if (Bits <= TargetTy->getIntegerBitWidth())
2337 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2338 Bits));
2339 }
2340
Richard Smithe30752c2012-10-09 19:52:38 +00002341 // Integers which fit in intptr_t are zero-extended and passed directly.
2342 if (V->getType()->isIntegerTy() &&
2343 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2344 return Builder.CreateZExt(V, TargetTy);
2345
2346 // Pointers are passed directly, everything else is passed by address.
2347 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002348 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002349 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002350 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002351 }
2352 return Builder.CreatePtrToInt(V, TargetTy);
2353}
2354
2355/// \brief Emit a representation of a SourceLocation for passing to a handler
2356/// in a sanitizer runtime library. The format for this data is:
2357/// \code
2358/// struct SourceLocation {
2359/// const char *Filename;
2360/// int32_t Line, Column;
2361/// };
2362/// \endcode
2363/// For an invalid SourceLocation, the Filename pointer is null.
2364llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002365 llvm::Constant *Filename;
2366 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002367
Alexey Samsonov6c124142014-07-18 17:50:06 +00002368 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2369 if (PLoc.isValid()) {
2370 auto FilenameGV = CGM.GetAddrOfConstantCString(PLoc.getFilename(), ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002371 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2372 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2373 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002374 Line = PLoc.getLine();
2375 Column = PLoc.getColumn();
2376 } else {
2377 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2378 Line = Column = 0;
2379 }
2380
2381 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2382 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002383
2384 return llvm::ConstantStruct::getAnon(Data);
2385}
2386
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002387namespace {
2388/// \brief Specify under what conditions this check can be recovered
2389enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002390 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002391 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002392 /// Check supports recovering, runtime has both fatal (noreturn) and
2393 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002394 Recoverable,
2395 /// Runtime conditionally aborts, always need to support recovery.
2396 AlwaysRecoverable
2397};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002398}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002399
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002400static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2401 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002402 switch (Kind) {
2403 case SanitizerKind::Vptr:
2404 return CheckRecoverableKind::AlwaysRecoverable;
2405 case SanitizerKind::Return:
2406 case SanitizerKind::Unreachable:
2407 return CheckRecoverableKind::Unrecoverable;
2408 default:
2409 return CheckRecoverableKind::Recoverable;
2410 }
2411}
2412
Alexey Samsonov88459522015-01-12 22:39:12 +00002413static void emitCheckHandlerCall(CodeGenFunction &CGF,
2414 llvm::FunctionType *FnType,
2415 ArrayRef<llvm::Value *> FnArgs,
2416 StringRef CheckName,
2417 CheckRecoverableKind RecoverKind, bool IsFatal,
2418 llvm::BasicBlock *ContBB) {
2419 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2420 bool NeedsAbortSuffix =
2421 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2422 std::string FnName = ("__ubsan_handle_" + CheckName +
2423 (NeedsAbortSuffix ? "_abort" : "")).str();
2424 bool MayReturn =
2425 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2426
2427 llvm::AttrBuilder B;
2428 if (!MayReturn) {
2429 B.addAttribute(llvm::Attribute::NoReturn)
2430 .addAttribute(llvm::Attribute::NoUnwind);
2431 }
2432 B.addAttribute(llvm::Attribute::UWTable);
2433
2434 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2435 FnType, FnName,
2436 llvm::AttributeSet::get(CGF.getLLVMContext(),
2437 llvm::AttributeSet::FunctionIndex, B));
2438 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2439 if (!MayReturn) {
2440 HandlerCall->setDoesNotReturn();
2441 CGF.Builder.CreateUnreachable();
2442 } else {
2443 CGF.Builder.CreateBr(ContBB);
2444 }
2445}
2446
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002447void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002448 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002449 StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
2450 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002451 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002452 assert(Checked.size() > 0);
Alexey Samsonov88459522015-01-12 22:39:12 +00002453
2454 llvm::Value *FatalCond = nullptr;
2455 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002456 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002457 for (int i = 0, n = Checked.size(); i < n; ++i) {
2458 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002459 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002460 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002461 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2462 ? TrapCond
2463 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2464 ? RecoverableCond
2465 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002466 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2467 }
2468
Peter Collingbourne9881b782015-06-18 23:59:22 +00002469 if (TrapCond)
2470 EmitTrapCheck(TrapCond);
2471 if (!FatalCond && !RecoverableCond)
2472 return;
2473
Alexey Samsonov88459522015-01-12 22:39:12 +00002474 llvm::Value *JointCond;
2475 if (FatalCond && RecoverableCond)
2476 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2477 else
2478 JointCond = FatalCond ? FatalCond : RecoverableCond;
2479 assert(JointCond);
2480
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002481 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002482 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002483#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002484 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002485 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002486 "All recoverable kinds in a single check must be same!");
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002487 assert(SanOpts.has(Checked[i].second));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002488 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002489#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002490
Richard Smith4d1458e2012-09-08 02:08:36 +00002491 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002492 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2493 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002494 // Give hint that we very much don't expect to execute the handler
2495 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2496 llvm::MDBuilder MDHelper(getLLVMContext());
2497 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2498 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002499 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002500
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002501 // Handler functions take an i8* pointing to the (handler-specific) static
2502 // information block, followed by a sequence of intptr_t arguments
2503 // representing operand values.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002504 SmallVector<llvm::Value *, 4> Args;
2505 SmallVector<llvm::Type *, 4> ArgTypes;
Richard Smithe30752c2012-10-09 19:52:38 +00002506 Args.reserve(DynamicArgs.size() + 1);
2507 ArgTypes.reserve(DynamicArgs.size() + 1);
2508
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002509 // Emit handler arguments and create handler function type.
2510 if (!StaticArgs.empty()) {
2511 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2512 auto *InfoPtr =
2513 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2514 llvm::GlobalVariable::PrivateLinkage, Info);
2515 InfoPtr->setUnnamedAddr(true);
2516 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2517 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2518 ArgTypes.push_back(Int8PtrTy);
2519 }
2520
Richard Smithe30752c2012-10-09 19:52:38 +00002521 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2522 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2523 ArgTypes.push_back(IntPtrTy);
2524 }
2525
2526 llvm::FunctionType *FnType =
2527 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002528
Alexey Samsonov88459522015-01-12 22:39:12 +00002529 if (!FatalCond || !RecoverableCond) {
2530 // Simple case: we need to generate a single handler call, either
2531 // fatal, or non-fatal.
2532 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind,
2533 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002534 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002535 // Emit two handler calls: first one for set of unrecoverable checks,
2536 // another one for recoverable.
2537 llvm::BasicBlock *NonFatalHandlerBB =
2538 createBasicBlock("non_fatal." + CheckName);
2539 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2540 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2541 EmitBlock(FatalHandlerBB);
2542 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, true,
2543 NonFatalHandlerBB);
2544 EmitBlock(NonFatalHandlerBB);
2545 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, false,
2546 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002547 }
Richard Smithe30752c2012-10-09 19:52:38 +00002548
Richard Smith4d1458e2012-09-08 02:08:36 +00002549 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002550}
2551
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002552void CodeGenFunction::EmitCfiSlowPathCheck(
2553 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2554 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002555 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2556
2557 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2558 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2559
2560 llvm::MDBuilder MDHelper(getLLVMContext());
2561 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2562 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2563
2564 EmitBlock(CheckBB);
2565
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002566 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2567
2568 llvm::CallInst *CheckCall;
2569 if (WithDiag) {
2570 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2571 auto *InfoPtr =
2572 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2573 llvm::GlobalVariable::PrivateLinkage, Info);
2574 InfoPtr->setUnnamedAddr(true);
2575 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2576
2577 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2578 "__cfi_slowpath_diag",
2579 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2580 false));
2581 CheckCall = Builder.CreateCall(
2582 SlowPathDiagFn,
2583 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2584 } else {
2585 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2586 "__cfi_slowpath",
2587 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2588 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2589 }
2590
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002591 CheckCall->setDoesNotThrow();
2592
2593 EmitBlock(Cont);
2594}
2595
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002596// This function is basically a switch over the CFI failure kind, which is
2597// extracted from CFICheckFailData (1st function argument). Each case is either
2598// llvm.trap or a call to one of the two runtime handlers, based on
2599// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2600// failure kind) traps, but this should really never happen. CFICheckFailData
2601// can be nullptr if the calling module has -fsanitize-trap behavior for this
2602// check kind; in this case __cfi_check_fail traps as well.
2603void CodeGenFunction::EmitCfiCheckFail() {
2604 SanitizerScope SanScope(this);
2605 FunctionArgList Args;
2606 ImplicitParamDecl ArgData(getContext(), nullptr, SourceLocation(), nullptr,
2607 getContext().VoidPtrTy);
2608 ImplicitParamDecl ArgAddr(getContext(), nullptr, SourceLocation(), nullptr,
2609 getContext().VoidPtrTy);
2610 Args.push_back(&ArgData);
2611 Args.push_back(&ArgAddr);
2612
John McCallc56a8b32016-03-11 04:30:31 +00002613 const CGFunctionInfo &FI =
2614 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002615
2616 llvm::Function *F = llvm::Function::Create(
2617 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2618 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2619 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2620
2621 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2622 SourceLocation());
2623
2624 llvm::Value *Data =
2625 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2626 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2627 llvm::Value *Addr =
2628 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2629 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2630
2631 // Data == nullptr means the calling module has trap behaviour for this check.
2632 llvm::Value *DataIsNotNullPtr =
2633 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2634 EmitTrapCheck(DataIsNotNullPtr);
2635
2636 llvm::StructType *SourceLocationTy =
2637 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty, nullptr);
2638 llvm::StructType *CfiCheckFailDataTy =
2639 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy, nullptr);
2640
2641 llvm::Value *V = Builder.CreateConstGEP2_32(
2642 CfiCheckFailDataTy,
2643 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2644 0);
2645 Address CheckKindAddr(V, getIntAlign());
2646 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2647
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002648 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2649 CGM.getLLVMContext(),
2650 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2651 llvm::Value *ValidVtable = Builder.CreateZExt(
2652 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::bitset_test),
2653 {Addr, AllVtables}),
2654 IntPtrTy);
2655
Evgeniy Stepanov4d3b0872016-01-25 23:45:37 +00002656 const std::pair<int, SanitizerMask> CheckKinds[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002657 {CFITCK_VCall, SanitizerKind::CFIVCall},
2658 {CFITCK_NVCall, SanitizerKind::CFINVCall},
2659 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
2660 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
2661 {CFITCK_ICall, SanitizerKind::CFIICall}};
2662
2663 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
2664 for (auto CheckKindMaskPair : CheckKinds) {
2665 int Kind = CheckKindMaskPair.first;
2666 SanitizerMask Mask = CheckKindMaskPair.second;
2667 llvm::Value *Cond =
2668 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002669 if (CGM.getLangOpts().Sanitize.has(Mask))
2670 EmitCheck(std::make_pair(Cond, Mask), "cfi_check_fail", {},
2671 {Data, Addr, ValidVtable});
2672 else
2673 EmitTrapCheck(Cond);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002674 }
2675
2676 FinishFunction();
2677 // The only reference to this function will be created during LTO link.
2678 // Make sure it survives until then.
2679 CGM.addUsedGlobal(F);
2680}
2681
Chad Rosierae229d52013-01-29 23:31:22 +00002682void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00002683 llvm::BasicBlock *Cont = createBasicBlock("cont");
2684
2685 // If we're optimizing, collapse all calls to trap down to just one per
2686 // function to save on code size.
2687 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2688 TrapBB = createBasicBlock("trap");
2689 Builder.CreateCondBr(Checked, Cont, TrapBB);
2690 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002691 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00002692 TrapCall->setDoesNotReturn();
2693 TrapCall->setDoesNotThrow();
2694 Builder.CreateUnreachable();
2695 } else {
2696 Builder.CreateCondBr(Checked, Cont, TrapBB);
2697 }
2698
2699 EmitBlock(Cont);
2700}
2701
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002702llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00002703 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002704
2705 if (!CGM.getCodeGenOpts().TrapFuncName.empty())
2706 TrapCall->addAttribute(llvm::AttributeSet::FunctionIndex,
2707 "trap-func-name",
2708 CGM.getCodeGenOpts().TrapFuncName);
2709
2710 return TrapCall;
2711}
2712
John McCall7f416cc2015-09-08 08:05:57 +00002713Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
2714 AlignmentSource *AlignSource) {
2715 assert(E->getType()->isArrayType() &&
2716 "Array to pointer decay must have array source type!");
2717
2718 // Expressions of array type can't be bitfields or vector elements.
2719 LValue LV = EmitLValue(E);
2720 Address Addr = LV.getAddress();
2721 if (AlignSource) *AlignSource = LV.getAlignmentSource();
2722
2723 // If the array type was an incomplete type, we need to make sure
2724 // the decay ends up being the right type.
2725 llvm::Type *NewTy = ConvertType(E->getType());
2726 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2727
2728 // Note that VLA pointers are always decayed, so we don't need to do
2729 // anything here.
2730 if (!E->getType()->isVariableArrayType()) {
2731 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2732 "Expected pointer to array");
2733 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2734 }
2735
2736 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2737 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2738}
2739
Chris Lattner6c5abe82010-06-26 23:03:20 +00002740/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2741/// array to pointer, return the array subexpression.
2742static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2743 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002744 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00002745 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00002746 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002747
Chris Lattner6c5abe82010-06-26 23:03:20 +00002748 // If this is a decay from variable width array, bail out.
2749 const Expr *SubExpr = CE->getSubExpr();
2750 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00002751 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002752
Chris Lattner6c5abe82010-06-26 23:03:20 +00002753 return SubExpr;
2754}
2755
John McCall7f416cc2015-09-08 08:05:57 +00002756static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
2757 llvm::Value *ptr,
2758 ArrayRef<llvm::Value*> indices,
2759 bool inbounds,
2760 const llvm::Twine &name = "arrayidx") {
2761 if (inbounds) {
2762 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name);
2763 } else {
2764 return CGF.Builder.CreateGEP(ptr, indices, name);
2765 }
2766}
2767
2768static CharUnits getArrayElementAlign(CharUnits arrayAlign,
2769 llvm::Value *idx,
2770 CharUnits eltSize) {
2771 // If we have a constant index, we can use the exact offset of the
2772 // element we're accessing.
2773 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
2774 CharUnits offset = constantIdx->getZExtValue() * eltSize;
2775 return arrayAlign.alignmentAtOffset(offset);
2776
2777 // Otherwise, use the worst-case alignment for any element.
2778 } else {
2779 return arrayAlign.alignmentOfArrayElement(eltSize);
2780 }
2781}
2782
2783static QualType getFixedSizeElementType(const ASTContext &ctx,
2784 const VariableArrayType *vla) {
2785 QualType eltType;
2786 do {
2787 eltType = vla->getElementType();
2788 } while ((vla = ctx.getAsVariableArrayType(eltType)));
2789 return eltType;
2790}
2791
2792static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
2793 ArrayRef<llvm::Value*> indices,
2794 QualType eltType, bool inbounds,
2795 const llvm::Twine &name = "arrayidx") {
2796 // All the indices except that last must be zero.
2797#ifndef NDEBUG
2798 for (auto idx : indices.drop_back())
2799 assert(isa<llvm::ConstantInt>(idx) &&
2800 cast<llvm::ConstantInt>(idx)->isZero());
2801#endif
2802
2803 // Determine the element size of the statically-sized base. This is
2804 // the thing that the indices are expressed in terms of.
2805 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
2806 eltType = getFixedSizeElementType(CGF.getContext(), vla);
2807 }
2808
2809 // We can use that to compute the best alignment of the element.
2810 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
2811 CharUnits eltAlign =
2812 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
2813
2814 llvm::Value *eltPtr =
2815 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name);
2816 return Address(eltPtr, eltAlign);
2817}
2818
Richard Smith539e4a72013-02-23 02:53:19 +00002819LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2820 bool Accessed) {
Ted Kremenekc81614d2007-08-20 16:18:38 +00002821 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner2da04b32007-08-24 05:35:26 +00002822 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Eli Friedman07bbeca2009-06-06 19:09:26 +00002823 QualType IdxTy = E->getIdx()->getType();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002824 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Eli Friedman07bbeca2009-06-06 19:09:26 +00002825
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002826 if (SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00002827 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
2828
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002829 // If the base is a vector type, then we are forming a vector element lvalue
2830 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002831 if (E->getBase()->getType()->isVectorType() &&
2832 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002833 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00002834 LValue LHS = EmitLValue(E->getBase());
Ted Kremenekc81614d2007-08-20 16:18:38 +00002835 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Eli Friedman327944b2008-06-13 23:01:12 +00002836 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
John McCall7f416cc2015-09-08 08:05:57 +00002837 E->getBase()->getType(),
2838 LHS.getAlignmentSource());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002839 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002840
John McCall7f416cc2015-09-08 08:05:57 +00002841 // All the other cases basically behave like simple offsetting.
2842
Ted Kremenekc81614d2007-08-20 16:18:38 +00002843 // Extend or truncate the index type to 32 or 64-bits.
John McCalle3dc1702011-02-15 09:22:45 +00002844 if (Idx->getType() != IntPtrTy)
2845 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
Mike Stumpd9546382009-12-12 01:27:46 +00002846
John McCall7f416cc2015-09-08 08:05:57 +00002847 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002848 if (isa<ExtVectorElementExpr>(E->getBase())) {
2849 LValue LV = EmitLValue(E->getBase());
John McCall7f416cc2015-09-08 08:05:57 +00002850 Address Addr = EmitExtVectorElementLValue(LV);
2851
2852 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
2853 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true);
2854 return MakeAddrLValue(Addr, EltType, LV.getAlignmentSource());
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002855 }
John McCall7f416cc2015-09-08 08:05:57 +00002856
2857 AlignmentSource AlignSource;
2858 Address Addr = Address::invalid();
2859 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002860 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00002861 // The base must be a pointer, which is not an aggregate. Emit
2862 // it. It needs to be emitted first in case it's what captures
2863 // the VLA bounds.
John McCall7f416cc2015-09-08 08:05:57 +00002864 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00002865
John McCall23c29fe2011-06-24 21:55:10 +00002866 // The element count here is the total number of non-VLA elements.
2867 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00002868
John McCall77527a82011-06-25 01:32:37 +00002869 // Effectively, the multiply by the VLA size is part of the GEP.
2870 // GEP indexes are signed, and scaling an index isn't permitted to
2871 // signed-overflow, so we use the same semantics for our explicit
2872 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002873 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00002874 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00002875 } else {
2876 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00002877 }
John McCall7f416cc2015-09-08 08:05:57 +00002878
2879 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
2880 !getLangOpts().isSignedOverflowDefined());
2881
Chris Lattner6c5abe82010-06-26 23:03:20 +00002882 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
2883 // Indexing over an interface, as in "NSString *P; P[4];"
John McCall7f416cc2015-09-08 08:05:57 +00002884 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
2885 llvm::Value *InterfaceSizeVal =
2886 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());;
Mike Stump4a3999f2009-09-09 13:00:44 +00002887
John McCall7f416cc2015-09-08 08:05:57 +00002888 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002889
John McCall7f416cc2015-09-08 08:05:57 +00002890 // Emit the base pointer.
2891 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
2892
2893 // We don't necessarily build correct LLVM struct types for ObjC
2894 // interfaces, so we can't rely on GEP to do this scaling
2895 // correctly, so we need to cast to i8*. FIXME: is this actually
2896 // true? A lot of other things in the fragile ABI would break...
2897 llvm::Type *OrigBaseTy = Addr.getType();
2898 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
2899
2900 // Do the GEP.
2901 CharUnits EltAlign =
2902 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
2903 llvm::Value *EltPtr =
2904 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false);
2905 Addr = Address(EltPtr, EltAlign);
2906
2907 // Cast back.
2908 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00002909 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
2910 // If this is A[i] where A is an array, the frontend will have decayed the
2911 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
2912 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
2913 // "gep x, i" here. Emit one "gep A, 0, i".
2914 assert(Array->getType()->isArrayType() &&
2915 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00002916 LValue ArrayLV;
2917 // For simple multidimensional array indexing, set the 'accessed' flag for
2918 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002919 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00002920 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
2921 else
2922 ArrayLV = EmitLValue(Array);
Craig Topper99e79272013-07-26 05:59:26 +00002923
Daniel Dunbar82634272011-04-01 00:49:43 +00002924 // Propagate the alignment from the array itself to the result.
John McCall7f416cc2015-09-08 08:05:57 +00002925 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
2926 {CGM.getSize(CharUnits::Zero()), Idx},
2927 E->getType(),
2928 !getLangOpts().isSignedOverflowDefined());
2929 AlignSource = ArrayLV.getAlignmentSource();
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002930 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002931 // The base must be a pointer; emit it with an estimate of its alignment.
2932 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
2933 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
2934 !getLangOpts().isSignedOverflowDefined());
Anders Carlsson3d312f82008-12-21 00:11:23 +00002935 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002936
John McCall7f416cc2015-09-08 08:05:57 +00002937 LValue LV = MakeAddrLValue(Addr, E->getType(), AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00002938
John McCall7f416cc2015-09-08 08:05:57 +00002939 // TODO: Preserve/extend path TBAA metadata?
John McCall8ccfcb52009-09-24 19:53:00 +00002940
Richard Smith9c6890a2012-11-01 22:30:59 +00002941 if (getLangOpts().ObjC1 &&
2942 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00002943 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002944 setObjCGCLValueClass(getContext(), E, LV);
2945 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00002946 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00002947}
2948
Alexey Bataev31300ed2016-02-04 11:27:03 +00002949static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
2950 AlignmentSource &AlignSource,
2951 QualType BaseTy, QualType ElTy,
2952 bool IsLowerBound) {
2953 LValue BaseLVal;
2954 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
2955 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
2956 if (BaseTy->isArrayType()) {
2957 Address Addr = BaseLVal.getAddress();
2958 AlignSource = BaseLVal.getAlignmentSource();
2959
2960 // If the array type was an incomplete type, we need to make sure
2961 // the decay ends up being the right type.
2962 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
2963 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
2964
2965 // Note that VLA pointers are always decayed, so we don't need to do
2966 // anything here.
2967 if (!BaseTy->isVariableArrayType()) {
2968 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2969 "Expected pointer to array");
2970 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
2971 "arraydecay");
2972 }
2973
2974 return CGF.Builder.CreateElementBitCast(Addr,
2975 CGF.ConvertTypeForMem(ElTy));
2976 }
2977 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &AlignSource);
2978 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
2979 }
2980 return CGF.EmitPointerWithAlignment(Base, &AlignSource);
2981}
2982
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002983LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
2984 bool IsLowerBound) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00002985 QualType BaseTy;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002986 if (auto *ASE =
2987 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
Alexey Bataev31300ed2016-02-04 11:27:03 +00002988 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002989 else
Alexey Bataev31300ed2016-02-04 11:27:03 +00002990 BaseTy = E->getBase()->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002991 QualType ResultExprTy;
2992 if (auto *AT = getContext().getAsArrayType(BaseTy))
2993 ResultExprTy = AT->getElementType();
2994 else
2995 ResultExprTy = BaseTy->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00002996 llvm::Value *Idx = nullptr;
Benjamin Kramer5ff67472016-04-11 08:26:13 +00002997 if (IsLowerBound || E->getColonLoc().isInvalid()) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002998 // Requesting lower bound or upper bound, but without provided length and
2999 // without ':' symbol for the default length -> length = 1.
3000 // Idx = LowerBound ?: 0;
3001 if (auto *LowerBound = E->getLowerBound()) {
3002 Idx = Builder.CreateIntCast(
3003 EmitScalarExpr(LowerBound), IntPtrTy,
3004 LowerBound->getType()->hasSignedIntegerRepresentation());
3005 } else
3006 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3007 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003008 // Try to emit length or lower bound as constant. If this is possible, 1
3009 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3010 // IR (LB + Len) - 1.
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003011 auto &C = CGM.getContext();
3012 auto *Length = E->getLength();
3013 llvm::APSInt ConstLength;
3014 if (Length) {
3015 // Idx = LowerBound + Length - 1;
3016 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3017 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3018 Length = nullptr;
3019 }
3020 auto *LowerBound = E->getLowerBound();
3021 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3022 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3023 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3024 LowerBound = nullptr;
3025 }
3026 if (!Length)
3027 --ConstLength;
3028 else if (!LowerBound)
3029 --ConstLowerBound;
3030
3031 if (Length || LowerBound) {
3032 auto *LowerBoundVal =
3033 LowerBound
3034 ? Builder.CreateIntCast(
3035 EmitScalarExpr(LowerBound), IntPtrTy,
3036 LowerBound->getType()->hasSignedIntegerRepresentation())
3037 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3038 auto *LengthVal =
3039 Length
3040 ? Builder.CreateIntCast(
3041 EmitScalarExpr(Length), IntPtrTy,
3042 Length->getType()->hasSignedIntegerRepresentation())
3043 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3044 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3045 /*HasNUW=*/false,
3046 !getLangOpts().isSignedOverflowDefined());
3047 if (Length && LowerBound) {
3048 Idx = Builder.CreateSub(
3049 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3050 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3051 }
3052 } else
3053 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3054 } else {
3055 // Idx = ArraySize - 1;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003056 QualType ArrayTy = BaseTy->isPointerType()
3057 ? E->getBase()->IgnoreParenImpCasts()->getType()
3058 : BaseTy;
3059 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003060 Length = VAT->getSizeExpr();
3061 if (Length->isIntegerConstantExpr(ConstLength, C))
3062 Length = nullptr;
3063 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003064 auto *CAT = C.getAsConstantArrayType(ArrayTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003065 ConstLength = CAT->getSize();
3066 }
3067 if (Length) {
3068 auto *LengthVal = Builder.CreateIntCast(
3069 EmitScalarExpr(Length), IntPtrTy,
3070 Length->getType()->hasSignedIntegerRepresentation());
3071 Idx = Builder.CreateSub(
3072 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3073 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3074 } else {
3075 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3076 --ConstLength;
3077 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3078 }
3079 }
3080 }
3081 assert(Idx);
3082
Alexey Bataev31300ed2016-02-04 11:27:03 +00003083 Address EltPtr = Address::invalid();
3084 AlignmentSource AlignSource;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003085 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003086 // The base must be a pointer, which is not an aggregate. Emit
3087 // it. It needs to be emitted first in case it's what captures
3088 // the VLA bounds.
3089 Address Base =
3090 emitOMPArraySectionBase(*this, E->getBase(), AlignSource, BaseTy,
3091 VLA->getElementType(), IsLowerBound);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003092 // The element count here is the total number of non-VLA elements.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003093 llvm::Value *NumElements = getVLASize(VLA).first;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003094
3095 // Effectively, the multiply by the VLA size is part of the GEP.
3096 // GEP indexes are signed, and scaling an index isn't permitted to
3097 // signed-overflow, so we use the same semantics for our explicit
3098 // multiply. We suppress this if overflow is not undefined behavior.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003099 if (getLangOpts().isSignedOverflowDefined())
3100 Idx = Builder.CreateMul(Idx, NumElements);
3101 else
3102 Idx = Builder.CreateNSWMul(Idx, NumElements);
3103 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3104 !getLangOpts().isSignedOverflowDefined());
3105 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3106 // If this is A[i] where A is an array, the frontend will have decayed the
3107 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3108 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3109 // "gep x, i" here. Emit one "gep A, 0, i".
3110 assert(Array->getType()->isArrayType() &&
3111 "Array to pointer decay must have array source type!");
3112 LValue ArrayLV;
3113 // For simple multidimensional array indexing, set the 'accessed' flag for
3114 // better bounds-checking of the base expression.
3115 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3116 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3117 else
3118 ArrayLV = EmitLValue(Array);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003119
Alexey Bataev31300ed2016-02-04 11:27:03 +00003120 // Propagate the alignment from the array itself to the result.
3121 EltPtr = emitArraySubscriptGEP(
3122 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3123 ResultExprTy, !getLangOpts().isSignedOverflowDefined());
3124 AlignSource = ArrayLV.getAlignmentSource();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003125 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003126 Address Base = emitOMPArraySectionBase(*this, E->getBase(), AlignSource,
3127 BaseTy, ResultExprTy, IsLowerBound);
3128 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3129 !getLangOpts().isSignedOverflowDefined());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003130 }
3131
Alexey Bataev31300ed2016-02-04 11:27:03 +00003132 return MakeAddrLValue(EltPtr, ResultExprTy, AlignSource);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003133}
3134
Chris Lattner9e751ca2007-08-02 23:37:31 +00003135LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00003136EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00003137 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003138 LValue Base;
3139
3140 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00003141 if (E->isArrow()) {
3142 // If it is a pointer to a vector, emit the address and form an lvalue with
3143 // it.
John McCall7f416cc2015-09-08 08:05:57 +00003144 AlignmentSource AlignSource;
3145 Address Ptr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003146 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
John McCall7f416cc2015-09-08 08:05:57 +00003147 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00003148 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00003149 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00003150 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3151 // emit the base as an lvalue.
3152 assert(E->getBase()->getType()->isVectorType());
3153 Base = EmitLValue(E->getBase());
3154 } else {
3155 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00003156 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00003157 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00003158 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00003159
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00003160 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00003161 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00003162 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00003163 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3164 AlignmentSource::Decl);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003165 }
John McCall1553b192011-06-16 04:16:24 +00003166
3167 QualType type =
3168 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00003169
Nate Begemand3862152008-05-13 21:03:02 +00003170 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00003171 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00003172 E->getEncodedElementAccess(Indices);
3173
3174 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00003175 llvm::Constant *CV =
3176 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00003177 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
John McCall7f416cc2015-09-08 08:05:57 +00003178 Base.getAlignmentSource());
Nate Begemand3862152008-05-13 21:03:02 +00003179 }
3180 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3181
3182 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003183 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00003184
Chris Lattner595ba3a2012-01-30 06:20:36 +00003185 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3186 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00003187 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00003188 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3189 Base.getAlignmentSource());
Chris Lattner9e751ca2007-08-02 23:37:31 +00003190}
3191
Devang Patel30efa2e2007-10-23 20:28:39 +00003192LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00003193 Expr *BaseExpr = E->getBase();
Eli Friedman327944b2008-06-13 23:01:12 +00003194
Chris Lattner4e4186b2007-12-02 18:52:07 +00003195 // 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 +00003196 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00003197 if (E->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00003198 AlignmentSource AlignSource;
3199 Address Addr = EmitPointerWithAlignment(BaseExpr, &AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003200 QualType PtrTy = BaseExpr->getType()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003201 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy);
3202 BaseLV = MakeAddrLValue(Addr, PtrTy, AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003203 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003204 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003205
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003206 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003207 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003208 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003209 setObjCGCLValueClass(getContext(), E, LV);
3210 return LV;
3211 }
Craig Topper99e79272013-07-26 05:59:26 +00003212
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003213 if (auto *VD = dyn_cast<VarDecl>(ND))
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00003214 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003215
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003216 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003217 return EmitFunctionDeclLValue(*this, E, FD);
3218
David Blaikie83d382b2011-09-23 05:06:16 +00003219 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003220}
Devang Patel30efa2e2007-10-23 20:28:39 +00003221
John McCalldec348f72013-05-03 07:33:41 +00003222/// Given that we are currently emitting a lambda, emit an l-value for
3223/// one of its members.
3224LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3225 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3226 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3227 QualType LambdaTagType =
3228 getContext().getTagDeclType(Field->getParent());
3229 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3230 return EmitLValueForField(LambdaLV, Field);
3231}
3232
John McCall7f416cc2015-09-08 08:05:57 +00003233/// Drill down to the storage of a field without walking into
3234/// reference types.
3235///
3236/// The resulting address doesn't necessarily have the right type.
3237static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3238 const FieldDecl *field) {
3239 const RecordDecl *rec = field->getParent();
3240
3241 unsigned idx =
3242 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3243
3244 CharUnits offset;
3245 // Adjust the alignment down to the given offset.
3246 // As a special case, if the LLVM field index is 0, we know that this
3247 // is zero.
3248 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3249 .getFieldOffset(field->getFieldIndex()) == 0) &&
3250 "LLVM field at index zero had non-zero offset?");
3251 if (idx != 0) {
3252 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3253 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3254 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3255 }
3256
3257 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3258}
3259
Eli Friedman7f1ff602012-04-16 03:54:45 +00003260LValue CodeGenFunction::EmitLValueForField(LValue base,
3261 const FieldDecl *field) {
John McCall7f416cc2015-09-08 08:05:57 +00003262 AlignmentSource fieldAlignSource =
3263 getFieldAlignmentSource(base.getAlignmentSource());
3264
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003265 if (field->isBitField()) {
3266 const CGRecordLayout &RL =
3267 CGM.getTypes().getCGRecordLayout(field->getParent());
3268 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003269 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003270 unsigned Idx = RL.getLLVMFieldNo(field);
3271 if (Idx != 0)
3272 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003273 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3274 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003275 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003276 llvm::Type *FieldIntTy =
3277 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3278 if (Addr.getElementType() != FieldIntTy)
3279 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003280
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003281 QualType fieldType =
3282 field->getType().withCVRQualifiers(base.getVRQualifiers());
John McCall7f416cc2015-09-08 08:05:57 +00003283 return LValue::MakeBitfield(Addr, Info, fieldType, fieldAlignSource);
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003284 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003285
John McCall53fcbd22011-02-26 08:07:02 +00003286 const RecordDecl *rec = field->getParent();
3287 QualType type = field->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003288
John McCall53fcbd22011-02-26 08:07:02 +00003289 bool mayAlias = rec->hasAttr<MayAliasAttr>();
3290
John McCall7f416cc2015-09-08 08:05:57 +00003291 Address addr = base.getAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003292 unsigned cvr = base.getVRQualifiers();
Manman Renc451e572013-04-04 21:53:22 +00003293 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
John McCall53fcbd22011-02-26 08:07:02 +00003294 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003295 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00003296 assert(!type->isReferenceType() && "union has reference member");
Manman Renc451e572013-04-04 21:53:22 +00003297 // TODO: handle path-aware TBAA for union.
3298 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003299 } else {
3300 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003301 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003302
3303 // If this is a reference field, load the reference right now.
3304 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3305 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3306 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3307
Manman Renc451e572013-04-04 21:53:22 +00003308 // Loading the reference will disable path-aware TBAA.
3309 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003310 if (CGM.shouldUseTBAA()) {
3311 llvm::MDNode *tbaa;
3312 if (mayAlias)
3313 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3314 else
3315 tbaa = CGM.getTBAAInfo(type);
Manman Ren4f755de2013-10-08 00:08:49 +00003316 if (tbaa)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00003317 CGM.DecorateInstructionWithTBAA(load, tbaa);
John McCall53fcbd22011-02-26 08:07:02 +00003318 }
3319
John McCall53fcbd22011-02-26 08:07:02 +00003320 mayAlias = false;
3321 type = refType->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003322
3323 CharUnits alignment =
3324 getNaturalTypeAlignment(type, &fieldAlignSource, /*pointee*/ true);
3325 addr = Address(load, alignment);
3326
3327 // Qualifiers on the struct don't apply to the referencee, and
3328 // we'll pick up CVR from the actual type later, so reset these
3329 // additional qualifiers now.
3330 cvr = 0;
John McCall53fcbd22011-02-26 08:07:02 +00003331 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003332 }
Craig Topper99e79272013-07-26 05:59:26 +00003333
Chris Lattner13ee4f42011-07-10 05:34:54 +00003334 // Make sure that the address is pointing to the right type. This is critical
3335 // for both unions and structs. A union needs a bitcast, a struct element
3336 // will need a bitcast if the LLVM type laid out doesn't match the desired
3337 // type.
John McCall7f416cc2015-09-08 08:05:57 +00003338 addr = Builder.CreateElementBitCast(addr,
3339 CGM.getTypes().ConvertTypeForMem(type),
3340 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003341
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003342 if (field->hasAttr<AnnotateAttr>())
3343 addr = EmitFieldAnnotations(field, addr);
3344
John McCall7f416cc2015-09-08 08:05:57 +00003345 LValue LV = MakeAddrLValue(addr, type, fieldAlignSource);
John McCall53fcbd22011-02-26 08:07:02 +00003346 LV.getQuals().addCVRQualifiers(cvr);
Manman Renc451e572013-04-04 21:53:22 +00003347 if (TBAAPath) {
3348 const ASTRecordLayout &Layout =
3349 getContext().getASTRecordLayout(field->getParent());
3350 // Set the base type to be the base type of the base LValue and
3351 // update offset to be relative to the base type.
Manman Ren0e521662013-04-27 00:39:37 +00003352 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3353 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
Manman Renc451e572013-04-04 21:53:22 +00003354 Layout.getFieldOffset(field->getFieldIndex()) /
3355 getContext().getCharWidth());
3356 }
Daniel Dunbarf166a522010-08-21 03:44:13 +00003357
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003358 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003359 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3360 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003361
3362 // Fields of may_alias structs act like 'char' for TBAA purposes.
3363 // FIXME: this should get propagated down through anonymous structs
3364 // and unions.
3365 if (mayAlias && LV.getTBAAInfo())
3366 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3367
Daniel Dunbarf166a522010-08-21 03:44:13 +00003368 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003369}
3370
Craig Topper99e79272013-07-26 05:59:26 +00003371LValue
3372CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003373 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003374 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003375
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003376 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003377 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003378
John McCall7f416cc2015-09-08 08:05:57 +00003379 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003380
John McCall7f416cc2015-09-08 08:05:57 +00003381 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003382 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003383 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003384
John McCall7f416cc2015-09-08 08:05:57 +00003385 // TODO: access-path TBAA?
3386 auto FieldAlignSource = getFieldAlignmentSource(Base.getAlignmentSource());
3387 return MakeAddrLValue(V, FieldType, FieldAlignSource);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003388}
3389
Chris Lattnerf53c0962010-09-06 00:11:41 +00003390LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00003391 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003392 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3393 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
Richard Smith2d988f02011-11-22 22:48:32 +00003394 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003395 if (E->getType()->isVariablyModifiedType())
3396 // make sure to emit the VLA size.
3397 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003398
John McCall7f416cc2015-09-08 08:05:57 +00003399 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003400 const Expr *InitExpr = E->getInitializer();
John McCall7f416cc2015-09-08 08:05:57 +00003401 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003402
Chad Rosier615ed1a2012-03-29 17:37:10 +00003403 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3404 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003405
3406 return Result;
3407}
3408
Richard Smithbb653bd2012-05-14 21:57:21 +00003409LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3410 if (!E->isGLValue())
3411 // Initializing an aggregate temporary in C++11: T{...}.
3412 return EmitAggExprToLValue(E);
3413
3414 // An lvalue initializer list must be initializing a reference.
3415 assert(E->getNumInits() == 1 && "reference init with multiple values");
3416 return EmitLValue(E->getInit(0));
3417}
3418
Richard Smithf3076ff2014-06-20 18:43:47 +00003419/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3420/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3421/// LValue is returned and the current block has been terminated.
3422static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3423 const Expr *Operand) {
3424 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3425 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3426 return None;
3427 }
3428
3429 return CGF.EmitLValue(Operand);
3430}
3431
John McCallc07a0c72011-02-17 10:25:35 +00003432LValue CodeGenFunction::
3433EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3434 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003435 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003436 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003437 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003438 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003439 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003440
Eli Friedman59954892012-01-25 05:04:17 +00003441 OpaqueValueMapping binding(*this, expr);
3442
John McCallc07a0c72011-02-17 10:25:35 +00003443 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003444 bool CondExprBool;
3445 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003446 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003447 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003448
Justin Bogneref512b92014-01-06 22:27:43 +00003449 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003450 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003451 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003452 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003453 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003454 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003455 }
3456
John McCallc07a0c72011-02-17 10:25:35 +00003457 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3458 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3459 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003460
3461 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003462 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003463
John McCall0a6bf2e2011-01-26 19:21:13 +00003464 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003465 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003466 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003467 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003468 Optional<LValue> lhs =
3469 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003470 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003471
Richard Smithf3076ff2014-06-20 18:43:47 +00003472 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003473 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003474
John McCallc07a0c72011-02-17 10:25:35 +00003475 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003476 if (lhs)
3477 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003478
John McCall0a6bf2e2011-01-26 19:21:13 +00003479 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003480 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003481 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003482 Optional<LValue> rhs =
3483 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003484 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003485 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003486 return EmitUnsupportedLValue(expr, "conditional operator");
3487 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003488
John McCallc07a0c72011-02-17 10:25:35 +00003489 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003490
Richard Smithf3076ff2014-06-20 18:43:47 +00003491 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003492 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003493 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003494 phi->addIncoming(lhs->getPointer(), lhsBlock);
3495 phi->addIncoming(rhs->getPointer(), rhsBlock);
3496 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3497 AlignmentSource alignSource =
3498 std::max(lhs->getAlignmentSource(), rhs->getAlignmentSource());
3499 return MakeAddrLValue(result, expr->getType(), alignSource);
Richard Smithf3076ff2014-06-20 18:43:47 +00003500 } else {
3501 assert((lhs || rhs) &&
3502 "both operands of glvalue conditional are throw-expressions?");
3503 return lhs ? *lhs : *rhs;
3504 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003505}
3506
Richard Smithbb653bd2012-05-14 21:57:21 +00003507/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3508/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003509/// otherwise if a cast is needed by the code generator in an lvalue context,
3510/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003511/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003512/// are permitted with aggregate result, including noop aggregate casts, and
3513/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003514LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003515 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003516 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003517 case CK_BitCast:
3518 case CK_ArrayToPointerDecay:
3519 case CK_FunctionToPointerDecay:
3520 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003521 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003522 case CK_IntegralToPointer:
3523 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003524 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003525 case CK_VectorSplat:
3526 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00003527 case CK_BooleanToSignedIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003528 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003529 case CK_IntegralToFloating:
3530 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003531 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003532 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003533 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003534 case CK_FloatingComplexToReal:
3535 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003536 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003537 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003538 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003539 case CK_IntegralComplexToReal:
3540 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003541 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003542 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003543 case CK_DerivedToBaseMemberPointer:
3544 case CK_BaseToDerivedMemberPointer:
3545 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003546 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003547 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003548 case CK_ARCProduceObject:
3549 case CK_ARCConsumeObject:
3550 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003551 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003552 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003553 case CK_AddressSpaceConversion:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003554 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3555
3556 case CK_Dependent:
3557 llvm_unreachable("dependent cast kind in IR gen!");
3558
3559 case CK_BuiltinFnToFnPtr:
3560 llvm_unreachable("builtin functions are handled elsewhere");
3561
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003562 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003563 case CK_NonAtomicToAtomic:
3564 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003565 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00003566
Anders Carlsson8a01a752011-04-11 02:03:26 +00003567 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00003568 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003569 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003570 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00003571 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00003572 }
3573
John McCalle3027922010-08-25 11:45:40 +00003574 case CK_ConstructorConversion:
3575 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00003576 case CK_CPointerToObjCPointerCast:
3577 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003578 case CK_NoOp:
3579 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003580 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00003581
John McCalle3027922010-08-25 11:45:40 +00003582 case CK_UncheckedDerivedToBase:
3583 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00003584 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00003585 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003586 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003587
Anders Carlssond95f9602009-09-12 16:16:49 +00003588 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003589 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00003590
Anders Carlssond95f9602009-09-12 16:16:49 +00003591 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00003592 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00003593 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3594 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00003595
John McCall7f416cc2015-09-08 08:05:57 +00003596 return MakeAddrLValue(Base, E->getType(), LV.getAlignmentSource());
Anders Carlssond95f9602009-09-12 16:16:49 +00003597 }
John McCalle3027922010-08-25 11:45:40 +00003598 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00003599 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00003600 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00003601 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003602 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003603
Anders Carlsson8c793172009-11-23 17:57:54 +00003604 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00003605
Anders Carlsson8c793172009-11-23 17:57:54 +00003606 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00003607 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00003608 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00003609 E->path_begin(), E->path_end(),
3610 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00003611
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003612 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3613 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00003614 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003615 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00003616 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003617
Peter Collingbourned2926c92015-03-14 02:42:25 +00003618 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003619 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3620 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003621 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003622
John McCall7f416cc2015-09-08 08:05:57 +00003623 return MakeAddrLValue(Derived, E->getType(), LV.getAlignmentSource());
Eli Friedman8c98dff2009-11-16 05:48:01 +00003624 }
John McCalle3027922010-08-25 11:45:40 +00003625 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00003626 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003627 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00003628
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00003629 CGM.EmitExplicitCastExprType(CE, this);
Anders Carlsson50cb3212009-11-14 21:21:42 +00003630 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003631 Address V = Builder.CreateBitCast(LV.getAddress(),
3632 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00003633
3634 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003635 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3636 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003637 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003638
John McCall7f416cc2015-09-08 08:05:57 +00003639 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Anders Carlsson50cb3212009-11-14 21:21:42 +00003640 }
John McCalle3027922010-08-25 11:45:40 +00003641 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003642 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003643 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3644 ConvertType(E->getType()));
3645 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003646 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003647 case CK_ZeroToOCLEvent:
3648 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00003649 }
Craig Topper99e79272013-07-26 05:59:26 +00003650
Douglas Gregorcdb466e2010-07-15 18:58:16 +00003651 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003652}
3653
John McCall1bf58462011-02-16 08:02:54 +00003654LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00003655 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00003656 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00003657}
3658
Eli Friedman7f1ff602012-04-16 03:54:45 +00003659RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003660 const FieldDecl *FD,
3661 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003662 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003663 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00003664 switch (getEvaluationKind(FT)) {
3665 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003666 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00003667 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00003668 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00003669 case TEK_Scalar:
Reid Kleckner9d031092016-05-02 22:42:34 +00003670 // This routine is used to load fields one-by-one to perform a copy, so
3671 // don't load reference fields.
3672 if (FD->getType()->isReferenceType())
3673 return RValue::get(FieldLV.getPointer());
Nick Lewycky2d84e842013-10-02 02:29:49 +00003674 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00003675 }
3676 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003677}
Douglas Gregorfe314812011-06-21 17:03:29 +00003678
Chris Lattnere47e4402007-06-01 18:02:12 +00003679//===--------------------------------------------------------------------===//
3680// Expression Emission
3681//===--------------------------------------------------------------------===//
3682
Craig Topper99e79272013-07-26 05:59:26 +00003683RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00003684 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003685 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003686 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00003687 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003688
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003689 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003690 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003691
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003692 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00003693 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3694
Douglas Gregore0e96302011-09-06 21:41:04 +00003695 const Decl *TargetDecl = E->getCalleeDecl();
3696 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
3697 if (unsigned builtinID = FD->getBuiltinID())
Peter Collingbournef7706832014-12-12 23:41:25 +00003698 return EmitBuiltinExpr(FD, builtinID, E, ReturnValue);
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003699 }
3700
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003701 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
Anders Carlsson4034a952009-05-27 04:18:27 +00003702 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003703 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003704
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003705 if (const auto *PseudoDtor =
3706 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
John McCall31168b02011-06-15 23:02:42 +00003707 QualType DestroyedType = PseudoDtor->getDestroyedType();
John McCall460ce582015-10-22 18:38:17 +00003708 if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003709 // Automatic Reference Counting:
3710 // If the pseudo-expression names a retainable object with weak or
3711 // strong lifetime, the object shall be released.
John McCall31168b02011-06-15 23:02:42 +00003712 Expr *BaseExpr = PseudoDtor->getBase();
John McCall7f416cc2015-09-08 08:05:57 +00003713 Address BaseValue = Address::invalid();
John McCall31168b02011-06-15 23:02:42 +00003714 Qualifiers BaseQuals;
Craig Topper99e79272013-07-26 05:59:26 +00003715
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003716 // 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 +00003717 if (PseudoDtor->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00003718 BaseValue = EmitPointerWithAlignment(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00003719 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
3720 BaseQuals = PTy->getPointeeType().getQualifiers();
3721 } else {
3722 LValue BaseLV = EmitLValue(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00003723 BaseValue = BaseLV.getAddress();
3724 QualType BaseTy = BaseExpr->getType();
3725 BaseQuals = BaseTy.getQualifiers();
3726 }
Craig Topper99e79272013-07-26 05:59:26 +00003727
John McCall460ce582015-10-22 18:38:17 +00003728 switch (DestroyedType.getObjCLifetime()) {
John McCall31168b02011-06-15 23:02:42 +00003729 case Qualifiers::OCL_None:
3730 case Qualifiers::OCL_ExplicitNone:
3731 case Qualifiers::OCL_Autoreleasing:
3732 break;
Craig Topper99e79272013-07-26 05:59:26 +00003733
John McCall31168b02011-06-15 23:02:42 +00003734 case Qualifiers::OCL_Strong:
Craig Topper99e79272013-07-26 05:59:26 +00003735 EmitARCRelease(Builder.CreateLoad(BaseValue,
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003736 PseudoDtor->getDestroyedType().isVolatileQualified()),
John McCallcdda29c2013-03-13 03:10:54 +00003737 ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00003738 break;
3739
3740 case Qualifiers::OCL_Weak:
3741 EmitARCDestroyWeak(BaseValue);
3742 break;
3743 }
3744 } else {
3745 // C++ [expr.pseudo]p1:
3746 // The result shall only be used as the operand for the function call
3747 // operator (), and the result of such a call has type void. The only
3748 // effect is the evaluation of the postfix-expression before the dot or
Craig Topper99e79272013-07-26 05:59:26 +00003749 // arrow.
John McCall31168b02011-06-15 23:02:42 +00003750 EmitScalarExpr(E->getCallee());
3751 }
Craig Topper99e79272013-07-26 05:59:26 +00003752
Craig Topper8a13c412014-05-21 05:09:00 +00003753 return RValue::get(nullptr);
Douglas Gregorad8a3362009-09-04 17:36:40 +00003754 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003755
Chris Lattner2da04b32007-08-24 05:35:26 +00003756 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003757 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
3758 TargetDecl);
Chris Lattner9e47ead2007-08-31 04:44:06 +00003759}
3760
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003761LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00003762 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00003763 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00003764 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00003765 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00003766 return EmitLValue(E->getRHS());
3767 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003768
John McCalle3027922010-08-25 11:45:40 +00003769 if (E->getOpcode() == BO_PtrMemD ||
3770 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003771 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003772
John McCalla2342eb2010-12-05 02:00:02 +00003773 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00003774
3775 // Note that in all of these cases, __block variables need the RHS
3776 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00003777
3778 switch (getEvaluationKind(E->getType())) {
3779 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00003780 switch (E->getLHS()->getType().getObjCLifetime()) {
3781 case Qualifiers::OCL_Strong:
3782 return EmitARCStoreStrong(E, /*ignored*/ false).first;
3783
3784 case Qualifiers::OCL_Autoreleasing:
3785 return EmitARCStoreAutoreleasing(E).first;
3786
3787 // No reason to do any of these differently.
3788 case Qualifiers::OCL_None:
3789 case Qualifiers::OCL_ExplicitNone:
3790 case Qualifiers::OCL_Weak:
3791 break;
3792 }
3793
John McCalld0a30012010-12-06 06:10:02 +00003794 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00003795 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
John McCall55e1fbc2011-06-25 02:11:03 +00003796 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00003797 return LV;
3798 }
John McCall4f29b492010-11-16 23:07:28 +00003799
John McCall47fb9502013-03-07 21:37:08 +00003800 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00003801 return EmitComplexAssignmentLValue(E);
3802
John McCall47fb9502013-03-07 21:37:08 +00003803 case TEK_Aggregate:
3804 return EmitAggExprToLValue(E);
3805 }
3806 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003807}
3808
Christopher Lambd91c3d42007-12-29 05:02:41 +00003809LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00003810 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00003811
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003812 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00003813 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3814 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00003815
David Majnemerced8bdf2015-02-25 17:36:15 +00003816 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003817 "Can't have a scalar return unless the return type is a "
3818 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00003819
John McCall7f416cc2015-09-08 08:05:57 +00003820 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00003821}
3822
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003823LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
3824 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00003825 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003826}
3827
Anders Carlsson3be22e22009-05-30 23:23:33 +00003828LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003829 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
3830 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00003831 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00003832 EmitCXXConstructExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003833 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3834 AlignmentSource::Decl);
Anders Carlsson3be22e22009-05-30 23:23:33 +00003835}
3836
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003837LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00003838CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003839 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00003840}
3841
John McCall7f416cc2015-09-08 08:05:57 +00003842Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
3843 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
3844 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00003845}
3846
3847LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003848 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
3849 AlignmentSource::Decl);
Nico Webercf4ff5862012-10-11 10:13:44 +00003850}
3851
Mike Stumpc9b231c2009-11-15 08:09:41 +00003852LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003853CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003854 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00003855 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00003856 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003857 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
3858 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3859 AlignmentSource::Decl);
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003860}
3861
Eli Friedman5bc17122012-02-08 05:34:55 +00003862LValue
3863CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00003864 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00003865 EmitLambdaExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003866 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3867 AlignmentSource::Decl);
Eli Friedman5bc17122012-02-08 05:34:55 +00003868}
3869
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003870LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003871 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00003872
Anders Carlsson280e61f12010-06-21 20:59:55 +00003873 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00003874 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3875 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00003876
Alp Toker314cc812014-01-25 16:55:45 +00003877 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00003878 "Can't have a scalar return unless the return type is a "
3879 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00003880
John McCall7f416cc2015-09-08 08:05:57 +00003881 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003882}
3883
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003884LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003885 Address V =
3886 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
3887 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003888}
3889
Daniel Dunbar722f4242009-04-22 05:08:15 +00003890llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003891 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00003892 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003893}
3894
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003895LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
3896 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003897 const ObjCIvarDecl *Ivar,
3898 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00003899 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00003900 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003901}
3902
3903LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003904 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00003905 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003906 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00003907 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003908 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003909 if (E->isArrow()) {
3910 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003911 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00003912 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003913 } else {
3914 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00003915 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003916 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00003917 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003918 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003919
Craig Topper99e79272013-07-26 05:59:26 +00003920 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00003921 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
3922 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00003923 setObjCGCLValueClass(getContext(), E, LV);
3924 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00003925}
3926
Chris Lattnera4185c52009-04-25 19:35:26 +00003927LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00003928 // Can only get l-value for message expression returning aggregate type
3929 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00003930 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3931 AlignmentSource::Decl);
Chris Lattnera4185c52009-04-25 19:35:26 +00003932}
3933
Anders Carlsson0435ed52009-12-24 19:08:58 +00003934RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003935 const CallExpr *E, ReturnValueSlot ReturnValue,
Samuel Antao798f11c2015-11-23 22:04:44 +00003936 CGCalleeInfo CalleeInfo, llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00003937 // Get the actual function type. The callee type will always be a pointer to
3938 // function type or a block pointer type.
3939 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00003940 "Call must have function pointer type!");
3941
Samuel Antao798f11c2015-11-23 22:04:44 +00003942 // Preserve the non-canonical function type because things like exception
3943 // specifications disappear in the canonical type. That information is useful
3944 // to drive the generation of more accurate code for this call later on.
3945 const FunctionProtoType *NonCanonicalFTP = CalleeType->getAs<PointerType>()
3946 ->getPointeeType()
3947 ->getAs<FunctionProtoType>();
3948
3949 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
3950
Eric Christopher2b2d56f2015-11-12 00:44:12 +00003951 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
Eric Christopher39db7262015-11-14 01:56:04 +00003952 // We can only guarantee that a function is called from the correct
3953 // context/function based on the appropriate target attributes,
3954 // so only check in the case where we have both always_inline and target
3955 // since otherwise we could be making a conditional call after a check for
3956 // the proper cpu features (and it won't cause code generation issues due to
3957 // function based code generation).
Eric Christopher2b2d56f2015-11-12 00:44:12 +00003958 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
3959 TargetDecl->hasAttr<TargetAttr>())
3960 checkTargetFeatures(E, FD);
3961
John McCall6fd4c232009-10-23 08:22:42 +00003962 CalleeType = getContext().getCanonicalType(CalleeType);
3963
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003964 const auto *FnType =
3965 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00003966
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003967 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003968 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
3969 if (llvm::Constant *PrefixSig =
3970 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003971 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003972 llvm::Constant *FTRTTIConst =
3973 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
3974 llvm::Type *PrefixStructTyElems[] = {
3975 PrefixSig->getType(),
3976 FTRTTIConst->getType()
3977 };
3978 llvm::StructType *PrefixStructTy = llvm::StructType::get(
3979 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
3980
3981 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
3982 Callee, llvm::PointerType::getUnqual(PrefixStructTy));
3983 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00003984 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00003985 llvm::Value *CalleeSig =
3986 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003987 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
3988
3989 llvm::BasicBlock *Cont = createBasicBlock("cont");
3990 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
3991 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
3992
3993 EmitBlock(TypeCheck);
3994 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00003995 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003996 llvm::Value *CalleeRTTI =
3997 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003998 llvm::Value *CalleeRTTIMatch =
3999 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4000 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004001 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004002 EmitCheckTypeDescriptor(CalleeType)
4003 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00004004 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
4005 "function_type_mismatch", StaticData, Callee);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004006
4007 Builder.CreateBr(Cont);
4008 EmitBlock(Cont);
4009 }
4010 }
4011
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004012 // If we are checking indirect calls and this call is indirect, check that the
4013 // function pointer is a member of the bit set for the function type.
4014 if (SanOpts.has(SanitizerKind::CFIICall) &&
4015 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4016 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00004017 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004018
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004019 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
4020 llvm::Value *BitSetName = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004021
4022 llvm::Value *CastedCallee = Builder.CreateBitCast(Callee, Int8PtrTy);
4023 llvm::Value *BitSetTest =
4024 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::bitset_test),
4025 {CastedCallee, BitSetName});
4026
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004027 auto TypeId = CGM.CreateCfiIdForTypeMetadata(MD);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004028 llvm::Constant *StaticData[] = {
4029 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4030 EmitCheckSourceLocation(E->getLocStart()),
4031 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4032 };
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004033 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && TypeId) {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004034 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, BitSetTest, TypeId,
4035 CastedCallee, StaticData);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004036 } else {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004037 EmitCheck(std::make_pair(BitSetTest, SanitizerKind::CFIICall),
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004038 "cfi_check_fail", StaticData,
4039 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004040 }
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004041 }
4042
Daniel Dunbarc722b852008-08-30 03:02:31 +00004043 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00004044 if (Chain)
4045 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4046 CGM.getContext().VoidPtrTy);
David Blaikief05779e2015-07-21 18:37:18 +00004047 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
4048 E->getDirectCallee(), /*ParamsToSkip*/ 0);
Daniel Dunbarc722b852008-08-30 03:02:31 +00004049
Peter Collingbournef7706832014-12-12 23:41:25 +00004050 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4051 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00004052
4053 // C99 6.5.2.2p6:
4054 // If the expression that denotes the called function has a type
4055 // that does not include a prototype, [the default argument
4056 // promotions are performed]. If the number of arguments does not
4057 // equal the number of parameters, the behavior is undefined. If
4058 // the function is defined with a type that includes a prototype,
4059 // and either the prototype ends with an ellipsis (, ...) or the
4060 // types of the arguments after promotion are not compatible with
4061 // the types of the parameters, the behavior is undefined. If the
4062 // function is defined with a type that does not include a
4063 // prototype, and the types of the arguments after promotion are
4064 // not compatible with those of the parameters after promotion,
4065 // the behavior is undefined [except in some trivial cases].
4066 // That is, in the general case, we should assume that a call
4067 // through an unprototyped function type works like a *non-variadic*
4068 // call. The way we make this work is to cast to the exact type
4069 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00004070 //
4071 // Chain calls use this same code path to add the invisible chain parameter
4072 // to the function type.
4073 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00004074 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00004075 CalleeTy = CalleeTy->getPointerTo();
4076 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
4077 }
4078
Samuel Antao798f11c2015-11-23 22:04:44 +00004079 return EmitCall(FnInfo, Callee, ReturnValue, Args,
4080 CGCalleeInfo(NonCanonicalFTP, TargetDecl));
Daniel Dunbar97db84c2008-08-23 03:46:30 +00004081}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004082
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004083LValue CodeGenFunction::
4084EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004085 Address BaseAddr = Address::invalid();
4086 if (E->getOpcode() == BO_PtrMemI) {
4087 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4088 } else {
4089 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4090 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004091
John McCallc134eb52010-08-31 21:07:20 +00004092 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4093
4094 const MemberPointerType *MPT
4095 = E->getRHS()->getType()->getAs<MemberPointerType>();
4096
John McCall7f416cc2015-09-08 08:05:57 +00004097 AlignmentSource AlignSource;
4098 Address MemberAddr =
4099 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT,
4100 &AlignSource);
John McCallc134eb52010-08-31 21:07:20 +00004101
John McCall7f416cc2015-09-08 08:05:57 +00004102 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), AlignSource);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004103}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004104
John McCall47fb9502013-03-07 21:37:08 +00004105/// Given the address of a temporary variable, produce an r-value of
4106/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00004107RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004108 QualType type,
4109 SourceLocation loc) {
John McCall7f416cc2015-09-08 08:05:57 +00004110 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
John McCall47fb9502013-03-07 21:37:08 +00004111 switch (getEvaluationKind(type)) {
4112 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004113 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004114 case TEK_Aggregate:
4115 return lvalue.asAggregateRValue();
4116 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004117 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004118 }
4119 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004120}
4121
Duncan Sandse81111c2012-04-10 08:23:07 +00004122void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004123 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00004124 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004125 return;
4126
Duncan Sands65229ed2012-04-16 16:29:47 +00004127 llvm::MDBuilder MDHelper(getLLVMContext());
4128 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004129
Duncan Sands6fc46192012-04-14 12:37:26 +00004130 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004131}
John McCallfe96e0b2011-11-06 09:01:30 +00004132
4133namespace {
4134 struct LValueOrRValue {
4135 LValue LV;
4136 RValue RV;
4137 };
4138}
4139
4140static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4141 const PseudoObjectExpr *E,
4142 bool forLValue,
4143 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004144 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00004145
4146 // Find the result expression, if any.
4147 const Expr *resultExpr = E->getResultExpr();
4148 LValueOrRValue result;
4149
4150 for (PseudoObjectExpr::const_semantics_iterator
4151 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4152 const Expr *semantic = *i;
4153
4154 // If this semantic expression is an opaque value, bind it
4155 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004156 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00004157
4158 // If this is the result expression, we may need to evaluate
4159 // directly into the slot.
4160 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4161 OVMA opaqueData;
4162 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00004163 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00004164 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
4165
John McCall7f416cc2015-09-08 08:05:57 +00004166 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4167 AlignmentSource::Decl);
John McCallfe96e0b2011-11-06 09:01:30 +00004168 opaqueData = OVMA::bind(CGF, ov, LV);
4169 result.RV = slot.asRValue();
4170
4171 // Otherwise, emit as normal.
4172 } else {
4173 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4174
4175 // If this is the result, also evaluate the result now.
4176 if (ov == resultExpr) {
4177 if (forLValue)
4178 result.LV = CGF.EmitLValue(ov);
4179 else
4180 result.RV = CGF.EmitAnyExpr(ov, slot);
4181 }
4182 }
4183
4184 opaques.push_back(opaqueData);
4185
4186 // Otherwise, if the expression is the result, evaluate it
4187 // and remember the result.
4188 } else if (semantic == resultExpr) {
4189 if (forLValue)
4190 result.LV = CGF.EmitLValue(semantic);
4191 else
4192 result.RV = CGF.EmitAnyExpr(semantic, slot);
4193
4194 // Otherwise, evaluate the expression in an ignored context.
4195 } else {
4196 CGF.EmitIgnoredExpr(semantic);
4197 }
4198 }
4199
4200 // Unbind all the opaques now.
4201 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4202 opaques[i].unbind(CGF);
4203
4204 return result;
4205}
4206
4207RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4208 AggValueSlot slot) {
4209 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4210}
4211
4212LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4213 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4214}