blob: ab4448bf3c56362219a5719a42f19aa757d5c529 [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
John McCall5d865c322010-08-31 07:33:07 +000014#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CGCall.h"
Tim Shen421119f2016-07-01 21:08:47 +000016#include "CGCleanup.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"
Tim Shen421119f2016-07-01 21:08:47 +000021#include "CodeGenFunction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "CodeGenModule.h"
John McCallcbc038a2011-09-21 08:08:30 +000023#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000024#include "clang/AST/ASTContext.h"
Renato Golin230c5eb2014-05-19 18:15:42 +000025#include "clang/AST/Attr.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000026#include "clang/AST/DeclObjC.h"
Vedant Kumar4593a462016-12-09 23:48:18 +000027#include "clang/AST/NSAPI.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000028#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "llvm/ADT/Hashing.h"
Alexey Bataevec474782014-10-09 08:45:04 +000030#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000031#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/IR/MDBuilder.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000035#include "llvm/Support/ConvertUTF.h"
Peter Collingbourne3eea6772015-05-11 21:39:14 +000036#include "llvm/Support/MathExtras.h"
Filipe Cabecinhasab731f72016-05-12 16:51:36 +000037#include "llvm/Support/Path.h"
Peter Collingbournedc134532016-01-16 00:31:22 +000038#include "llvm/Transforms/Utils/SanitizerStats.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000039
Filipe Cabecinhas84171bd2016-12-12 16:43:40 +000040#include <string>
41
Chris Lattnere47e4402007-06-01 18:02:12 +000042using namespace clang;
43using namespace CodeGen;
44
Chris Lattnerd7f58862007-06-02 05:24:33 +000045//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000046// Miscellaneous Helper Methods
47//===--------------------------------------------------------------------===//
48
John McCallad7c5c12011-02-08 08:22:06 +000049llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
50 unsigned addressSpace =
51 cast<llvm::PointerType>(value->getType())->getAddressSpace();
52
Chris Lattner2192fe52011-07-18 04:24:23 +000053 llvm::PointerType *destType = Int8PtrTy;
John McCallad7c5c12011-02-08 08:22:06 +000054 if (addressSpace)
55 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
56
57 if (value->getType() == destType) return value;
58 return Builder.CreateBitCast(value, destType);
59}
60
Chris Lattnere9a64532007-06-22 21:44:33 +000061/// CreateTempAlloca - This creates a alloca and inserts it into the entry
62/// block.
John McCall7f416cc2015-09-08 08:05:57 +000063Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
64 const Twine &Name) {
65 auto Alloca = CreateTempAlloca(Ty, Name);
66 Alloca->setAlignment(Align.getQuantity());
67 return Address(Alloca, Align);
68}
69
70/// CreateTempAlloca - This creates a alloca and inserts it into the entry
71/// block.
Chris Lattner2192fe52011-07-18 04:24:23 +000072llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000073 const Twine &Name) {
Craig Topper8a13c412014-05-21 05:09:00 +000074 return new llvm::AllocaInst(Ty, nullptr, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +000075}
Chris Lattner8394d792007-06-05 20:53:16 +000076
John McCall7f416cc2015-09-08 08:05:57 +000077/// CreateDefaultAlignTempAlloca - This creates an alloca with the
78/// default alignment of the corresponding LLVM type, which is *not*
79/// guaranteed to be related in any way to the expected alignment of
80/// an AST type that might have been lowered to Ty.
81Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
82 const Twine &Name) {
83 CharUnits Align =
84 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
85 return CreateTempAlloca(Ty, Align, Name);
86}
87
88void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
89 assert(isa<llvm::AllocaInst>(Var.getPointer()));
90 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
91 Store->setAlignment(Var.getAlignment().getQuantity());
John McCall2e6567a2010-04-22 01:10:34 +000092 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +000093 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
John McCall2e6567a2010-04-22 01:10:34 +000094}
95
John McCall7f416cc2015-09-08 08:05:57 +000096Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +000097 CharUnits Align = getContext().getTypeAlignInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +000098 return CreateTempAlloca(ConvertType(Ty), Align, Name);
Daniel Dunbard0049182010-02-16 19:44:13 +000099}
100
John McCall7f416cc2015-09-08 08:05:57 +0000101Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name) {
Daniel Dunbara7566f12010-02-09 02:48:28 +0000102 // FIXME: Should we prefer the preferred type alignment here?
John McCall7f416cc2015-09-08 08:05:57 +0000103 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name);
104}
105
106Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
107 const Twine &Name) {
108 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name);
Daniel Dunbara7566f12010-02-09 02:48:28 +0000109}
110
Chris Lattner8394d792007-06-05 20:53:16 +0000111/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
112/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000113llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000114 PGO.setCurrentStmt(E);
John McCall7a9aac22010-08-23 01:21:21 +0000115 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +0000116 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +0000117 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +0000118 }
John McCall7a9aac22010-08-23 01:21:21 +0000119
120 QualType BoolTy = getContext().BoolTy;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000121 SourceLocation Loc = E->getExprLoc();
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000122 if (!E->getType()->isAnyComplexType())
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000123 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +0000124
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000125 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
126 Loc);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000127}
128
John McCalla2342eb2010-12-05 02:00:02 +0000129/// EmitIgnoredExpr - Emit code to compute the specified expression,
130/// ignoring the result.
131void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
132 if (E->isRValue())
133 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
134
135 // Just emit it as an l-value and drop the result.
136 EmitLValue(E);
137}
138
John McCall7a626f62010-09-15 10:14:12 +0000139/// EmitAnyExpr - Emit code to compute the specified expression which
140/// can have any type. The result is returned as an RValue struct.
141/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000142/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000143RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
144 AggValueSlot aggSlot,
145 bool ignoreResult) {
John McCall47fb9502013-03-07 21:37:08 +0000146 switch (getEvaluationKind(E->getType())) {
147 case TEK_Scalar:
John McCall4e8ca4f2012-07-02 23:58:38 +0000148 return RValue::get(EmitScalarExpr(E, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000149 case TEK_Complex:
John McCall4e8ca4f2012-07-02 23:58:38 +0000150 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000151 case TEK_Aggregate:
152 if (!ignoreResult && aggSlot.isIgnored())
153 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
154 EmitAggExpr(E, aggSlot);
155 return aggSlot.asRValue();
156 }
157 llvm_unreachable("bad evaluation kind");
Chris Lattner4647a212007-08-31 22:49:20 +0000158}
159
Mike Stump4a3999f2009-09-09 13:00:44 +0000160/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
161/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000162RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
163 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000164
John McCall47fb9502013-03-07 21:37:08 +0000165 if (hasAggregateEvaluationKind(E->getType()))
John McCall7a626f62010-09-15 10:14:12 +0000166 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
167 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000168}
169
John McCall21886962010-04-21 10:05:39 +0000170/// EmitAnyExprToMem - Evaluate an expression into a given memory
171/// location.
172void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000173 Address Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000174 Qualifiers Quals,
175 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000176 // FIXME: This function should take an LValue as an argument.
John McCall47fb9502013-03-07 21:37:08 +0000177 switch (getEvaluationKind(E->getType())) {
178 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000179 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
John McCall47fb9502013-03-07 21:37:08 +0000180 /*isInit*/ false);
181 return;
182
183 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000184 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000185 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000186 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000187 AggValueSlot::IsAliased_t(!IsInit)));
John McCall47fb9502013-03-07 21:37:08 +0000188 return;
189 }
190
191 case TEK_Scalar: {
John McCall21886962010-04-21 10:05:39 +0000192 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000193 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000194 EmitStoreThroughLValue(RV, LV);
John McCall47fb9502013-03-07 21:37:08 +0000195 return;
John McCall21886962010-04-21 10:05:39 +0000196 }
John McCall47fb9502013-03-07 21:37:08 +0000197 }
198 llvm_unreachable("bad evaluation kind");
John McCall21886962010-04-21 10:05:39 +0000199}
200
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000201static void
202pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
John McCall7f416cc2015-09-08 08:05:57 +0000203 const Expr *E, Address ReferenceTemporary) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000204 // Objective-C++ ARC:
205 // If we are binding a reference to a temporary that has ownership, we
206 // need to perform retain/release operations on the temporary.
Richard Smith736a9472013-06-12 20:42:33 +0000207 //
208 // FIXME: This should be looking at E, not M.
John McCall460ce582015-10-22 18:38:17 +0000209 if (auto Lifetime = M->getType().getObjCLifetime()) {
210 switch (Lifetime) {
Richard Smith736a9472013-06-12 20:42:33 +0000211 case Qualifiers::OCL_None:
212 case Qualifiers::OCL_ExplicitNone:
213 // Carry on to normal cleanup handling.
214 break;
Sebastian Redl29526f02011-11-27 16:50:07 +0000215
Richard Smith736a9472013-06-12 20:42:33 +0000216 case Qualifiers::OCL_Autoreleasing:
217 // Nothing to do; cleaned up by an autorelease pool.
218 return;
219
220 case Qualifiers::OCL_Strong:
221 case Qualifiers::OCL_Weak:
222 switch (StorageDuration Duration = M->getStorageDuration()) {
223 case SD_Static:
224 // Note: we intentionally do not register a cleanup to release
225 // the object on program termination.
226 return;
227
228 case SD_Thread:
229 // FIXME: We should probably register a cleanup in this case.
230 return;
231
232 case SD_Automatic:
233 case SD_FullExpression:
Richard Smith736a9472013-06-12 20:42:33 +0000234 CodeGenFunction::Destroyer *Destroy;
235 CleanupKind CleanupKind;
236 if (Lifetime == Qualifiers::OCL_Strong) {
237 const ValueDecl *VD = M->getExtendingDecl();
238 bool Precise =
239 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
240 CleanupKind = CGF.getARCCleanupKind();
241 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
242 : &CodeGenFunction::destroyARCStrongImprecise;
243 } else {
244 // __weak objects always get EH cleanups; otherwise, exceptions
245 // could cause really nasty crashes instead of mere leaks.
246 CleanupKind = NormalAndEHCleanup;
247 Destroy = &CodeGenFunction::destroyARCWeak;
248 }
249 if (Duration == SD_FullExpression)
250 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000251 M->getType(), *Destroy,
Richard Smith736a9472013-06-12 20:42:33 +0000252 CleanupKind & EHCleanup);
253 else
254 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000255 M->getType(),
Richard Smith736a9472013-06-12 20:42:33 +0000256 *Destroy, CleanupKind & EHCleanup);
257 return;
258
259 case SD_Dynamic:
260 llvm_unreachable("temporary cannot have dynamic storage duration");
261 }
262 llvm_unreachable("unknown storage duration");
263 }
264 }
265
Craig Topper8a13c412014-05-21 05:09:00 +0000266 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
Richard Smith736a9472013-06-12 20:42:33 +0000267 if (const RecordType *RT =
268 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
269 // Get the destructor for the reference temporary.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000270 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith736a9472013-06-12 20:42:33 +0000271 if (!ClassDecl->hasTrivialDestructor())
272 ReferenceTemporaryDtor = ClassDecl->getDestructor();
273 }
274
275 if (!ReferenceTemporaryDtor)
276 return;
277
278 // Call the destructor for the temporary.
279 switch (M->getStorageDuration()) {
280 case SD_Static:
281 case SD_Thread: {
282 llvm::Constant *CleanupFn;
283 llvm::Constant *CleanupArg;
284 if (E->getType()->isArrayType()) {
285 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
John McCall7f416cc2015-09-08 08:05:57 +0000286 ReferenceTemporary, E->getType(),
David Blaikieebe87e12013-08-27 23:57:18 +0000287 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
288 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
Richard Smith736a9472013-06-12 20:42:33 +0000289 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
290 } else {
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000291 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
292 StructorType::Complete);
John McCall7f416cc2015-09-08 08:05:57 +0000293 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
Richard Smith736a9472013-06-12 20:42:33 +0000294 }
295 CGF.CGM.getCXXABI().registerGlobalDtor(
296 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
297 break;
298 }
299
300 case SD_FullExpression:
301 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
302 CodeGenFunction::destroyCXXObject,
303 CGF.getLangOpts().Exceptions);
304 break;
305
306 case SD_Automatic:
307 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
308 ReferenceTemporary, E->getType(),
309 CodeGenFunction::destroyCXXObject,
310 CGF.getLangOpts().Exceptions);
311 break;
312
313 case SD_Dynamic:
314 llvm_unreachable("temporary cannot have dynamic storage duration");
315 }
316}
317
John McCall7f416cc2015-09-08 08:05:57 +0000318static Address
Richard Smith736a9472013-06-12 20:42:33 +0000319createReferenceTemporary(CodeGenFunction &CGF,
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000320 const MaterializeTemporaryExpr *M, const Expr *Inner) {
Richard Smith736a9472013-06-12 20:42:33 +0000321 switch (M->getStorageDuration()) {
322 case SD_FullExpression:
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000323 case SD_Automatic: {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000324 // If we have a constant temporary array or record try to promote it into a
325 // constant global under the same rules a normal constant would've been
326 // promoted. This is easier on the optimizer and generally emits fewer
327 // instructions.
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000328 QualType Ty = Inner->getType();
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000329 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000330 (Ty->isArrayType() || Ty->isRecordType()) &&
331 CGF.CGM.isTypeConstant(Ty, true))
332 if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000333 auto *GV = new llvm::GlobalVariable(
334 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
335 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp");
John McCall7f416cc2015-09-08 08:05:57 +0000336 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
337 GV->setAlignment(alignment.getQuantity());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000338 // FIXME: Should we put the new global into a COMDAT?
John McCall7f416cc2015-09-08 08:05:57 +0000339 return Address(GV, alignment);
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000340 }
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000341 return CGF.CreateMemTemp(Ty, "ref.tmp");
342 }
Richard Smith736a9472013-06-12 20:42:33 +0000343 case SD_Thread:
344 case SD_Static:
Hans Wennborgf9d865b2015-03-17 16:38:58 +0000345 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
Richard Smith736a9472013-06-12 20:42:33 +0000346
347 case SD_Dynamic:
348 llvm_unreachable("temporary can't have dynamic storage duration");
349 }
350 llvm_unreachable("unknown storage duration");
351}
352
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000353LValue CodeGenFunction::
354EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000355 const Expr *E = M->GetTemporaryExpr();
Richard Smith7c5d4dc2013-06-11 02:41:00 +0000356
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000357 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
358 // as that will cause the lifetime adjustment to be lost for ARC
John McCall460ce582015-10-22 18:38:17 +0000359 auto ownership = M->getType().getObjCLifetime();
360 if (ownership != Qualifiers::OCL_None &&
361 ownership != Qualifiers::OCL_ExplicitNone) {
John McCall7f416cc2015-09-08 08:05:57 +0000362 Address Object = createReferenceTemporary(*this, M, E);
363 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
364 Object = Address(llvm::ConstantExpr::getBitCast(Var,
365 ConvertTypeForMem(E->getType())
366 ->getPointerTo(Object.getAddressSpace())),
367 Object.getAlignment());
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000368
369 // createReferenceTemporary will promote the temporary to a global with a
370 // constant initializer if it can. It can only do this to a value of
371 // ARC-manageable type if the value is global and therefore "immune" to
372 // ref-counting operations. Therefore we have no need to emit either a
373 // dynamic initialization or a cleanup and we can just return the address
374 // of the temporary.
375 if (Var->hasInitializer())
376 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
377
Richard Smitha509f2f2013-06-14 03:07:01 +0000378 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
379 }
John McCall7f416cc2015-09-08 08:05:57 +0000380 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
381 AlignmentSource::Decl);
Richard Smitha509f2f2013-06-14 03:07:01 +0000382
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000383 switch (getEvaluationKind(E->getType())) {
384 default: llvm_unreachable("expected scalar or aggregate expression");
385 case TEK_Scalar:
386 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
387 break;
388 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000389 EmitAggExpr(E, AggValueSlot::forAddr(Object,
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000390 E->getType().getQualifiers(),
391 AggValueSlot::IsDestructed,
392 AggValueSlot::DoesNotNeedGCBarriers,
393 AggValueSlot::IsNotAliased));
394 break;
395 }
396 }
Richard Smith736a9472013-06-12 20:42:33 +0000397
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000398 pushTemporaryCleanup(*this, M, E, Object);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000399 return RefTempDst;
Jordan Roseb1312a52013-04-11 00:58:58 +0000400 }
401
Richard Smithf3fabd22013-06-03 00:17:11 +0000402 SmallVector<const Expr *, 2> CommaLHSs;
Jordan Roseb1312a52013-04-11 00:58:58 +0000403 SmallVector<SubobjectAdjustment, 2> Adjustments;
Richard Smithf3fabd22013-06-03 00:17:11 +0000404 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
405
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000406 for (const auto &Ignored : CommaLHSs)
407 EmitIgnoredExpr(Ignored);
Richard Smithf3fabd22013-06-03 00:17:11 +0000408
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000409 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
Richard Smith736a9472013-06-12 20:42:33 +0000410 if (opaque->getType()->isRecordType()) {
411 assert(Adjustments.empty());
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000412 return EmitOpaqueValueLValue(opaque);
Jordan Roseb1312a52013-04-11 00:58:58 +0000413 }
414 }
415
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000416 // Create and initialize the reference temporary.
John McCall7f416cc2015-09-08 08:05:57 +0000417 Address Object = createReferenceTemporary(*this, M, E);
418 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
419 Object = Address(llvm::ConstantExpr::getBitCast(
420 Var, ConvertTypeForMem(E->getType())->getPointerTo()),
421 Object.getAlignment());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000422 // If the temporary is a global and has a constant initializer or is a
423 // constant temporary that we promoted to a global, we may have already
424 // initialized it.
Richard Smitha509f2f2013-06-14 03:07:01 +0000425 if (!Var->hasInitializer()) {
426 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
427 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
428 }
429 } else {
Tim Shen421119f2016-07-01 21:08:47 +0000430 switch (M->getStorageDuration()) {
431 case SD_Automatic:
432 case SD_FullExpression:
433 if (auto *Size = EmitLifetimeStart(
434 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
435 Object.getPointer())) {
436 if (M->getStorageDuration() == SD_Automatic)
437 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
438 Object, Size);
439 else
440 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
441 Size);
442 }
443 break;
444 default:
445 break;
446 }
Richard Smitha509f2f2013-06-14 03:07:01 +0000447 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
448 }
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000449 pushTemporaryCleanup(*this, M, E, Object);
Jordan Roseb1312a52013-04-11 00:58:58 +0000450
Richard Smith736a9472013-06-12 20:42:33 +0000451 // Perform derived-to-base casts and/or field accesses, to get from the
452 // temporary object we created (and, potentially, for which we extended
453 // the lifetime) to the subobject we're binding the reference to.
454 for (unsigned I = Adjustments.size(); I != 0; --I) {
455 SubobjectAdjustment &Adjustment = Adjustments[I-1];
456 switch (Adjustment.Kind) {
457 case SubobjectAdjustment::DerivedToBaseAdjustment:
458 Object =
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000459 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
460 Adjustment.DerivedToBase.BasePath->path_begin(),
461 Adjustment.DerivedToBase.BasePath->path_end(),
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000462 /*NullCheckValue=*/ false, E->getExprLoc());
Richard Smith736a9472013-06-12 20:42:33 +0000463 break;
Richard Smithf3fabd22013-06-03 00:17:11 +0000464
Richard Smith736a9472013-06-12 20:42:33 +0000465 case SubobjectAdjustment::FieldAdjustment: {
John McCall7f416cc2015-09-08 08:05:57 +0000466 LValue LV = MakeAddrLValue(Object, E->getType(),
467 AlignmentSource::Decl);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000468 LV = EmitLValueForField(LV, Adjustment.Field);
Richard Smith736a9472013-06-12 20:42:33 +0000469 assert(LV.isSimple() &&
470 "materialized temporary field is not a simple lvalue");
471 Object = LV.getAddress();
472 break;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000473 }
474
Richard Smith736a9472013-06-12 20:42:33 +0000475 case SubobjectAdjustment::MemberPointerAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000476 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
John McCall7f416cc2015-09-08 08:05:57 +0000477 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
478 Adjustment.Ptr.MPT);
Richard Smith736a9472013-06-12 20:42:33 +0000479 break;
480 }
481 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000482 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000483
John McCall7f416cc2015-09-08 08:05:57 +0000484 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000485}
486
487RValue
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000488CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
489 // Emit the expression as an lvalue.
490 LValue LV = EmitLValue(E);
491 assert(LV.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000492 llvm::Value *Value = LV.getPointer();
Richard Smith736a9472013-06-12 20:42:33 +0000493
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000494 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000495 // C++11 [dcl.ref]p5 (as amended by core issue 453):
496 // If a glvalue to which a reference is directly bound designates neither
497 // an existing object or function of an appropriate type nor a region of
498 // storage of suitable size and alignment to contain an object of the
499 // reference's type, the behavior is undefined.
500 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000501 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000502 }
John McCall8680f872010-07-21 06:29:51 +0000503
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000504 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000505}
506
507
Mike Stump4a3999f2009-09-09 13:00:44 +0000508/// getAccessedFieldNo - Given an encoded value and a result number, return the
509/// input field number being accessed.
510unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000511 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000512 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
513 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000514}
515
Richard Smith4d3110a2012-10-25 02:14:12 +0000516/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
517static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
518 llvm::Value *High) {
519 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
520 llvm::Value *K47 = Builder.getInt64(47);
521 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
522 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
523 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
524 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
525 return Builder.CreateMul(B1, KMul);
526}
527
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000528bool CodeGenFunction::sanitizePerformTypeCheck() const {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000529 return SanOpts.has(SanitizerKind::Null) |
530 SanOpts.has(SanitizerKind::Alignment) |
531 SanOpts.has(SanitizerKind::ObjectSize) |
532 SanOpts.has(SanitizerKind::Vptr);
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000533}
534
Richard Smithe30752c2012-10-09 19:52:38 +0000535void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +0000536 llvm::Value *Ptr, QualType Ty,
Vedant Kumar18348ea2017-02-17 23:22:55 +0000537 CharUnits Alignment,
538 SanitizerSet SkippedChecks) {
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000539 if (!sanitizePerformTypeCheck())
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000540 return;
541
Richard Smith2d8b2942012-11-01 07:22:08 +0000542 // Don't check pointers outside the default address space. The null check
543 // isn't correct, the object-size check isn't supported by LLVM, and we can't
544 // communicate the addresses to the runtime handler for the vptr check.
John McCall7f416cc2015-09-08 08:05:57 +0000545 if (Ptr->getType()->getPointerAddressSpace())
Richard Smith2d8b2942012-11-01 07:22:08 +0000546 return;
547
Alexey Samsonov24cad992014-07-17 18:46:27 +0000548 SanitizerScope SanScope(this);
549
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000550 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
Craig Topper8a13c412014-05-21 05:09:00 +0000551 llvm::BasicBlock *Done = nullptr;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000552
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000553 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
554 TCK == TCK_UpcastToVirtualBase;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000555 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
Vedant Kumar18348ea2017-02-17 23:22:55 +0000556 !SkippedChecks.has(SanitizerKind::Null)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000557 // The glvalue must not be an empty glvalue.
John McCall7f416cc2015-09-08 08:05:57 +0000558 llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr);
Richard Smith2c5868c2013-02-13 21:18:23 +0000559
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000560 if (AllowNullPointers) {
561 // When performing pointer casts, it's OK if the value is null.
Richard Smith2c5868c2013-02-13 21:18:23 +0000562 // Skip the remaining checks in that case.
563 Done = createBasicBlock("null");
564 llvm::BasicBlock *Rest = createBasicBlock("not.null");
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000565 Builder.CreateCondBr(IsNonNull, Rest, Done);
Richard Smith2c5868c2013-02-13 21:18:23 +0000566 EmitBlock(Rest);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +0000567 } else {
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000568 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
Richard Smith2c5868c2013-02-13 21:18:23 +0000569 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000570 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000571
Vedant Kumar18348ea2017-02-17 23:22:55 +0000572 if (SanOpts.has(SanitizerKind::ObjectSize) &&
573 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
574 !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000575 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000576
Richard Smith69d0d262012-08-24 00:54:33 +0000577 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000578 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000579 // to check this.
Matt Arsenault2f152632013-10-07 19:00:18 +0000580 // FIXME: Get object address space
581 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
582 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smith69d0d262012-08-24 00:54:33 +0000583 llvm::Value *Min = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +0000584 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
Richard Smith69d0d262012-08-24 00:54:33 +0000585 llvm::Value *LargeEnough =
David Blaikie43f9bb72015-05-18 22:14:03 +0000586 Builder.CreateICmpUGE(Builder.CreateCall(F, {CastAddr, Min}),
Richard Smith69d0d262012-08-24 00:54:33 +0000587 llvm::ConstantInt::get(IntPtrTy, Size));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000588 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
Richard Smithe30752c2012-10-09 19:52:38 +0000589 }
Richard Smith69d0d262012-08-24 00:54:33 +0000590
Richard Smithb1b0ab42012-11-05 22:21:05 +0000591 uint64_t AlignVal = 0;
592
Vedant Kumar18348ea2017-02-17 23:22:55 +0000593 if (SanOpts.has(SanitizerKind::Alignment) &&
594 !SkippedChecks.has(SanitizerKind::Alignment)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000595 AlignVal = Alignment.getQuantity();
596 if (!Ty->isIncompleteType() && !AlignVal)
597 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
598
Richard Smith69d0d262012-08-24 00:54:33 +0000599 // The glvalue must be suitably aligned.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000600 if (AlignVal) {
601 llvm::Value *Align =
John McCall7f416cc2015-09-08 08:05:57 +0000602 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
Richard Smithb1b0ab42012-11-05 22:21:05 +0000603 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
604 llvm::Value *Aligned =
605 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000606 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000607 }
Richard Smith69d0d262012-08-24 00:54:33 +0000608 }
609
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000610 if (Checks.size() > 0) {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000611 // Make sure we're not losing information. Alignment needs to be a power of
612 // 2
613 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
Richard Smithe30752c2012-10-09 19:52:38 +0000614 llvm::Constant *StaticData[] = {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000615 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
616 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
617 llvm::ConstantInt::get(Int8Ty, TCK)};
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000618 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData, Ptr);
Richard Smithe30752c2012-10-09 19:52:38 +0000619 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000620
Richard Smithb1b0ab42012-11-05 22:21:05 +0000621 // If possible, check that the vptr indicates that there is a subobject of
622 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000623 //
624 // C++11 [basic.life]p5,6:
625 // [For storage which does not refer to an object within its lifetime]
626 // The program has undefined behavior if:
627 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000628 // or call a non-static member function
Richard Smith4d3110a2012-10-25 02:14:12 +0000629 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000630 if (SanOpts.has(SanitizerKind::Vptr) &&
Vedant Kumar18348ea2017-02-17 23:22:55 +0000631 !SkippedChecks.has(SanitizerKind::Vptr) &&
Richard Smith2c5868c2013-02-13 21:18:23 +0000632 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000633 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
634 TCK == TCK_UpcastToVirtualBase) &&
Richard Smith4d3110a2012-10-25 02:14:12 +0000635 RD && RD->hasDefinition() && RD->isDynamicClass()) {
Richard Smith4d3110a2012-10-25 02:14:12 +0000636 // Compute a hash of the mangled name of the type.
637 //
638 // FIXME: This is not guaranteed to be deterministic! Move to a
639 // fingerprinting mechanism once LLVM provides one. For the time
640 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000641 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000642 llvm::raw_svector_ostream Out(MangledName);
643 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
644 Out);
Richard Smith4d3110a2012-10-25 02:14:12 +0000645
Alexey Samsonov84856012014-07-10 22:34:19 +0000646 // Blacklist based on the mangled type.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000647 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
648 Out.str())) {
Alexey Samsonov84856012014-07-10 22:34:19 +0000649 llvm::hash_code TypeHash = hash_value(Out.str());
Richard Smith4d3110a2012-10-25 02:14:12 +0000650
Alexey Samsonov84856012014-07-10 22:34:19 +0000651 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
652 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
653 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
John McCall7f416cc2015-09-08 08:05:57 +0000654 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000655 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
656 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
Richard Smith4d3110a2012-10-25 02:14:12 +0000657
Alexey Samsonov84856012014-07-10 22:34:19 +0000658 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
659 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
Richard Smith4d3110a2012-10-25 02:14:12 +0000660
Alexey Samsonov84856012014-07-10 22:34:19 +0000661 // Look the hash up in our cache.
662 const int CacheSize = 128;
663 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
664 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
665 "__ubsan_vptr_type_cache");
666 llvm::Value *Slot = Builder.CreateAnd(Hash,
667 llvm::ConstantInt::get(IntPtrTy,
668 CacheSize-1));
669 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
670 llvm::Value *CacheVal =
John McCall7f416cc2015-09-08 08:05:57 +0000671 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
672 getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000673
674 // If the hash isn't in the cache, call a runtime handler to perform the
675 // hard work of checking whether the vptr is for an object of the right
676 // type. This will either fill in the cache and return, or produce a
677 // diagnostic.
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000678 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
Alexey Samsonov84856012014-07-10 22:34:19 +0000679 llvm::Constant *StaticData[] = {
680 EmitCheckSourceLocation(Loc),
681 EmitCheckTypeDescriptor(Ty),
682 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
683 llvm::ConstantInt::get(Int8Ty, TCK)
684 };
John McCall7f416cc2015-09-08 08:05:57 +0000685 llvm::Value *DynamicData[] = { Ptr, Hash };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000686 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000687 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
688 DynamicData);
Alexey Samsonov84856012014-07-10 22:34:19 +0000689 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000690 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000691
692 if (Done) {
693 Builder.CreateBr(Done);
694 EmitBlock(Done);
695 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000696}
Chris Lattner4647a212007-08-31 22:49:20 +0000697
Richard Smith539e4a72013-02-23 02:53:19 +0000698/// Determine whether this expression refers to a flexible array member in a
699/// struct. We disable array bounds checks for such members.
700static bool isFlexibleArrayMemberExpr(const Expr *E) {
701 // For compatibility with existing code, we treat arrays of length 0 or
702 // 1 as flexible array members.
703 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000704 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000705 if (CAT->getSize().ugt(1))
706 return false;
707 } else if (!isa<IncompleteArrayType>(AT))
708 return false;
709
710 E = E->IgnoreParens();
711
712 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000713 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000714 // FIXME: If the base type of the member expr is not FD->getParent(),
715 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000716 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith539e4a72013-02-23 02:53:19 +0000717 RecordDecl::field_iterator FI(
718 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
719 return ++FI == FD->getParent()->field_end();
720 }
Vedant Kumare356f1a2016-10-04 20:36:04 +0000721 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
722 return IRE->getDecl()->getNextIvar() == nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000723 }
724
725 return false;
726}
727
728/// If Base is known to point to the start of an array, return the length of
729/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000730static llvm::Value *getArrayIndexingBound(
731 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000732 // For the vector indexing extension, the bound is the number of elements.
733 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
734 IndexedType = Base->getType();
735 return CGF.Builder.getInt32(VT->getNumElements());
736 }
737
738 Base = Base->IgnoreParens();
739
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000740 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000741 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
742 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
743 IndexedType = CE->getSubExpr()->getType();
744 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000745 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000746 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000747 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000748 return CGF.getVLASize(VAT).first;
749 }
750 }
751
Craig Topper8a13c412014-05-21 05:09:00 +0000752 return nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000753}
754
755void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
756 llvm::Value *Index, QualType IndexType,
757 bool Accessed) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000758 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
Richard Smith6b53e222013-10-22 22:51:04 +0000759 "should not be called unless adding bounds checks");
Alexey Samsonov24cad992014-07-17 18:46:27 +0000760 SanitizerScope SanScope(this);
Richard Smith2847b222013-02-24 01:56:24 +0000761
Richard Smith539e4a72013-02-23 02:53:19 +0000762 QualType IndexedType;
763 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
764 if (!Bound)
765 return;
766
767 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
768 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
769 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
770
771 llvm::Constant *StaticData[] = {
772 EmitCheckSourceLocation(E->getExprLoc()),
773 EmitCheckTypeDescriptor(IndexedType),
774 EmitCheckTypeDescriptor(IndexType)
775 };
776 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
777 : Builder.CreateICmpULE(IndexVal, BoundVal);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000778 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
779 SanitizerHandler::OutOfBounds, StaticData, Index);
Richard Smith539e4a72013-02-23 02:53:19 +0000780}
781
Chris Lattner116ce8f2010-01-09 21:40:03 +0000782
Chris Lattner116ce8f2010-01-09 21:40:03 +0000783CodeGenFunction::ComplexPairTy CodeGenFunction::
784EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
785 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000786 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +0000787
Chris Lattner116ce8f2010-01-09 21:40:03 +0000788 llvm::Value *NextVal;
789 if (isa<llvm::IntegerType>(InVal.first->getType())) {
790 uint64_t AmountVal = isInc ? 1 : -1;
791 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +0000792
Chris Lattner116ce8f2010-01-09 21:40:03 +0000793 // Add the inc/dec to the real part.
794 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
795 } else {
796 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
797 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
798 if (!isInc)
799 FVal.changeSign();
800 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
Craig Topper99e79272013-07-26 05:59:26 +0000801
Chris Lattner116ce8f2010-01-09 21:40:03 +0000802 // Add the inc/dec to the real part.
803 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
804 }
Craig Topper99e79272013-07-26 05:59:26 +0000805
Chris Lattner116ce8f2010-01-09 21:40:03 +0000806 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +0000807
Chris Lattner116ce8f2010-01-09 21:40:03 +0000808 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +0000809 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Craig Topper99e79272013-07-26 05:59:26 +0000810
Chris Lattner116ce8f2010-01-09 21:40:03 +0000811 // If this is a postinc, return the value read from memory, otherwise use the
812 // updated value.
813 return isPre ? IncVal : InVal;
814}
815
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000816void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
817 CodeGenFunction *CGF) {
818 // Bind VLAs in the cast type.
819 if (CGF && E->getType()->isVariablyModifiedType())
820 CGF->EmitVariablyModifiedType(E->getType());
821
822 if (CGDebugInfo *DI = getModuleDebugInfo())
823 DI->EmitExplicitCastType(E->getType());
824}
825
Chris Lattnera45c5af2007-06-02 19:47:04 +0000826//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000827// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000828//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000829
John McCall7f416cc2015-09-08 08:05:57 +0000830/// EmitPointerWithAlignment - Given an expression of pointer type, try to
831/// derive a more accurate bound on the alignment of the pointer.
832Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
833 AlignmentSource *Source) {
834 // We allow this with ObjC object pointers because of fragile ABIs.
835 assert(E->getType()->isPointerType() ||
836 E->getType()->isObjCObjectPointerType());
837 E = E->IgnoreParens();
838
839 // Casts:
840 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000841 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
842 CGM.EmitExplicitCastExprType(ECE, this);
John McCall7f416cc2015-09-08 08:05:57 +0000843
844 switch (CE->getCastKind()) {
845 // Non-converting casts (but not C's implicit conversion from void*).
846 case CK_BitCast:
847 case CK_NoOp:
848 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
849 if (PtrTy->getPointeeType()->isVoidType())
850 break;
851
852 AlignmentSource InnerSource;
853 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerSource);
854 if (Source) *Source = InnerSource;
855
856 // If this is an explicit bitcast, and the source l-value is
857 // opaque, honor the alignment of the casted-to type.
858 if (isa<ExplicitCastExpr>(CE) &&
John McCall7f416cc2015-09-08 08:05:57 +0000859 InnerSource != AlignmentSource::Decl) {
860 Addr = Address(Addr.getPointer(),
861 getNaturalPointeeTypeAlignment(E->getType(), Source));
862 }
863
Peter Collingbourne574975e2016-01-14 02:49:48 +0000864 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
865 CE->getCastKind() == CK_BitCast) {
Peter Collingbourneee381ff2015-09-09 00:01:31 +0000866 if (auto PT = E->getType()->getAs<PointerType>())
867 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
868 /*MayBeNull=*/true,
869 CodeGenFunction::CFITCK_UnrelatedCast,
870 CE->getLocStart());
871 }
872
John McCall7f416cc2015-09-08 08:05:57 +0000873 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
874 }
875 break;
876
877 // Array-to-pointer decay.
878 case CK_ArrayToPointerDecay:
879 return EmitArrayToPointerDecay(CE->getSubExpr(), Source);
880
881 // Derived-to-base conversions.
882 case CK_UncheckedDerivedToBase:
883 case CK_DerivedToBase: {
884 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), Source);
885 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
886 return GetAddressOfBaseClass(Addr, Derived,
887 CE->path_begin(), CE->path_end(),
888 ShouldNullCheckClassCastValue(CE),
889 CE->getExprLoc());
890 }
891
892 // TODO: Is there any reason to treat base-to-derived conversions
893 // specially?
894 default:
895 break;
896 }
897 }
898
899 // Unary &.
900 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
901 if (UO->getOpcode() == UO_AddrOf) {
902 LValue LV = EmitLValue(UO->getSubExpr());
903 if (Source) *Source = LV.getAlignmentSource();
904 return LV.getAddress();
905 }
906 }
907
908 // TODO: conditional operators, comma.
909
910 // Otherwise, use the alignment of the type.
911 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), Source);
912 return Address(EmitScalarExpr(E), Align);
913}
914
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000915RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000916 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +0000917 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +0000918
919 switch (getEvaluationKind(Ty)) {
920 case TEK_Complex: {
921 llvm::Type *EltTy =
922 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +0000923 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000924 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000925 }
Craig Topper99e79272013-07-26 05:59:26 +0000926
Chris Lattner65526f02010-08-23 05:26:13 +0000927 // If this is a use of an undefined aggregate type, the aggregate must have an
928 // identifiable address. Just because the contents of the value are undefined
929 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +0000930 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000931 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +0000932 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000933 }
John McCall47fb9502013-03-07 21:37:08 +0000934
935 case TEK_Scalar:
936 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
937 }
938 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +0000939}
940
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000941RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
942 const char *Name) {
943 ErrorUnsupported(E, Name);
944 return GetUndefRValue(E->getType());
945}
946
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000947LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
948 const char *Name) {
949 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000950 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +0000951 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
952 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000953}
954
Vedant Kumare550d112017-02-23 01:22:38 +0000955bool CodeGenFunction::IsDeclRefOrWrappedCXXThis(const Expr *Obj) {
Vedant Kumar34b1fd62017-02-17 23:22:59 +0000956 if (isa<DeclRefExpr>(Obj))
957 return true;
958
959 const Expr *Base = Obj;
960 while (!isa<CXXThisExpr>(Base)) {
961 // The result of a dynamic_cast can be null.
962 if (isa<CXXDynamicCastExpr>(Base))
963 return false;
964
965 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
966 Base = CE->getSubExpr();
967 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
968 Base = PE->getSubExpr();
969 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
970 if (UO->getOpcode() == UO_Extension)
971 Base = UO->getSubExpr();
972 else
973 return false;
974 } else {
975 return false;
976 }
977 }
978 return true;
979}
980
Richard Smith4d1458e2012-09-08 02:08:36 +0000981LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +0000982 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000983 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +0000984 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
985 else
986 LV = EmitLValue(E);
Vedant Kumar34b1fd62017-02-17 23:22:59 +0000987 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
988 SanitizerSet SkippedChecks;
989 if (const auto *ME = dyn_cast<MemberExpr>(E))
Vedant Kumare550d112017-02-23 01:22:38 +0000990 if (IsDeclRefOrWrappedCXXThis(ME->getBase()))
Vedant Kumar34b1fd62017-02-17 23:22:59 +0000991 SkippedChecks.set(SanitizerKind::Null, true);
John McCall7f416cc2015-09-08 08:05:57 +0000992 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
Vedant Kumar34b1fd62017-02-17 23:22:59 +0000993 E->getType(), LV.getAlignment(), SkippedChecks);
994 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000995 return LV;
996}
997
Chris Lattner8394d792007-06-05 20:53:16 +0000998/// EmitLValue - Emit code to compute a designator that specifies the location
999/// of the expression.
1000///
Mike Stump4a3999f2009-09-09 13:00:44 +00001001/// This can return one of two things: a simple address or a bitfield reference.
1002/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1003/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +00001004///
Mike Stump4a3999f2009-09-09 13:00:44 +00001005/// If this returns a bitfield reference, nothing about the pointee type of the
1006/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +00001007///
Mike Stump4a3999f2009-09-09 13:00:44 +00001008/// If this returns a normal address, and if the lvalue's C type is fixed size,
1009/// this method guarantees that the returned pointer type will point to an LLVM
1010/// type of the same size of the lvalue's type. If the lvalue has a variable
1011/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +00001012///
Chris Lattnerd7f58862007-06-02 05:24:33 +00001013LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +00001014 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +00001015 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001016 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +00001017
John McCallc109a252011-11-07 03:59:57 +00001018 case Expr::ObjCPropertyRefExprClass:
1019 llvm_unreachable("cannot emit a property reference directly");
1020
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00001021 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +00001022 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00001023 case Expr::ObjCIsaExprClass:
1024 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001025 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00001026 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001027 case Expr::CompoundAssignOperatorClass: {
1028 QualType Ty = E->getType();
1029 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1030 Ty = AT->getValueType();
1031 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +00001032 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1033 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001034 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001035 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +00001036 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001037 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001038 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001039 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00001040 case Expr::VAArgExprClass:
1041 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001042 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001043 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +00001044 case Expr::ParenExprClass:
1045 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +00001046 case Expr::GenericSelectionExprClass:
1047 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +00001048 case Expr::PredefinedExprClass:
1049 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +00001050 case Expr::StringLiteralClass:
1051 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001052 case Expr::ObjCEncodeExprClass:
1053 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +00001054 case Expr::PseudoObjectExprClass:
1055 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001056 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +00001057 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +00001058 case Expr::CXXTemporaryObjectExprClass:
1059 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001060 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1061 case Expr::CXXBindTemporaryExprClass:
1062 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +00001063 case Expr::CXXUuidofExprClass:
1064 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +00001065 case Expr::LambdaExprClass:
1066 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +00001067
1068 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001069 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +00001070 enterFullExpression(cleanups);
1071 RunCleanupsScope Scope(*this);
Reid Kleckner092d0652017-03-06 22:18:34 +00001072 LValue LV = EmitLValue(cleanups->getSubExpr());
1073 if (LV.isSimple()) {
1074 // Defend against branches out of gnu statement expressions surrounded by
1075 // cleanups.
1076 llvm::Value *V = LV.getPointer();
1077 Scope.ForceCleanup({&V});
1078 return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
1079 getContext(), LV.getAlignmentSource(),
1080 LV.getTBAAInfo());
1081 }
1082 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1083 // bitfield lvalue or some other non-simple lvalue?
1084 return LV;
John McCall08ef4662011-11-10 08:15:53 +00001085 }
1086
Anders Carlsson52ce3bb2009-11-14 01:51:50 +00001087 case Expr::CXXDefaultArgExprClass:
1088 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001089 case Expr::CXXDefaultInitExprClass: {
1090 CXXDefaultInitExprScope Scope(*this);
1091 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1092 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001093 case Expr::CXXTypeidExprClass:
1094 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001095
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001096 case Expr::ObjCMessageExprClass:
1097 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001098 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001099 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001100 case Expr::StmtExprClass:
1101 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001102 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001103 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001104 case Expr::ArraySubscriptExprClass:
1105 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001106 case Expr::OMPArraySectionExprClass:
1107 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001108 case Expr::ExtVectorElementExprClass:
1109 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001110 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001111 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001112 case Expr::CompoundLiteralExprClass:
1113 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001114 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001115 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001116 case Expr::BinaryConditionalOperatorClass:
1117 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001118 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001119 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001120 case Expr::OpaqueValueExprClass:
1121 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001122 case Expr::SubstNonTypeTemplateParmExprClass:
1123 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001124 case Expr::ImplicitCastExprClass:
1125 case Expr::CStyleCastExprClass:
1126 case Expr::CXXFunctionalCastExprClass:
1127 case Expr::CXXStaticCastExprClass:
1128 case Expr::CXXDynamicCastExprClass:
1129 case Expr::CXXReinterpretCastExprClass:
1130 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001131 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001132 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001133
Douglas Gregorfe314812011-06-21 17:03:29 +00001134 case Expr::MaterializeTemporaryExprClass:
1135 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001136 }
1137}
1138
John McCall71335052012-03-10 03:05:10 +00001139/// Given an object of the given canonical type, can we safely copy a
1140/// value out of it based on its initializer?
1141static bool isConstantEmittableObjectType(QualType type) {
1142 assert(type.isCanonical());
1143 assert(!type->isReferenceType());
1144
1145 // Must be const-qualified but non-volatile.
1146 Qualifiers qs = type.getLocalQualifiers();
1147 if (!qs.hasConst() || qs.hasVolatile()) return false;
1148
1149 // Otherwise, all object types satisfy this except C++ classes with
1150 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001151 if (const auto *RT = dyn_cast<RecordType>(type))
1152 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001153 if (RD->hasMutableFields() || !RD->isTrivial())
1154 return false;
1155
1156 return true;
1157}
1158
1159/// Can we constant-emit a load of a reference to a variable of the
1160/// given type? This is different from predicates like
1161/// Decl::isUsableInConstantExpressions because we do want it to apply
1162/// in situations that don't necessarily satisfy the language's rules
1163/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1164/// to do this with const float variables even if those variables
1165/// aren't marked 'constexpr'.
1166enum ConstantEmissionKind {
1167 CEK_None,
1168 CEK_AsReferenceOnly,
1169 CEK_AsValueOrReference,
1170 CEK_AsValueOnly
1171};
1172static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1173 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001174 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001175 if (isConstantEmittableObjectType(ref->getPointeeType()))
1176 return CEK_AsValueOrReference;
1177 return CEK_AsReferenceOnly;
1178 }
1179 if (isConstantEmittableObjectType(type))
1180 return CEK_AsValueOnly;
1181 return CEK_None;
1182}
1183
1184/// Try to emit a reference to the given value without producing it as
1185/// an l-value. This is actually more than an optimization: we can't
1186/// produce an l-value for variables that we never actually captured
1187/// in a block or lambda, which means const int variables or constexpr
1188/// literals or similar.
1189CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001190CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1191 ValueDecl *value = refExpr->getDecl();
1192
John McCall71335052012-03-10 03:05:10 +00001193 // The value needs to be an enum constant or a constant variable.
1194 ConstantEmissionKind CEK;
1195 if (isa<ParmVarDecl>(value)) {
1196 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001197 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001198 CEK = checkVarTypeForConstantEmission(var->getType());
1199 } else if (isa<EnumConstantDecl>(value)) {
1200 CEK = CEK_AsValueOnly;
1201 } else {
1202 CEK = CEK_None;
1203 }
1204 if (CEK == CEK_None) return ConstantEmission();
1205
John McCall71335052012-03-10 03:05:10 +00001206 Expr::EvalResult result;
1207 bool resultIsReference;
1208 QualType resultType;
1209
1210 // It's best to evaluate all the way as an r-value if that's permitted.
1211 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001212 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001213 resultIsReference = false;
1214 resultType = refExpr->getType();
1215
1216 // Otherwise, try to evaluate as an l-value.
1217 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001218 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001219 resultIsReference = true;
1220 resultType = value->getType();
1221
1222 // Failure.
1223 } else {
1224 return ConstantEmission();
1225 }
1226
1227 // In any case, if the initializer has side-effects, abandon ship.
1228 if (result.HasSideEffects)
1229 return ConstantEmission();
1230
1231 // Emit as a constant.
1232 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1233
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001234 // Make sure we emit a debug reference to the global variable.
1235 // This should probably fire even for
1236 if (isa<VarDecl>(value)) {
1237 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001238 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001239 } else {
1240 assert(isa<EnumConstantDecl>(value));
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001241 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001242 }
John McCall71335052012-03-10 03:05:10 +00001243
1244 // If we emitted a reference constant, we need to dereference that.
1245 if (resultIsReference)
1246 return ConstantEmission::forReference(C);
1247
1248 return ConstantEmission::forValue(C);
1249}
1250
Nick Lewycky2d84e842013-10-02 02:29:49 +00001251llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1252 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +00001253 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001254 lvalue.getType(), Loc, lvalue.getAlignmentSource(),
1255 lvalue.getTBAAInfo(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001256 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1257 lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001258}
1259
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001260static bool hasBooleanRepresentation(QualType Ty) {
1261 if (Ty->isBooleanType())
1262 return true;
1263
1264 if (const EnumType *ET = Ty->getAs<EnumType>())
1265 return ET->getDecl()->getIntegerType()->isBooleanType();
1266
Douglas Gregor298f43d2012-04-12 20:42:30 +00001267 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1268 return hasBooleanRepresentation(AT->getValueType());
1269
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001270 return false;
1271}
1272
Richard Smith1629da92012-12-13 07:11:50 +00001273static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1274 llvm::APInt &Min, llvm::APInt &End,
Vedant Kumar4593a462016-12-09 23:48:18 +00001275 bool StrictEnums, bool IsBool) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001276 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001277 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1278 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001279 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001280 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001281
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001282 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001283 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1284 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001285 } else {
1286 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001287 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001288 unsigned Bitwidth = LTy->getScalarSizeInBits();
1289 unsigned NumNegativeBits = ED->getNumNegativeBits();
1290 unsigned NumPositiveBits = ED->getNumPositiveBits();
1291
1292 if (NumNegativeBits) {
1293 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1294 assert(NumBits <= Bitwidth);
1295 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1296 Min = -End;
1297 } else {
1298 assert(NumPositiveBits <= Bitwidth);
1299 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1300 Min = llvm::APInt(Bitwidth, 0);
1301 }
1302 }
Richard Smith1629da92012-12-13 07:11:50 +00001303 return true;
1304}
1305
1306llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1307 llvm::APInt Min, End;
Vedant Kumar4593a462016-12-09 23:48:18 +00001308 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1309 hasBooleanRepresentation(Ty)))
Craig Topper8a13c412014-05-21 05:09:00 +00001310 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001311
Duncan Sandsc720e782012-04-15 18:04:54 +00001312 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001313 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001314}
1315
Vedant Kumar5a972652017-02-27 19:46:19 +00001316bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1317 SourceLocation Loc) {
1318 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1319 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1320 if (!HasBoolCheck && !HasEnumCheck)
1321 return false;
1322
1323 bool IsBool = hasBooleanRepresentation(Ty) ||
1324 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1325 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1326 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1327 if (!NeedsBoolCheck && !NeedsEnumCheck)
1328 return false;
1329
Vedant Kumar129edab2017-03-09 16:06:27 +00001330 // Single-bit booleans don't need to be checked. Special-case this to avoid
1331 // a bit width mismatch when handling bitfield values. This is handled by
1332 // EmitFromMemory for the non-bitfield case.
1333 if (IsBool &&
1334 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1335 return false;
1336
Vedant Kumar5a972652017-02-27 19:46:19 +00001337 llvm::APInt Min, End;
1338 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1339 return true;
1340
1341 SanitizerScope SanScope(this);
1342 llvm::Value *Check;
1343 --End;
1344 if (!Min) {
1345 Check = Builder.CreateICmpULE(
1346 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1347 } else {
1348 llvm::Value *Upper = Builder.CreateICmpSLE(
1349 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1350 llvm::Value *Lower = Builder.CreateICmpSGE(
1351 Value, llvm::ConstantInt::get(getLLVMContext(), Min));
1352 Check = Builder.CreateAnd(Upper, Lower);
1353 }
1354 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1355 EmitCheckTypeDescriptor(Ty)};
1356 SanitizerMask Kind =
1357 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1358 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1359 StaticArgs, EmitCheckValue(Value));
1360 return true;
1361}
1362
John McCall7f416cc2015-09-08 08:05:57 +00001363llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1364 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001365 SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +00001366 AlignmentSource AlignSource,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001367 llvm::MDNode *TBAAInfo,
1368 QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001369 uint64_t TBAAOffset,
1370 bool isNontemporal) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001371 // For better performance, handle vector loads differently.
1372 if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001373 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001374
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001375 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001376
John McCall7f416cc2015-09-08 08:05:57 +00001377 // Handle vectors of size 3 like size 4 for better performance.
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001378 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001379
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001380 // Bitcast to vec4 type.
1381 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
1382 4);
John McCall7f416cc2015-09-08 08:05:57 +00001383 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001384 // Now load value.
John McCall7f416cc2015-09-08 08:05:57 +00001385 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001386
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001387 // Shuffle vector to get vec3.
John McCall7f416cc2015-09-08 08:05:57 +00001388 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
Benjamin Kramer99383102015-07-28 16:25:32 +00001389 {0, 1, 2}, "extractVec");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001390 return EmitFromMemory(V, Ty);
1391 }
1392 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001393
1394 // Atomic operations have to be done on integral types.
David Majnemera38c9f12016-05-24 16:09:25 +00001395 LValue AtomicLValue =
John McCall7f416cc2015-09-08 08:05:57 +00001396 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
David Majnemera38c9f12016-05-24 16:09:25 +00001397 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1398 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001399 }
Craig Topper99e79272013-07-26 05:59:26 +00001400
John McCall7f416cc2015-09-08 08:05:57 +00001401 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001402 if (isNontemporal) {
1403 llvm::MDNode *Node = llvm::MDNode::get(
1404 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1405 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1406 }
Manman Renc451e572013-04-04 21:53:22 +00001407 if (TBAAInfo) {
1408 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1409 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001410 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001411 CGM.DecorateInstructionWithTBAA(Load, TBAAPath,
1412 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001413 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001414
Vedant Kumar5a972652017-02-27 19:46:19 +00001415 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1416 // In order to prevent the optimizer from throwing away the check, don't
1417 // attach range metadata to the load.
Richard Smith1629da92012-12-13 07:11:50 +00001418 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001419 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1420 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001421
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001422 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001423}
1424
John McCall3a7f6922010-10-27 20:58:56 +00001425llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1426 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001427 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001428 // This should really always be an i1, but sometimes it's already
1429 // an i8, and it's awkward to track those cases down.
1430 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001431 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1432 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1433 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001434 }
1435
1436 return Value;
1437}
1438
1439llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1440 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001441 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001442 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1443 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001444 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1445 }
1446
1447 return Value;
1448}
1449
John McCall7f416cc2015-09-08 08:05:57 +00001450void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1451 bool Volatile, QualType Ty,
1452 AlignmentSource AlignSource,
1453 llvm::MDNode *TBAAInfo,
Manman Renc451e572013-04-04 21:53:22 +00001454 bool isInit, QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001455 uint64_t TBAAOffset,
1456 bool isNontemporal) {
Craig Topper99e79272013-07-26 05:59:26 +00001457
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001458 // Handle vectors differently to get better performance.
1459 if (Ty->isVectorType()) {
1460 llvm::Type *SrcTy = Value->getType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001461 auto *VecTy = cast<llvm::VectorType>(SrcTy);
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001462 // Handle vec3 special.
1463 if (VecTy->getNumElements() == 3) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001464 // Our source is a vec3, do a shuffle vector to make it a vec4.
Benjamin Kramer99383102015-07-28 16:25:32 +00001465 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1466 Builder.getInt32(2),
1467 llvm::UndefValue::get(Builder.getInt32Ty())};
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001468 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1469 Value = Builder.CreateShuffleVector(Value,
1470 llvm::UndefValue::get(VecTy),
1471 MaskV, "extractVec");
1472 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1473 }
John McCall7f416cc2015-09-08 08:05:57 +00001474 if (Addr.getElementType() != SrcTy) {
1475 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001476 }
1477 }
Craig Topper99e79272013-07-26 05:59:26 +00001478
John McCall3a7f6922010-10-27 20:58:56 +00001479 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001480
David Majnemera38c9f12016-05-24 16:09:25 +00001481 LValue AtomicLValue =
1482 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
David Majnemera5b195a2015-02-14 01:35:12 +00001483 if (Ty->isAtomicType() ||
David Majnemera38c9f12016-05-24 16:09:25 +00001484 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1485 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
John McCalla8ec7eb2013-03-07 21:37:17 +00001486 return;
1487 }
1488
Daniel Dunbar03816342010-08-21 02:24:36 +00001489 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001490 if (isNontemporal) {
1491 llvm::MDNode *Node =
1492 llvm::MDNode::get(Store->getContext(),
1493 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1494 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1495 }
Manman Renc451e572013-04-04 21:53:22 +00001496 if (TBAAInfo) {
1497 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1498 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001499 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001500 CGM.DecorateInstructionWithTBAA(Store, TBAAPath,
1501 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001502 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001503}
1504
David Chisnallfa35df62012-01-16 17:27:18 +00001505void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001506 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001507 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001508 lvalue.getType(), lvalue.getAlignmentSource(),
Manman Renc451e572013-04-04 21:53:22 +00001509 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001510 lvalue.getTBAAOffset(), lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001511}
1512
Mike Stump4a3999f2009-09-09 13:00:44 +00001513/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1514/// method emits the address of the lvalue, then loads the result as an rvalue,
1515/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001516RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001517 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001518 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001519 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001520 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1521 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001522 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001523 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001524 // In MRC mode, we do a load+autorelease.
1525 if (!getLangOpts().ObjCAutoRefCount) {
1526 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1527 }
1528
1529 // In ARC mode, we load retained and then consume the value.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001530 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1531 Object = EmitObjCConsumeObject(LV.getType(), Object);
1532 return RValue::get(Object);
1533 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001534
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001535 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001536 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001537
John McCalla1dee5302010-08-22 10:59:02 +00001538 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001539 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001540 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001541
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001542 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001543 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001544 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001545 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001546 "vecext"));
1547 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001548
1549 // If this is a reference to a subset of the elements of a vector, either
1550 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001551 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001552 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001553
Renato Golin230c5eb2014-05-19 18:15:42 +00001554 // Global Register variables always invoke intrinsics
1555 if (LV.isGlobalReg())
1556 return EmitLoadOfGlobalRegLValue(LV);
1557
John McCallc109a252011-11-07 03:59:57 +00001558 assert(LV.isBitField() && "Unknown LValue type!");
Vedant Kumar129edab2017-03-09 16:06:27 +00001559 return EmitLoadOfBitfieldLValue(LV, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +00001560}
1561
Vedant Kumar129edab2017-03-09 16:06:27 +00001562RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1563 SourceLocation Loc) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001564 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001565
Daniel Dunbar3447a022010-04-13 23:34:15 +00001566 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001567 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001568
John McCall7f416cc2015-09-08 08:05:57 +00001569 Address Ptr = LV.getBitFieldAddress();
1570 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001571
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001572 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001573 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001574 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1575 if (HighBits)
1576 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1577 if (Info.Offset + HighBits)
1578 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1579 } else {
1580 if (Info.Offset)
1581 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001582 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001583 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1584 Info.Size),
1585 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001586 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001587 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Vedant Kumar129edab2017-03-09 16:06:27 +00001588 EmitScalarRangeCheck(Val, LV.getType(), Loc);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001589 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001590}
1591
Nate Begemanb699c9b2009-01-18 06:42:49 +00001592// If this is a reference to a subset of the elements of a vector, create an
1593// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001594RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001595 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1596 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001597
Nate Begemanf322eab2008-05-09 06:41:27 +00001598 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001599
1600 // If the result of the expression is a non-vector type, we must be extracting
1601 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001602 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001603 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001604 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001605 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001606 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001607 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001608
1609 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001610 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001611
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001612 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001613 for (unsigned i = 0; i != NumResultElts; ++i)
1614 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001615
Chris Lattner91c08ad2011-02-15 00:14:06 +00001616 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1617 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001618 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001619 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001620}
1621
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001622/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001623Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1624 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001625 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1626 QualType EQT = ExprVT->getElementType();
1627 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001628
John McCall7f416cc2015-09-08 08:05:57 +00001629 Address CastToPointerElement =
1630 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1631 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001632
1633 const llvm::Constant *Elts = LV.getExtVectorElts();
1634 unsigned ix = getAccessedFieldNo(0, Elts);
1635
John McCall7f416cc2015-09-08 08:05:57 +00001636 Address VectorBasePtrPlusIx =
1637 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1638 getContext().getTypeSizeInChars(EQT),
1639 "vector.elt");
1640
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001641 return VectorBasePtrPlusIx;
1642}
1643
Renato Golin230c5eb2014-05-19 18:15:42 +00001644/// @brief Load of global gamed gegisters are always calls to intrinsics.
1645RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001646 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1647 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001648 llvm::MDNode *RegName = cast<llvm::MDNode>(
1649 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001650
1651 // We accept integer and pointer types only
1652 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1653 llvm::Type *Ty = OrigTy;
1654 if (OrigTy->isPointerTy())
1655 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1656 llvm::Type *Types[] = { Ty };
1657
Renato Golin230c5eb2014-05-19 18:15:42 +00001658 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001659 llvm::Value *Call = Builder.CreateCall(
1660 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001661 if (OrigTy->isPointerTy())
1662 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001663 return RValue::get(Call);
1664}
Chris Lattner40ff7012007-08-03 16:18:34 +00001665
Chris Lattner9369a562007-06-29 16:31:29 +00001666
Chris Lattner8394d792007-06-05 20:53:16 +00001667/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1668/// lvalue, where both are guaranteed to the have the same type, and that type
1669/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001670void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001671 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001672 if (!Dst.isSimple()) {
1673 if (Dst.isVectorElt()) {
1674 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001675 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1676 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001677 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001678 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001679 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1680 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001681 return;
1682 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001683
Nate Begemance4d7fc2008-04-18 23:10:10 +00001684 // If this is an update of extended vector elements, insert them as
1685 // appropriate.
1686 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001687 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001688
Renato Golin230c5eb2014-05-19 18:15:42 +00001689 if (Dst.isGlobalReg())
1690 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1691
John McCallc109a252011-11-07 03:59:57 +00001692 assert(Dst.isBitField() && "Unknown LValue type");
1693 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001694 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001695
John McCall31168b02011-06-15 23:02:42 +00001696 // There's special magic for assigning into an ARC-qualified l-value.
1697 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1698 switch (Lifetime) {
1699 case Qualifiers::OCL_None:
1700 llvm_unreachable("present but none");
1701
1702 case Qualifiers::OCL_ExplicitNone:
1703 // nothing special
1704 break;
1705
1706 case Qualifiers::OCL_Strong:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001707 if (isInit) {
1708 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1709 break;
1710 }
John McCall55e1fbc2011-06-25 02:11:03 +00001711 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001712 return;
1713
1714 case Qualifiers::OCL_Weak:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001715 if (isInit)
1716 // Initialize and then skip the primitive store.
1717 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1718 else
1719 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001720 return;
1721
1722 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001723 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1724 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001725 // fall into the normal path
1726 break;
1727 }
1728 }
1729
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001730 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001731 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001732 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001733 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001734 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001735 return;
1736 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001737
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001738 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001739 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001740 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001741 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001742 if (Dst.isObjCIvar()) {
1743 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001744 llvm::Type *ResultType = IntPtrTy;
1745 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1746 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001747 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001748 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001749 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1750 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001751 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001752 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001753 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001754 } else if (Dst.isGlobalObjCRef()) {
1755 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1756 Dst.isThreadLocalRef());
1757 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001758 else
1759 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001760 return;
1761 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001762
Chris Lattner6278e6a2007-08-11 00:04:45 +00001763 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001764 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001765}
1766
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001767void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001768 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001769 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001770 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001771 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001772
Daniel Dunbar67aba792010-04-15 03:47:33 +00001773 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001774 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001775
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001776 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001777 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001778 /*IsSigned=*/false);
1779 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001780
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001781 // See if there are other bits in the bitfield's storage we'll need to load
1782 // and mask together with source before storing.
1783 if (Info.StorageSize != Info.Size) {
1784 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001785 llvm::Value *Val =
1786 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001787
1788 // Mask the source value as needed.
1789 if (!hasBooleanRepresentation(Dst.getType()))
1790 SrcVal = Builder.CreateAnd(SrcVal,
1791 llvm::APInt::getLowBitsSet(Info.StorageSize,
1792 Info.Size),
1793 "bf.value");
1794 MaskedVal = SrcVal;
1795 if (Info.Offset)
1796 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1797
1798 // Mask out the original value.
1799 Val = Builder.CreateAnd(Val,
1800 ~llvm::APInt::getBitsSet(Info.StorageSize,
1801 Info.Offset,
1802 Info.Offset + Info.Size),
1803 "bf.clear");
1804
1805 // Or together the unchanged values and the source value.
1806 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1807 } else {
1808 assert(Info.Offset == 0);
1809 }
1810
1811 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001812 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001813
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001814 // Return the new value of the bit-field, if requested.
1815 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001816 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001817
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001818 // Sign extend the value if needed.
1819 if (Info.IsSigned) {
1820 assert(Info.Size <= Info.StorageSize);
1821 unsigned HighBits = Info.StorageSize - Info.Size;
1822 if (HighBits) {
1823 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1824 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1825 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001826 }
1827
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001828 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1829 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001830 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001831 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001832}
1833
Nate Begemance4d7fc2008-04-18 23:10:10 +00001834void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001835 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001836 // This access turns into a read/modify/write of the vector. Load the input
1837 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001838 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1839 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001840 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001841
Chris Lattner4647a212007-08-31 22:49:20 +00001842 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001843
John McCall55e1fbc2011-06-25 02:11:03 +00001844 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001845 unsigned NumSrcElts = VTy->getNumElements();
Craig Topperf2f1a092016-07-08 02:17:35 +00001846 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001847 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001848 // Use shuffle vector is the src and destination are the same number of
1849 // elements and restore the vector mask since it is on the side it will be
1850 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001851 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001852 for (unsigned i = 0; i != NumSrcElts; ++i)
1853 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001854
Chris Lattner91c08ad2011-02-15 00:14:06 +00001855 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001856 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001857 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001858 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001859 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001860 // Extended the source vector to the same length and then shuffle it
1861 // into the destination.
1862 // FIXME: since we're shuffling with undef, can we just use the indices
1863 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001864 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001865 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001866 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001867 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001868 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001869 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001870 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001871 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001872 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001873 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001874 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001875 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001876 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001877
Joey Goulycf4143b2013-11-21 17:09:05 +00001878 // When the vector size is odd and .odd or .hi is used, the last element
1879 // of the Elts constant array will be one past the size of the vector.
1880 // Ignore the last element here, if it is greater than the mask size.
1881 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1882 NumSrcElts--;
1883
Nate Begemanb699c9b2009-01-18 06:42:49 +00001884 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001885 for (unsigned i = 0; i != NumSrcElts; ++i)
1886 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001887 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001888 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001889 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001890 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001891 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001892 }
1893 } else {
1894 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001895 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001896 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001897 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001898 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001899
John McCall7f416cc2015-09-08 08:05:57 +00001900 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1901 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001902}
1903
Renato Golin230c5eb2014-05-19 18:15:42 +00001904/// @brief Store of global named registers are always calls to intrinsics.
1905void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001906 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1907 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001908 llvm::MDNode *RegName = cast<llvm::MDNode>(
1909 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00001910 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00001911
1912 // We accept integer and pointer types only
1913 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1914 llvm::Type *Ty = OrigTy;
1915 if (OrigTy->isPointerTy())
1916 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1917 llvm::Type *Types[] = { Ty };
1918
Renato Golin230c5eb2014-05-19 18:15:42 +00001919 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1920 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00001921 if (OrigTy->isPointerTy())
1922 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00001923 Builder.CreateCall(
1924 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00001925}
1926
Eric Christopherc9e2a682014-05-20 17:10:39 +00001927// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001928// generating write-barries API. It is currently a global, ivar,
1929// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001930static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001931 LValue &LV,
1932 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001933 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001934 return;
Craig Topper99e79272013-07-26 05:59:26 +00001935
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001936 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001937 QualType ExpTy = E->getType();
1938 if (IsMemberAccess && ExpTy->isPointerType()) {
1939 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00001940 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001941 // writer-barrier conservatively.
1942 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1943 if (ExpTy->isRecordType()) {
1944 LV.setObjCIvar(false);
1945 return;
1946 }
1947 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001948 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001949 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001950 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001951 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001952 return;
1953 }
Craig Topper99e79272013-07-26 05:59:26 +00001954
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001955 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1956 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001957 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001958 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00001959 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001960 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001961 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001962 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001963 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001964 }
Craig Topper99e79272013-07-26 05:59:26 +00001965
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001966 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001967 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001968 return;
1969 }
Craig Topper99e79272013-07-26 05:59:26 +00001970
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001971 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001972 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001973 if (LV.isObjCIvar()) {
1974 // If cast is to a structure pointer, follow gcc's behavior and make it
1975 // a non-ivar write-barrier.
1976 QualType ExpTy = E->getType();
1977 if (ExpTy->isPointerType())
1978 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1979 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00001980 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001981 }
1982 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001983 }
Peter Collingbourne91147592011-04-15 00:35:48 +00001984
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001985 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001986 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1987 return;
1988 }
1989
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001990 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001991 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001992 return;
1993 }
Craig Topper99e79272013-07-26 05:59:26 +00001994
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001995 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001996 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001997 return;
1998 }
John McCall31168b02011-06-15 23:02:42 +00001999
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002000 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002001 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00002002 return;
2003 }
2004
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002005 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002006 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00002007 if (LV.isObjCIvar() && !LV.isObjCArray())
2008 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002009 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00002010 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002011 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00002012 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002013 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002014 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002015 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002016 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002017
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002018 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002019 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002020 // We don't know if member is an 'ivar', but this flag is looked at
2021 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002022 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002023 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002024 }
2025}
2026
Chris Lattner3f32d692011-07-12 06:52:18 +00002027static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00002028EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00002029 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002030 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00002031 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00002032 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00002033}
2034
Alexey Bataev97720002014-11-11 04:05:39 +00002035static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00002036 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2037 llvm::Type *RealVarTy, SourceLocation Loc) {
2038 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2039 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
2040 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2041}
2042
2043Address CodeGenFunction::EmitLoadOfReference(Address Addr,
2044 const ReferenceType *RefTy,
2045 AlignmentSource *Source) {
2046 llvm::Value *Ptr = Builder.CreateLoad(Addr);
2047 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
2048 Source, /*forPointee*/ true));
2049
2050}
2051
2052LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
2053 const ReferenceType *RefTy) {
2054 AlignmentSource Source;
2055 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &Source);
2056 return MakeAddrLValue(Addr, RefTy->getPointeeType(), Source);
Alexey Bataev97720002014-11-11 04:05:39 +00002057}
2058
Alexey Bataev31300ed2016-02-04 11:27:03 +00002059Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2060 const PointerType *PtrTy,
2061 AlignmentSource *Source) {
2062 llvm::Value *Addr = Builder.CreateLoad(Ptr);
2063 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(), Source,
2064 /*forPointeeType=*/true));
2065}
2066
2067LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2068 const PointerType *PtrTy) {
2069 AlignmentSource Source;
2070 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &Source);
2071 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), Source);
2072}
2073
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002074static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2075 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00002076 QualType T = E->getType();
2077
2078 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00002079 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2080 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00002081 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2082
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002083 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002084 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2085 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00002086 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00002087 Address Addr(V, Alignment);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002088 LValue LV;
Alexey Bataev97720002014-11-11 04:05:39 +00002089 // Emit reference to the private copy of the variable if it is an OpenMP
2090 // threadprivate variable.
2091 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00002092 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002093 E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00002094 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2095 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002096 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002097 LV = CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002098 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002099 setObjCGCLValueClass(CGF.getContext(), E, LV);
2100 return LV;
2101}
2102
John McCallb92ab1a2016-10-26 23:46:34 +00002103static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2104 const FunctionDecl *FD) {
2105 if (FD->hasAttr<WeakRefAttr>()) {
2106 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2107 return aliasee.getPointer();
2108 }
2109
2110 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002111 if (!FD->hasPrototype()) {
2112 if (const FunctionProtoType *Proto =
2113 FD->getType()->getAs<FunctionProtoType>()) {
2114 // Ugly case: for a K&R-style definition, the type of the definition
2115 // isn't the same as the type of a use. Correct for this with a
2116 // bitcast.
2117 QualType NoProtoType =
John McCallb92ab1a2016-10-26 23:46:34 +00002118 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2119 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2120 V = llvm::ConstantExpr::getBitCast(V,
2121 CGM.getTypes().ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002122 }
2123 }
John McCallb92ab1a2016-10-26 23:46:34 +00002124 return V;
2125}
2126
2127static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2128 const Expr *E, const FunctionDecl *FD) {
2129 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
Eli Friedmana0544d62011-12-03 04:14:32 +00002130 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
John McCall7f416cc2015-09-08 08:05:57 +00002131 return CGF.MakeAddrLValue(V, E->getType(), Alignment, AlignmentSource::Decl);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002132}
2133
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00002134static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2135 llvm::Value *ThisValue) {
2136 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2137 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2138 return CGF.EmitLValueForField(LV, FD);
2139}
2140
Renato Golin230c5eb2014-05-19 18:15:42 +00002141/// Named Registers are named metadata pointing to the register name
2142/// which will be read from/written to as an argument to the intrinsic
2143/// @llvm.read/write_register.
2144/// So far, only the name is being passed down, but other options such as
2145/// register type, allocation type or even optimization options could be
2146/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002147static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002148 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002149 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002150 assert(Asm->getLabel().size() < 64-Name.size() &&
2151 "Register name too big");
2152 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002153 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002154 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002155 if (M->getNumOperands() == 0) {
2156 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2157 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002158 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002159 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2160 }
John McCall7f416cc2015-09-08 08:05:57 +00002161
2162 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2163
2164 llvm::Value *Ptr =
2165 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2166 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002167}
2168
Chris Lattnerd7f58862007-06-02 05:24:33 +00002169LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002170 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002171 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002172
Renato Goline7b3d5d2014-05-27 16:46:27 +00002173 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2174 // Global Named registers access via intrinsics only
2175 if (VD->getStorageClass() == SC_Register &&
2176 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002177 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002178
Renato Goline7b3d5d2014-05-27 16:46:27 +00002179 // A DeclRefExpr for a reference initialized by a constant expression can
2180 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002181 const Expr *Init = VD->getAnyInitializer(VD);
2182 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2183 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002184 VD->checkInitIsICE() &&
2185 // Do not emit if it is private OpenMP variable.
2186 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2187 LocalDeclMap.count(VD))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002188 llvm::Constant *Val =
2189 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2190 assert(Val && "failed to emit reference constant expression");
2191 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002192
2193 // Should we be using the alignment of the constant pointer we emitted?
2194 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2195 /*pointee*/ true);
2196
2197 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
Richard Smith5a1104b2012-10-20 01:38:33 +00002198 }
David Majnemer602cfe72015-01-01 09:49:44 +00002199
2200 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002201 if (E->refersToEnclosingVariableOrCapture()) {
David Majnemer602cfe72015-01-01 09:49:44 +00002202 if (auto *FD = LambdaCaptureFields.lookup(VD))
2203 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2204 else if (CapturedStmtInfo) {
Alexey Bataevac5eabb2016-11-07 11:16:04 +00002205 auto I = LocalDeclMap.find(VD);
2206 if (I != LocalDeclMap.end()) {
2207 if (auto RefTy = VD->getType()->getAs<ReferenceType>())
2208 return EmitLoadOfReferenceLValue(I->second, RefTy);
2209 return MakeAddrLValue(I->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002210 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002211 LValue CapLVal =
2212 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2213 CapturedStmtInfo->getContextValue());
2214 return MakeAddrLValue(
2215 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2216 CapLVal.getType(), AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002217 }
John McCall7f416cc2015-09-08 08:05:57 +00002218
David Majnemer602cfe72015-01-01 09:49:44 +00002219 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002220 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2221 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002222 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002223 }
2224
Eli Friedman5720e342012-01-21 04:52:58 +00002225 // FIXME: We should be able to assert this for FunctionDecls as well!
2226 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2227 // those with a valid source location.
2228 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2229 !E->getLocation().isValid()) &&
2230 "Should not use decl without marking it used!");
2231
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002232 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002233 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002234 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2235 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002236 }
2237
Renato Goline7b3d5d2014-05-27 16:46:27 +00002238 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002239 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002240 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002241 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002242
John McCall7f416cc2015-09-08 08:05:57 +00002243 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002244
John McCall7f416cc2015-09-08 08:05:57 +00002245 // The variable should generally be present in the local decl map.
2246 auto iter = LocalDeclMap.find(VD);
2247 if (iter != LocalDeclMap.end()) {
2248 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002249
John McCall7f416cc2015-09-08 08:05:57 +00002250 // Otherwise, it might be static local we haven't emitted yet for
2251 // some reason; most likely, because it's in an outer function.
2252 } else if (VD->isStaticLocal()) {
2253 addr = Address(CGM.getOrCreateStaticVarDecl(
2254 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2255 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002256
John McCall7f416cc2015-09-08 08:05:57 +00002257 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002258 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002259 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2260 }
2261
2262
2263 // Check for OpenMP threadprivate variables.
2264 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2265 return EmitThreadPrivateVarDeclLValue(
2266 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2267 E->getExprLoc());
2268 }
2269
2270 // Drill into block byref variables.
2271 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2272 if (isBlockByref) {
2273 addr = emitBlockByrefAddress(addr, VD);
2274 }
2275
2276 // Drill into reference types.
2277 LValue LV;
2278 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2279 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2280 } else {
2281 LV = MakeAddrLValue(addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002282 }
Chris Lattner3f32d692011-07-12 06:52:18 +00002283
John McCallcdda29c2013-03-13 03:10:54 +00002284 bool isLocalStorage = VD->hasLocalStorage();
2285
2286 bool NonGCable = isLocalStorage &&
2287 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002288 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002289 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002290 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002291 LV.setNonGC(true);
2292 }
John McCallcdda29c2013-03-13 03:10:54 +00002293
2294 bool isImpreciseLifetime =
2295 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2296 if (isImpreciseLifetime)
2297 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002298 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002299 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002300 }
John McCallf3a88602011-02-03 08:15:49 +00002301
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002302 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002303 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002304
Richard Smithda383632016-08-15 01:33:41 +00002305 // FIXME: While we're emitting a binding from an enclosing scope, all other
2306 // DeclRefExprs we see should be implicitly treated as if they also refer to
2307 // an enclosing scope.
2308 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2309 return EmitLValue(BD->getBinding());
2310
David Blaikie83d382b2011-09-23 05:06:16 +00002311 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002312}
Chris Lattnere47e4402007-06-01 18:02:12 +00002313
Chris Lattner8394d792007-06-05 20:53:16 +00002314LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2315 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002316 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002317 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002318
Chris Lattner0f398c42008-07-26 22:37:01 +00002319 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002320 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002321 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002322 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002323 QualType T = E->getSubExpr()->getType()->getPointeeType();
2324 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002325
John McCall7f416cc2015-09-08 08:05:57 +00002326 AlignmentSource AlignSource;
2327 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &AlignSource);
2328 LValue LV = MakeAddrLValue(Addr, T, AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002329 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002330
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002331 // We should not generate __weak write barrier on indirect reference
2332 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2333 // But, we continue to generate __strong write barrier on indirect write
2334 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002335 if (getLangOpts().ObjC1 &&
2336 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002337 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002338 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002339 return LV;
2340 }
John McCalle3027922010-08-25 11:45:40 +00002341 case UO_Real:
2342 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002343 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002344 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002345
Richard Smith0b6b8e42012-02-18 20:53:32 +00002346 // __real is valid on scalars. This is a faster way of testing that.
2347 // __imag can only produce an rvalue on scalars.
2348 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002349 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002350 assert(E->getSubExpr()->getType()->isArithmeticType());
2351 return LV;
2352 }
2353
Alexey Bataev611b0a12016-11-07 18:15:02 +00002354 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
John McCalla2342eb2010-12-05 02:00:02 +00002355
John McCall7f416cc2015-09-08 08:05:57 +00002356 Address Component =
2357 (E->getOpcode() == UO_Real
2358 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2359 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
Alexey Bataev611b0a12016-11-07 18:15:02 +00002360 LValue ElemLV = MakeAddrLValue(Component, T, LV.getAlignmentSource());
2361 ElemLV.getQuals().addQualifiers(LV.getQuals());
2362 return ElemLV;
Chris Lattner595db862007-10-30 22:53:42 +00002363 }
John McCalle3027922010-08-25 11:45:40 +00002364 case UO_PreInc:
2365 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002366 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002367 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002368
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002369 if (E->getType()->isAnyComplexType())
2370 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2371 else
2372 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2373 return LV;
2374 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002375 }
Chris Lattner8394d792007-06-05 20:53:16 +00002376}
2377
Chris Lattner4347e3692007-06-06 04:54:52 +00002378LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002379 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
John McCall7f416cc2015-09-08 08:05:57 +00002380 E->getType(), AlignmentSource::Decl);
Chris Lattner4347e3692007-06-06 04:54:52 +00002381}
2382
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002383LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002384 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
John McCall7f416cc2015-09-08 08:05:57 +00002385 E->getType(), AlignmentSource::Decl);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002386}
2387
Mike Stump4a3999f2009-09-09 13:00:44 +00002388LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002389 auto SL = E->getFunctionName();
2390 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2391 StringRef FnName = CurFn->getName();
2392 if (FnName.startswith("\01"))
2393 FnName = FnName.substr(1);
2394 StringRef NameItems[] = {
2395 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2396 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002397 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2398 std::string Name = SL->getString();
2399 if (!Name.empty()) {
2400 unsigned Discriminator =
2401 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2402 if (Discriminator)
2403 Name += "_" + Twine(Discriminator + 1).str();
2404 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
2405 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2406 } else {
2407 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2408 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2409 }
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002410 }
Alexey Bataevec474782014-10-09 08:45:04 +00002411 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
John McCall7f416cc2015-09-08 08:05:57 +00002412 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002413}
2414
Richard Smithe30752c2012-10-09 19:52:38 +00002415/// Emit a type description suitable for use by a runtime sanitizer library. The
2416/// format of a type descriptor is
2417///
2418/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002419/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002420/// \endcode
2421///
Richard Smith683398a2012-10-09 23:55:19 +00002422/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2423/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002424llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002425 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002426 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002427 return C;
2428
Richard Smithe30752c2012-10-09 19:52:38 +00002429 uint16_t TypeKind = -1;
2430 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002431
Richard Smithe30752c2012-10-09 19:52:38 +00002432 if (T->isIntegerType()) {
2433 TypeKind = 0;
2434 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002435 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002436 } else if (T->isFloatingType()) {
2437 TypeKind = 1;
2438 TypeInfo = getContext().getTypeSize(T);
2439 }
2440
2441 // Format the type name as if for a diagnostic, including quotes and
2442 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002443 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002444 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2445 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002446 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002447 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002448
2449 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002450 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2451 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002452 };
2453 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2454
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002455 auto *GV = new llvm::GlobalVariable(
2456 CGM.getModule(), Descriptor->getType(),
2457 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002458 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002459 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002460
2461 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002462 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002463
Richard Smithe30752c2012-10-09 19:52:38 +00002464 return GV;
2465}
2466
2467llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2468 llvm::Type *TargetTy = IntPtrTy;
2469
Richard Smith48366f72013-03-22 00:47:07 +00002470 // Floating-point types which fit into intptr_t are bitcast to integers
2471 // and then passed directly (after zero-extension, if necessary).
2472 if (V->getType()->isFloatingPointTy()) {
2473 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2474 if (Bits <= TargetTy->getIntegerBitWidth())
2475 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2476 Bits));
2477 }
2478
Richard Smithe30752c2012-10-09 19:52:38 +00002479 // Integers which fit in intptr_t are zero-extended and passed directly.
2480 if (V->getType()->isIntegerTy() &&
2481 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2482 return Builder.CreateZExt(V, TargetTy);
2483
2484 // Pointers are passed directly, everything else is passed by address.
2485 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002486 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002487 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002488 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002489 }
2490 return Builder.CreatePtrToInt(V, TargetTy);
2491}
2492
2493/// \brief Emit a representation of a SourceLocation for passing to a handler
2494/// in a sanitizer runtime library. The format for this data is:
2495/// \code
2496/// struct SourceLocation {
2497/// const char *Filename;
2498/// int32_t Line, Column;
2499/// };
2500/// \endcode
2501/// For an invalid SourceLocation, the Filename pointer is null.
2502llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002503 llvm::Constant *Filename;
2504 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002505
Alexey Samsonov6c124142014-07-18 17:50:06 +00002506 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2507 if (PLoc.isValid()) {
Filipe Cabecinhasab731f72016-05-12 16:51:36 +00002508 StringRef FilenameString = PLoc.getFilename();
2509
2510 int PathComponentsToStrip =
2511 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2512 if (PathComponentsToStrip < 0) {
2513 assert(PathComponentsToStrip != INT_MIN);
2514 int PathComponentsToKeep = -PathComponentsToStrip;
2515 auto I = llvm::sys::path::rbegin(FilenameString);
2516 auto E = llvm::sys::path::rend(FilenameString);
2517 while (I != E && --PathComponentsToKeep)
2518 ++I;
2519
2520 FilenameString = FilenameString.substr(I - E);
2521 } else if (PathComponentsToStrip > 0) {
2522 auto I = llvm::sys::path::begin(FilenameString);
2523 auto E = llvm::sys::path::end(FilenameString);
2524 while (I != E && PathComponentsToStrip--)
2525 ++I;
2526
2527 if (I != E)
2528 FilenameString =
2529 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2530 else
2531 FilenameString = llvm::sys::path::filename(FilenameString);
2532 }
2533
2534 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002535 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2536 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2537 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002538 Line = PLoc.getLine();
2539 Column = PLoc.getColumn();
2540 } else {
2541 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2542 Line = Column = 0;
2543 }
2544
2545 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2546 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002547
2548 return llvm::ConstantStruct::getAnon(Data);
2549}
2550
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002551namespace {
2552/// \brief Specify under what conditions this check can be recovered
2553enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002554 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002555 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002556 /// Check supports recovering, runtime has both fatal (noreturn) and
2557 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002558 Recoverable,
2559 /// Runtime conditionally aborts, always need to support recovery.
2560 AlwaysRecoverable
2561};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002562}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002563
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002564static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2565 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002566 switch (Kind) {
2567 case SanitizerKind::Vptr:
2568 return CheckRecoverableKind::AlwaysRecoverable;
2569 case SanitizerKind::Return:
2570 case SanitizerKind::Unreachable:
2571 return CheckRecoverableKind::Unrecoverable;
2572 default:
2573 return CheckRecoverableKind::Recoverable;
2574 }
2575}
2576
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002577namespace {
2578struct SanitizerHandlerInfo {
2579 char const *const Name;
2580 unsigned Version;
2581};
Saleem Abdulrasoolca6e2b42016-12-13 03:27:35 +00002582}
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002583
2584const SanitizerHandlerInfo SanitizerHandlers[] = {
2585#define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2586 LIST_SANITIZER_CHECKS
2587#undef SANITIZER_CHECK
2588};
2589
Alexey Samsonov88459522015-01-12 22:39:12 +00002590static void emitCheckHandlerCall(CodeGenFunction &CGF,
2591 llvm::FunctionType *FnType,
2592 ArrayRef<llvm::Value *> FnArgs,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002593 SanitizerHandler CheckHandler,
Alexey Samsonov88459522015-01-12 22:39:12 +00002594 CheckRecoverableKind RecoverKind, bool IsFatal,
2595 llvm::BasicBlock *ContBB) {
2596 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2597 bool NeedsAbortSuffix =
2598 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002599 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2600 const StringRef CheckName = CheckInfo.Name;
2601 std::string FnName =
2602 ("__ubsan_handle_" + CheckName +
Vedant Kumar4881bdf2016-12-12 18:47:33 +00002603 (CheckInfo.Version ? "_v" + llvm::utostr(CheckInfo.Version) : "") +
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002604 (NeedsAbortSuffix ? "_abort" : ""))
2605 .str();
Alexey Samsonov88459522015-01-12 22:39:12 +00002606 bool MayReturn =
2607 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2608
2609 llvm::AttrBuilder B;
2610 if (!MayReturn) {
2611 B.addAttribute(llvm::Attribute::NoReturn)
2612 .addAttribute(llvm::Attribute::NoUnwind);
2613 }
2614 B.addAttribute(llvm::Attribute::UWTable);
2615
2616 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2617 FnType, FnName,
2618 llvm::AttributeSet::get(CGF.getLLVMContext(),
Saleem Abdulrasool05b8fde2016-12-15 16:30:20 +00002619 llvm::AttributeSet::FunctionIndex, B),
2620 /*Local=*/true);
Alexey Samsonov88459522015-01-12 22:39:12 +00002621 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2622 if (!MayReturn) {
2623 HandlerCall->setDoesNotReturn();
2624 CGF.Builder.CreateUnreachable();
2625 } else {
2626 CGF.Builder.CreateBr(ContBB);
2627 }
2628}
2629
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002630void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002631 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002632 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002633 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002634 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002635 assert(Checked.size() > 0);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002636 assert(CheckHandler >= 0 &&
2637 CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers));
2638 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
Alexey Samsonov88459522015-01-12 22:39:12 +00002639
2640 llvm::Value *FatalCond = nullptr;
2641 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002642 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002643 for (int i = 0, n = Checked.size(); i < n; ++i) {
2644 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002645 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002646 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002647 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2648 ? TrapCond
2649 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2650 ? RecoverableCond
2651 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002652 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2653 }
2654
Peter Collingbourne9881b782015-06-18 23:59:22 +00002655 if (TrapCond)
2656 EmitTrapCheck(TrapCond);
2657 if (!FatalCond && !RecoverableCond)
2658 return;
2659
Alexey Samsonov88459522015-01-12 22:39:12 +00002660 llvm::Value *JointCond;
2661 if (FatalCond && RecoverableCond)
2662 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2663 else
2664 JointCond = FatalCond ? FatalCond : RecoverableCond;
2665 assert(JointCond);
2666
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002667 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002668 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002669#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002670 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002671 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002672 "All recoverable kinds in a single check must be same!");
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002673 assert(SanOpts.has(Checked[i].second));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002674 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002675#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002676
Richard Smith4d1458e2012-09-08 02:08:36 +00002677 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002678 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2679 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002680 // Give hint that we very much don't expect to execute the handler
2681 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2682 llvm::MDBuilder MDHelper(getLLVMContext());
2683 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2684 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002685 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002686
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002687 // Handler functions take an i8* pointing to the (handler-specific) static
2688 // information block, followed by a sequence of intptr_t arguments
2689 // representing operand values.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002690 SmallVector<llvm::Value *, 4> Args;
2691 SmallVector<llvm::Type *, 4> ArgTypes;
Richard Smithe30752c2012-10-09 19:52:38 +00002692 Args.reserve(DynamicArgs.size() + 1);
2693 ArgTypes.reserve(DynamicArgs.size() + 1);
2694
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002695 // Emit handler arguments and create handler function type.
2696 if (!StaticArgs.empty()) {
2697 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2698 auto *InfoPtr =
2699 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2700 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002701 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002702 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2703 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2704 ArgTypes.push_back(Int8PtrTy);
2705 }
2706
Richard Smithe30752c2012-10-09 19:52:38 +00002707 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2708 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2709 ArgTypes.push_back(IntPtrTy);
2710 }
2711
2712 llvm::FunctionType *FnType =
2713 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002714
Alexey Samsonov88459522015-01-12 22:39:12 +00002715 if (!FatalCond || !RecoverableCond) {
2716 // Simple case: we need to generate a single handler call, either
2717 // fatal, or non-fatal.
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002718 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
Alexey Samsonov88459522015-01-12 22:39:12 +00002719 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002720 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002721 // Emit two handler calls: first one for set of unrecoverable checks,
2722 // another one for recoverable.
2723 llvm::BasicBlock *NonFatalHandlerBB =
2724 createBasicBlock("non_fatal." + CheckName);
2725 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2726 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2727 EmitBlock(FatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002728 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
Alexey Samsonov88459522015-01-12 22:39:12 +00002729 NonFatalHandlerBB);
2730 EmitBlock(NonFatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002731 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
Alexey Samsonov88459522015-01-12 22:39:12 +00002732 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002733 }
Richard Smithe30752c2012-10-09 19:52:38 +00002734
Richard Smith4d1458e2012-09-08 02:08:36 +00002735 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002736}
2737
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002738void CodeGenFunction::EmitCfiSlowPathCheck(
2739 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2740 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002741 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2742
2743 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2744 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2745
2746 llvm::MDBuilder MDHelper(getLLVMContext());
2747 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2748 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2749
2750 EmitBlock(CheckBB);
2751
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002752 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2753
2754 llvm::CallInst *CheckCall;
2755 if (WithDiag) {
2756 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2757 auto *InfoPtr =
2758 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2759 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002760 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002761 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2762
2763 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2764 "__cfi_slowpath_diag",
2765 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2766 false));
2767 CheckCall = Builder.CreateCall(
2768 SlowPathDiagFn,
2769 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2770 } else {
2771 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2772 "__cfi_slowpath",
2773 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2774 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2775 }
2776
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002777 CheckCall->setDoesNotThrow();
2778
2779 EmitBlock(Cont);
2780}
2781
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002782// This function is basically a switch over the CFI failure kind, which is
2783// extracted from CFICheckFailData (1st function argument). Each case is either
2784// llvm.trap or a call to one of the two runtime handlers, based on
2785// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2786// failure kind) traps, but this should really never happen. CFICheckFailData
2787// can be nullptr if the calling module has -fsanitize-trap behavior for this
2788// check kind; in this case __cfi_check_fail traps as well.
2789void CodeGenFunction::EmitCfiCheckFail() {
2790 SanitizerScope SanScope(this);
2791 FunctionArgList Args;
2792 ImplicitParamDecl ArgData(getContext(), nullptr, SourceLocation(), nullptr,
2793 getContext().VoidPtrTy);
2794 ImplicitParamDecl ArgAddr(getContext(), nullptr, SourceLocation(), nullptr,
2795 getContext().VoidPtrTy);
2796 Args.push_back(&ArgData);
2797 Args.push_back(&ArgAddr);
2798
John McCallc56a8b32016-03-11 04:30:31 +00002799 const CGFunctionInfo &FI =
2800 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002801
2802 llvm::Function *F = llvm::Function::Create(
2803 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2804 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2805 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2806
2807 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2808 SourceLocation());
2809
2810 llvm::Value *Data =
2811 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2812 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2813 llvm::Value *Addr =
2814 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2815 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2816
2817 // Data == nullptr means the calling module has trap behaviour for this check.
2818 llvm::Value *DataIsNotNullPtr =
2819 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2820 EmitTrapCheck(DataIsNotNullPtr);
2821
2822 llvm::StructType *SourceLocationTy =
2823 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty, nullptr);
2824 llvm::StructType *CfiCheckFailDataTy =
2825 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy, nullptr);
2826
2827 llvm::Value *V = Builder.CreateConstGEP2_32(
2828 CfiCheckFailDataTy,
2829 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2830 0);
2831 Address CheckKindAddr(V, getIntAlign());
2832 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2833
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002834 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2835 CGM.getLLVMContext(),
2836 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2837 llvm::Value *ValidVtable = Builder.CreateZExt(
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002838 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002839 {Addr, AllVtables}),
2840 IntPtrTy);
2841
Evgeniy Stepanov4d3b0872016-01-25 23:45:37 +00002842 const std::pair<int, SanitizerMask> CheckKinds[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002843 {CFITCK_VCall, SanitizerKind::CFIVCall},
2844 {CFITCK_NVCall, SanitizerKind::CFINVCall},
2845 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
2846 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
2847 {CFITCK_ICall, SanitizerKind::CFIICall}};
2848
2849 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
2850 for (auto CheckKindMaskPair : CheckKinds) {
2851 int Kind = CheckKindMaskPair.first;
2852 SanitizerMask Mask = CheckKindMaskPair.second;
2853 llvm::Value *Cond =
2854 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002855 if (CGM.getLangOpts().Sanitize.has(Mask))
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002856 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002857 {Data, Addr, ValidVtable});
2858 else
2859 EmitTrapCheck(Cond);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002860 }
2861
2862 FinishFunction();
2863 // The only reference to this function will be created during LTO link.
2864 // Make sure it survives until then.
2865 CGM.addUsedGlobal(F);
2866}
2867
Chad Rosierae229d52013-01-29 23:31:22 +00002868void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00002869 llvm::BasicBlock *Cont = createBasicBlock("cont");
2870
2871 // If we're optimizing, collapse all calls to trap down to just one per
2872 // function to save on code size.
2873 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2874 TrapBB = createBasicBlock("trap");
2875 Builder.CreateCondBr(Checked, Cont, TrapBB);
2876 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002877 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00002878 TrapCall->setDoesNotReturn();
2879 TrapCall->setDoesNotThrow();
2880 Builder.CreateUnreachable();
2881 } else {
2882 Builder.CreateCondBr(Checked, Cont, TrapBB);
2883 }
2884
2885 EmitBlock(Cont);
2886}
2887
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002888llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00002889 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002890
Amaury Sechet21f51b32016-09-09 04:42:49 +00002891 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
2892 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
2893 CGM.getCodeGenOpts().TrapFuncName);
2894 TrapCall->addAttribute(llvm::AttributeSet::FunctionIndex, A);
2895 }
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002896
2897 return TrapCall;
2898}
2899
John McCall7f416cc2015-09-08 08:05:57 +00002900Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
2901 AlignmentSource *AlignSource) {
2902 assert(E->getType()->isArrayType() &&
2903 "Array to pointer decay must have array source type!");
2904
2905 // Expressions of array type can't be bitfields or vector elements.
2906 LValue LV = EmitLValue(E);
2907 Address Addr = LV.getAddress();
2908 if (AlignSource) *AlignSource = LV.getAlignmentSource();
2909
2910 // If the array type was an incomplete type, we need to make sure
2911 // the decay ends up being the right type.
2912 llvm::Type *NewTy = ConvertType(E->getType());
2913 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2914
2915 // Note that VLA pointers are always decayed, so we don't need to do
2916 // anything here.
2917 if (!E->getType()->isVariableArrayType()) {
2918 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2919 "Expected pointer to array");
2920 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2921 }
2922
2923 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2924 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2925}
2926
Chris Lattner6c5abe82010-06-26 23:03:20 +00002927/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2928/// array to pointer, return the array subexpression.
2929static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2930 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002931 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00002932 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00002933 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002934
Chris Lattner6c5abe82010-06-26 23:03:20 +00002935 // If this is a decay from variable width array, bail out.
2936 const Expr *SubExpr = CE->getSubExpr();
2937 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00002938 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002939
Chris Lattner6c5abe82010-06-26 23:03:20 +00002940 return SubExpr;
2941}
2942
John McCall7f416cc2015-09-08 08:05:57 +00002943static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
2944 llvm::Value *ptr,
2945 ArrayRef<llvm::Value*> indices,
2946 bool inbounds,
2947 const llvm::Twine &name = "arrayidx") {
2948 if (inbounds) {
2949 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name);
2950 } else {
2951 return CGF.Builder.CreateGEP(ptr, indices, name);
2952 }
2953}
2954
2955static CharUnits getArrayElementAlign(CharUnits arrayAlign,
2956 llvm::Value *idx,
2957 CharUnits eltSize) {
2958 // If we have a constant index, we can use the exact offset of the
2959 // element we're accessing.
2960 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
2961 CharUnits offset = constantIdx->getZExtValue() * eltSize;
2962 return arrayAlign.alignmentAtOffset(offset);
2963
2964 // Otherwise, use the worst-case alignment for any element.
2965 } else {
2966 return arrayAlign.alignmentOfArrayElement(eltSize);
2967 }
2968}
2969
2970static QualType getFixedSizeElementType(const ASTContext &ctx,
2971 const VariableArrayType *vla) {
2972 QualType eltType;
2973 do {
2974 eltType = vla->getElementType();
2975 } while ((vla = ctx.getAsVariableArrayType(eltType)));
2976 return eltType;
2977}
2978
2979static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
2980 ArrayRef<llvm::Value*> indices,
2981 QualType eltType, bool inbounds,
2982 const llvm::Twine &name = "arrayidx") {
2983 // All the indices except that last must be zero.
2984#ifndef NDEBUG
2985 for (auto idx : indices.drop_back())
2986 assert(isa<llvm::ConstantInt>(idx) &&
2987 cast<llvm::ConstantInt>(idx)->isZero());
2988#endif
2989
2990 // Determine the element size of the statically-sized base. This is
2991 // the thing that the indices are expressed in terms of.
2992 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
2993 eltType = getFixedSizeElementType(CGF.getContext(), vla);
2994 }
2995
2996 // We can use that to compute the best alignment of the element.
2997 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
2998 CharUnits eltAlign =
2999 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3000
3001 llvm::Value *eltPtr =
3002 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name);
3003 return Address(eltPtr, eltAlign);
3004}
3005
Richard Smith539e4a72013-02-23 02:53:19 +00003006LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3007 bool Accessed) {
Richard Smith9e67b992016-09-26 23:49:47 +00003008 // The index must always be an integer, which is not an aggregate. Emit it
3009 // in lexical order (this complexity is, sadly, required by C++17).
3010 llvm::Value *IdxPre =
3011 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
Richard Smith40885712016-09-27 00:53:24 +00003012 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
Richard Smith9e67b992016-09-26 23:49:47 +00003013 auto *Idx = IdxPre;
3014 if (E->getLHS() != E->getIdx()) {
3015 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3016 Idx = EmitScalarExpr(E->getIdx());
3017 }
Eli Friedman07bbeca2009-06-06 19:09:26 +00003018
Richard Smith9e67b992016-09-26 23:49:47 +00003019 QualType IdxTy = E->getIdx()->getType();
3020 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
3021
3022 if (SanOpts.has(SanitizerKind::ArrayBounds))
3023 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3024
3025 // Extend or truncate the index type to 32 or 64-bits.
3026 if (Promote && Idx->getType() != IntPtrTy)
3027 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3028
3029 return Idx;
3030 };
3031 IdxPre = nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +00003032
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003033 // If the base is a vector type, then we are forming a vector element lvalue
3034 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003035 if (E->getBase()->getType()->isVectorType() &&
3036 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003037 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00003038 LValue LHS = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003039 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
Ted Kremenekc81614d2007-08-20 16:18:38 +00003040 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Eli Friedman327944b2008-06-13 23:01:12 +00003041 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
John McCall7f416cc2015-09-08 08:05:57 +00003042 E->getBase()->getType(),
3043 LHS.getAlignmentSource());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003044 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003045
John McCall7f416cc2015-09-08 08:05:57 +00003046 // All the other cases basically behave like simple offsetting.
3047
John McCall7f416cc2015-09-08 08:05:57 +00003048 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003049 if (isa<ExtVectorElementExpr>(E->getBase())) {
3050 LValue LV = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003051 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003052 Address Addr = EmitExtVectorElementLValue(LV);
3053
3054 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
3055 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true);
3056 return MakeAddrLValue(Addr, EltType, LV.getAlignmentSource());
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003057 }
John McCall7f416cc2015-09-08 08:05:57 +00003058
3059 AlignmentSource AlignSource;
3060 Address Addr = Address::invalid();
3061 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003062 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00003063 // The base must be a pointer, which is not an aggregate. Emit
3064 // it. It needs to be emitted first in case it's what captures
3065 // the VLA bounds.
John McCall7f416cc2015-09-08 08:05:57 +00003066 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Richard Smith9e67b992016-09-26 23:49:47 +00003067 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Mike Stump4a3999f2009-09-09 13:00:44 +00003068
John McCall23c29fe2011-06-24 21:55:10 +00003069 // The element count here is the total number of non-VLA elements.
3070 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00003071
John McCall77527a82011-06-25 01:32:37 +00003072 // Effectively, the multiply by the VLA size is part of the GEP.
3073 // GEP indexes are signed, and scaling an index isn't permitted to
3074 // signed-overflow, so we use the same semantics for our explicit
3075 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003076 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00003077 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003078 } else {
3079 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003080 }
John McCall7f416cc2015-09-08 08:05:57 +00003081
3082 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3083 !getLangOpts().isSignedOverflowDefined());
3084
Chris Lattner6c5abe82010-06-26 23:03:20 +00003085 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3086 // Indexing over an interface, as in "NSString *P; P[4];"
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003087
John McCall7f416cc2015-09-08 08:05:57 +00003088 // Emit the base pointer.
3089 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Richard Smith9e67b992016-09-26 23:49:47 +00003090 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3091
3092 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3093 llvm::Value *InterfaceSizeVal =
3094 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3095
3096 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
John McCall7f416cc2015-09-08 08:05:57 +00003097
3098 // We don't necessarily build correct LLVM struct types for ObjC
3099 // interfaces, so we can't rely on GEP to do this scaling
3100 // correctly, so we need to cast to i8*. FIXME: is this actually
3101 // true? A lot of other things in the fragile ABI would break...
3102 llvm::Type *OrigBaseTy = Addr.getType();
3103 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3104
3105 // Do the GEP.
3106 CharUnits EltAlign =
3107 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
3108 llvm::Value *EltPtr =
3109 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false);
3110 Addr = Address(EltPtr, EltAlign);
3111
3112 // Cast back.
3113 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00003114 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3115 // If this is A[i] where A is an array, the frontend will have decayed the
3116 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3117 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3118 // "gep x, i" here. Emit one "gep A, 0, i".
3119 assert(Array->getType()->isArrayType() &&
3120 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00003121 LValue ArrayLV;
3122 // For simple multidimensional array indexing, set the 'accessed' flag for
3123 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003124 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00003125 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3126 else
3127 ArrayLV = EmitLValue(Array);
Richard Smith9e67b992016-09-26 23:49:47 +00003128 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Craig Topper99e79272013-07-26 05:59:26 +00003129
Daniel Dunbar82634272011-04-01 00:49:43 +00003130 // Propagate the alignment from the array itself to the result.
John McCall7f416cc2015-09-08 08:05:57 +00003131 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
3132 {CGM.getSize(CharUnits::Zero()), Idx},
3133 E->getType(),
3134 !getLangOpts().isSignedOverflowDefined());
3135 AlignSource = ArrayLV.getAlignmentSource();
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003136 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003137 // The base must be a pointer; emit it with an estimate of its alignment.
3138 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Richard Smith9e67b992016-09-26 23:49:47 +00003139 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003140 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3141 !getLangOpts().isSignedOverflowDefined());
Anders Carlsson3d312f82008-12-21 00:11:23 +00003142 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003143
John McCall7f416cc2015-09-08 08:05:57 +00003144 LValue LV = MakeAddrLValue(Addr, E->getType(), AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00003145
John McCall7f416cc2015-09-08 08:05:57 +00003146 // TODO: Preserve/extend path TBAA metadata?
John McCall8ccfcb52009-09-24 19:53:00 +00003147
Richard Smith9c6890a2012-11-01 22:30:59 +00003148 if (getLangOpts().ObjC1 &&
3149 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00003150 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00003151 setObjCGCLValueClass(getContext(), E, LV);
3152 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00003153 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00003154}
3155
Alexey Bataev31300ed2016-02-04 11:27:03 +00003156static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
3157 AlignmentSource &AlignSource,
3158 QualType BaseTy, QualType ElTy,
3159 bool IsLowerBound) {
3160 LValue BaseLVal;
3161 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3162 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3163 if (BaseTy->isArrayType()) {
3164 Address Addr = BaseLVal.getAddress();
3165 AlignSource = BaseLVal.getAlignmentSource();
3166
3167 // If the array type was an incomplete type, we need to make sure
3168 // the decay ends up being the right type.
3169 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3170 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3171
3172 // Note that VLA pointers are always decayed, so we don't need to do
3173 // anything here.
3174 if (!BaseTy->isVariableArrayType()) {
3175 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3176 "Expected pointer to array");
3177 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3178 "arraydecay");
3179 }
3180
3181 return CGF.Builder.CreateElementBitCast(Addr,
3182 CGF.ConvertTypeForMem(ElTy));
3183 }
3184 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &AlignSource);
3185 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3186 }
3187 return CGF.EmitPointerWithAlignment(Base, &AlignSource);
3188}
3189
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003190LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3191 bool IsLowerBound) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003192 QualType BaseTy;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003193 if (auto *ASE =
3194 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
Alexey Bataev31300ed2016-02-04 11:27:03 +00003195 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003196 else
Alexey Bataev31300ed2016-02-04 11:27:03 +00003197 BaseTy = E->getBase()->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003198 QualType ResultExprTy;
3199 if (auto *AT = getContext().getAsArrayType(BaseTy))
3200 ResultExprTy = AT->getElementType();
3201 else
3202 ResultExprTy = BaseTy->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003203 llvm::Value *Idx = nullptr;
Benjamin Kramer5ff67472016-04-11 08:26:13 +00003204 if (IsLowerBound || E->getColonLoc().isInvalid()) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003205 // Requesting lower bound or upper bound, but without provided length and
3206 // without ':' symbol for the default length -> length = 1.
3207 // Idx = LowerBound ?: 0;
3208 if (auto *LowerBound = E->getLowerBound()) {
3209 Idx = Builder.CreateIntCast(
3210 EmitScalarExpr(LowerBound), IntPtrTy,
3211 LowerBound->getType()->hasSignedIntegerRepresentation());
3212 } else
3213 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3214 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003215 // Try to emit length or lower bound as constant. If this is possible, 1
3216 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3217 // IR (LB + Len) - 1.
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003218 auto &C = CGM.getContext();
3219 auto *Length = E->getLength();
3220 llvm::APSInt ConstLength;
3221 if (Length) {
3222 // Idx = LowerBound + Length - 1;
3223 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3224 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3225 Length = nullptr;
3226 }
3227 auto *LowerBound = E->getLowerBound();
3228 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3229 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3230 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3231 LowerBound = nullptr;
3232 }
3233 if (!Length)
3234 --ConstLength;
3235 else if (!LowerBound)
3236 --ConstLowerBound;
3237
3238 if (Length || LowerBound) {
3239 auto *LowerBoundVal =
3240 LowerBound
3241 ? Builder.CreateIntCast(
3242 EmitScalarExpr(LowerBound), IntPtrTy,
3243 LowerBound->getType()->hasSignedIntegerRepresentation())
3244 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3245 auto *LengthVal =
3246 Length
3247 ? Builder.CreateIntCast(
3248 EmitScalarExpr(Length), IntPtrTy,
3249 Length->getType()->hasSignedIntegerRepresentation())
3250 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3251 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3252 /*HasNUW=*/false,
3253 !getLangOpts().isSignedOverflowDefined());
3254 if (Length && LowerBound) {
3255 Idx = Builder.CreateSub(
3256 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3257 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3258 }
3259 } else
3260 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3261 } else {
3262 // Idx = ArraySize - 1;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003263 QualType ArrayTy = BaseTy->isPointerType()
3264 ? E->getBase()->IgnoreParenImpCasts()->getType()
3265 : BaseTy;
3266 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003267 Length = VAT->getSizeExpr();
3268 if (Length->isIntegerConstantExpr(ConstLength, C))
3269 Length = nullptr;
3270 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003271 auto *CAT = C.getAsConstantArrayType(ArrayTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003272 ConstLength = CAT->getSize();
3273 }
3274 if (Length) {
3275 auto *LengthVal = Builder.CreateIntCast(
3276 EmitScalarExpr(Length), IntPtrTy,
3277 Length->getType()->hasSignedIntegerRepresentation());
3278 Idx = Builder.CreateSub(
3279 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3280 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3281 } else {
3282 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3283 --ConstLength;
3284 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3285 }
3286 }
3287 }
3288 assert(Idx);
3289
Alexey Bataev31300ed2016-02-04 11:27:03 +00003290 Address EltPtr = Address::invalid();
3291 AlignmentSource AlignSource;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003292 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003293 // The base must be a pointer, which is not an aggregate. Emit
3294 // it. It needs to be emitted first in case it's what captures
3295 // the VLA bounds.
3296 Address Base =
3297 emitOMPArraySectionBase(*this, E->getBase(), AlignSource, BaseTy,
3298 VLA->getElementType(), IsLowerBound);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003299 // The element count here is the total number of non-VLA elements.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003300 llvm::Value *NumElements = getVLASize(VLA).first;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003301
3302 // Effectively, the multiply by the VLA size is part of the GEP.
3303 // GEP indexes are signed, and scaling an index isn't permitted to
3304 // signed-overflow, so we use the same semantics for our explicit
3305 // multiply. We suppress this if overflow is not undefined behavior.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003306 if (getLangOpts().isSignedOverflowDefined())
3307 Idx = Builder.CreateMul(Idx, NumElements);
3308 else
3309 Idx = Builder.CreateNSWMul(Idx, NumElements);
3310 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3311 !getLangOpts().isSignedOverflowDefined());
3312 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3313 // If this is A[i] where A is an array, the frontend will have decayed the
3314 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3315 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3316 // "gep x, i" here. Emit one "gep A, 0, i".
3317 assert(Array->getType()->isArrayType() &&
3318 "Array to pointer decay must have array source type!");
3319 LValue ArrayLV;
3320 // For simple multidimensional array indexing, set the 'accessed' flag for
3321 // better bounds-checking of the base expression.
3322 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3323 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3324 else
3325 ArrayLV = EmitLValue(Array);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003326
Alexey Bataev31300ed2016-02-04 11:27:03 +00003327 // Propagate the alignment from the array itself to the result.
3328 EltPtr = emitArraySubscriptGEP(
3329 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3330 ResultExprTy, !getLangOpts().isSignedOverflowDefined());
3331 AlignSource = ArrayLV.getAlignmentSource();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003332 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003333 Address Base = emitOMPArraySectionBase(*this, E->getBase(), AlignSource,
3334 BaseTy, ResultExprTy, IsLowerBound);
3335 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3336 !getLangOpts().isSignedOverflowDefined());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003337 }
3338
Alexey Bataev31300ed2016-02-04 11:27:03 +00003339 return MakeAddrLValue(EltPtr, ResultExprTy, AlignSource);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003340}
3341
Chris Lattner9e751ca2007-08-02 23:37:31 +00003342LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00003343EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00003344 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003345 LValue Base;
3346
3347 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00003348 if (E->isArrow()) {
3349 // If it is a pointer to a vector, emit the address and form an lvalue with
3350 // it.
John McCall7f416cc2015-09-08 08:05:57 +00003351 AlignmentSource AlignSource;
3352 Address Ptr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003353 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
John McCall7f416cc2015-09-08 08:05:57 +00003354 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00003355 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00003356 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00003357 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3358 // emit the base as an lvalue.
3359 assert(E->getBase()->getType()->isVectorType());
3360 Base = EmitLValue(E->getBase());
3361 } else {
3362 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00003363 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00003364 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00003365 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00003366
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00003367 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00003368 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00003369 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00003370 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3371 AlignmentSource::Decl);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003372 }
John McCall1553b192011-06-16 04:16:24 +00003373
3374 QualType type =
3375 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00003376
Nate Begemand3862152008-05-13 21:03:02 +00003377 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00003378 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00003379 E->getEncodedElementAccess(Indices);
3380
3381 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00003382 llvm::Constant *CV =
3383 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00003384 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
John McCall7f416cc2015-09-08 08:05:57 +00003385 Base.getAlignmentSource());
Nate Begemand3862152008-05-13 21:03:02 +00003386 }
3387 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3388
3389 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003390 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00003391
Chris Lattner595ba3a2012-01-30 06:20:36 +00003392 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3393 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00003394 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00003395 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3396 Base.getAlignmentSource());
Chris Lattner9e751ca2007-08-02 23:37:31 +00003397}
3398
Devang Patel30efa2e2007-10-23 20:28:39 +00003399LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00003400 Expr *BaseExpr = E->getBase();
Eli Friedman327944b2008-06-13 23:01:12 +00003401
Chris Lattner4e4186b2007-12-02 18:52:07 +00003402 // 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 +00003403 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00003404 if (E->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00003405 AlignmentSource AlignSource;
3406 Address Addr = EmitPointerWithAlignment(BaseExpr, &AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003407 QualType PtrTy = BaseExpr->getType()->getPointeeType();
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003408 SanitizerSet SkippedChecks;
Vedant Kumare550d112017-02-23 01:22:38 +00003409 if (IsDeclRefOrWrappedCXXThis(BaseExpr))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003410 SkippedChecks.set(SanitizerKind::Null, true);
3411 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
3412 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
John McCall7f416cc2015-09-08 08:05:57 +00003413 BaseLV = MakeAddrLValue(Addr, PtrTy, AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003414 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003415 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003416
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003417 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003418 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003419 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003420 setObjCGCLValueClass(getContext(), E, LV);
3421 return LV;
3422 }
Craig Topper99e79272013-07-26 05:59:26 +00003423
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003424 if (auto *VD = dyn_cast<VarDecl>(ND))
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00003425 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003426
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003427 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003428 return EmitFunctionDeclLValue(*this, E, FD);
3429
David Blaikie83d382b2011-09-23 05:06:16 +00003430 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003431}
Devang Patel30efa2e2007-10-23 20:28:39 +00003432
John McCalldec348f72013-05-03 07:33:41 +00003433/// Given that we are currently emitting a lambda, emit an l-value for
3434/// one of its members.
3435LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3436 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3437 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3438 QualType LambdaTagType =
3439 getContext().getTagDeclType(Field->getParent());
3440 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3441 return EmitLValueForField(LambdaLV, Field);
3442}
3443
John McCall7f416cc2015-09-08 08:05:57 +00003444/// Drill down to the storage of a field without walking into
3445/// reference types.
3446///
3447/// The resulting address doesn't necessarily have the right type.
3448static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3449 const FieldDecl *field) {
3450 const RecordDecl *rec = field->getParent();
3451
3452 unsigned idx =
3453 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3454
3455 CharUnits offset;
3456 // Adjust the alignment down to the given offset.
3457 // As a special case, if the LLVM field index is 0, we know that this
3458 // is zero.
3459 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3460 .getFieldOffset(field->getFieldIndex()) == 0) &&
3461 "LLVM field at index zero had non-zero offset?");
3462 if (idx != 0) {
3463 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3464 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3465 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3466 }
3467
3468 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3469}
3470
Eli Friedman7f1ff602012-04-16 03:54:45 +00003471LValue CodeGenFunction::EmitLValueForField(LValue base,
3472 const FieldDecl *field) {
John McCall7f416cc2015-09-08 08:05:57 +00003473 AlignmentSource fieldAlignSource =
3474 getFieldAlignmentSource(base.getAlignmentSource());
3475
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003476 if (field->isBitField()) {
3477 const CGRecordLayout &RL =
3478 CGM.getTypes().getCGRecordLayout(field->getParent());
3479 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003480 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003481 unsigned Idx = RL.getLLVMFieldNo(field);
3482 if (Idx != 0)
3483 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003484 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3485 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003486 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003487 llvm::Type *FieldIntTy =
3488 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3489 if (Addr.getElementType() != FieldIntTy)
3490 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003491
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003492 QualType fieldType =
3493 field->getType().withCVRQualifiers(base.getVRQualifiers());
John McCall7f416cc2015-09-08 08:05:57 +00003494 return LValue::MakeBitfield(Addr, Info, fieldType, fieldAlignSource);
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003495 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003496
John McCall53fcbd22011-02-26 08:07:02 +00003497 const RecordDecl *rec = field->getParent();
3498 QualType type = field->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003499
John McCall53fcbd22011-02-26 08:07:02 +00003500 bool mayAlias = rec->hasAttr<MayAliasAttr>();
3501
John McCall7f416cc2015-09-08 08:05:57 +00003502 Address addr = base.getAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003503 unsigned cvr = base.getVRQualifiers();
Manman Renc451e572013-04-04 21:53:22 +00003504 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
John McCall53fcbd22011-02-26 08:07:02 +00003505 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003506 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00003507 assert(!type->isReferenceType() && "union has reference member");
Manman Renc451e572013-04-04 21:53:22 +00003508 // TODO: handle path-aware TBAA for union.
3509 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003510 } else {
3511 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003512 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003513
3514 // If this is a reference field, load the reference right now.
3515 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3516 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3517 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3518
Manman Renc451e572013-04-04 21:53:22 +00003519 // Loading the reference will disable path-aware TBAA.
3520 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003521 if (CGM.shouldUseTBAA()) {
3522 llvm::MDNode *tbaa;
3523 if (mayAlias)
3524 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3525 else
3526 tbaa = CGM.getTBAAInfo(type);
Manman Ren4f755de2013-10-08 00:08:49 +00003527 if (tbaa)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00003528 CGM.DecorateInstructionWithTBAA(load, tbaa);
John McCall53fcbd22011-02-26 08:07:02 +00003529 }
3530
John McCall53fcbd22011-02-26 08:07:02 +00003531 mayAlias = false;
3532 type = refType->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003533
3534 CharUnits alignment =
3535 getNaturalTypeAlignment(type, &fieldAlignSource, /*pointee*/ true);
3536 addr = Address(load, alignment);
3537
3538 // Qualifiers on the struct don't apply to the referencee, and
3539 // we'll pick up CVR from the actual type later, so reset these
3540 // additional qualifiers now.
3541 cvr = 0;
John McCall53fcbd22011-02-26 08:07:02 +00003542 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003543 }
Craig Topper99e79272013-07-26 05:59:26 +00003544
Chris Lattner13ee4f42011-07-10 05:34:54 +00003545 // Make sure that the address is pointing to the right type. This is critical
3546 // for both unions and structs. A union needs a bitcast, a struct element
3547 // will need a bitcast if the LLVM type laid out doesn't match the desired
3548 // type.
John McCall7f416cc2015-09-08 08:05:57 +00003549 addr = Builder.CreateElementBitCast(addr,
3550 CGM.getTypes().ConvertTypeForMem(type),
3551 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003552
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003553 if (field->hasAttr<AnnotateAttr>())
3554 addr = EmitFieldAnnotations(field, addr);
3555
John McCall7f416cc2015-09-08 08:05:57 +00003556 LValue LV = MakeAddrLValue(addr, type, fieldAlignSource);
John McCall53fcbd22011-02-26 08:07:02 +00003557 LV.getQuals().addCVRQualifiers(cvr);
Manman Renc451e572013-04-04 21:53:22 +00003558 if (TBAAPath) {
3559 const ASTRecordLayout &Layout =
3560 getContext().getASTRecordLayout(field->getParent());
3561 // Set the base type to be the base type of the base LValue and
3562 // update offset to be relative to the base type.
Manman Ren0e521662013-04-27 00:39:37 +00003563 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3564 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
Manman Renc451e572013-04-04 21:53:22 +00003565 Layout.getFieldOffset(field->getFieldIndex()) /
3566 getContext().getCharWidth());
3567 }
Daniel Dunbarf166a522010-08-21 03:44:13 +00003568
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003569 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003570 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3571 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003572
3573 // Fields of may_alias structs act like 'char' for TBAA purposes.
3574 // FIXME: this should get propagated down through anonymous structs
3575 // and unions.
3576 if (mayAlias && LV.getTBAAInfo())
3577 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3578
Daniel Dunbarf166a522010-08-21 03:44:13 +00003579 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003580}
3581
Craig Topper99e79272013-07-26 05:59:26 +00003582LValue
3583CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003584 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003585 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003586
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003587 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003588 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003589
John McCall7f416cc2015-09-08 08:05:57 +00003590 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003591
John McCall7f416cc2015-09-08 08:05:57 +00003592 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003593 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003594 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003595
John McCall7f416cc2015-09-08 08:05:57 +00003596 // TODO: access-path TBAA?
3597 auto FieldAlignSource = getFieldAlignmentSource(Base.getAlignmentSource());
3598 return MakeAddrLValue(V, FieldType, FieldAlignSource);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003599}
3600
Chris Lattnerf53c0962010-09-06 00:11:41 +00003601LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00003602 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003603 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3604 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
Richard Smith2d988f02011-11-22 22:48:32 +00003605 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003606 if (E->getType()->isVariablyModifiedType())
3607 // make sure to emit the VLA size.
3608 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003609
John McCall7f416cc2015-09-08 08:05:57 +00003610 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003611 const Expr *InitExpr = E->getInitializer();
John McCall7f416cc2015-09-08 08:05:57 +00003612 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003613
Chad Rosier615ed1a2012-03-29 17:37:10 +00003614 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3615 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003616
3617 return Result;
3618}
3619
Richard Smithbb653bd2012-05-14 21:57:21 +00003620LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3621 if (!E->isGLValue())
3622 // Initializing an aggregate temporary in C++11: T{...}.
3623 return EmitAggExprToLValue(E);
3624
3625 // An lvalue initializer list must be initializing a reference.
Richard Smith122f88d2016-12-06 23:52:28 +00003626 assert(E->isTransparent() && "non-transparent glvalue init list");
Richard Smithbb653bd2012-05-14 21:57:21 +00003627 return EmitLValue(E->getInit(0));
3628}
3629
Richard Smithf3076ff2014-06-20 18:43:47 +00003630/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3631/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3632/// LValue is returned and the current block has been terminated.
3633static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3634 const Expr *Operand) {
3635 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3636 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3637 return None;
3638 }
3639
3640 return CGF.EmitLValue(Operand);
3641}
3642
John McCallc07a0c72011-02-17 10:25:35 +00003643LValue CodeGenFunction::
3644EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3645 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003646 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003647 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003648 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003649 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003650 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003651
Eli Friedman59954892012-01-25 05:04:17 +00003652 OpaqueValueMapping binding(*this, expr);
3653
John McCallc07a0c72011-02-17 10:25:35 +00003654 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003655 bool CondExprBool;
3656 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003657 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003658 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003659
Justin Bogneref512b92014-01-06 22:27:43 +00003660 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003661 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003662 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003663 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003664 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003665 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003666 }
3667
John McCallc07a0c72011-02-17 10:25:35 +00003668 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3669 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3670 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003671
3672 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003673 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003674
John McCall0a6bf2e2011-01-26 19:21:13 +00003675 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003676 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003677 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003678 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003679 Optional<LValue> lhs =
3680 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003681 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003682
Richard Smithf3076ff2014-06-20 18:43:47 +00003683 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003684 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003685
John McCallc07a0c72011-02-17 10:25:35 +00003686 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003687 if (lhs)
3688 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003689
John McCall0a6bf2e2011-01-26 19:21:13 +00003690 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003691 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003692 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003693 Optional<LValue> rhs =
3694 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003695 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003696 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003697 return EmitUnsupportedLValue(expr, "conditional operator");
3698 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003699
John McCallc07a0c72011-02-17 10:25:35 +00003700 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003701
Richard Smithf3076ff2014-06-20 18:43:47 +00003702 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003703 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003704 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003705 phi->addIncoming(lhs->getPointer(), lhsBlock);
3706 phi->addIncoming(rhs->getPointer(), rhsBlock);
3707 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3708 AlignmentSource alignSource =
3709 std::max(lhs->getAlignmentSource(), rhs->getAlignmentSource());
3710 return MakeAddrLValue(result, expr->getType(), alignSource);
Richard Smithf3076ff2014-06-20 18:43:47 +00003711 } else {
3712 assert((lhs || rhs) &&
3713 "both operands of glvalue conditional are throw-expressions?");
3714 return lhs ? *lhs : *rhs;
3715 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003716}
3717
Richard Smithbb653bd2012-05-14 21:57:21 +00003718/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3719/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003720/// otherwise if a cast is needed by the code generator in an lvalue context,
3721/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003722/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003723/// are permitted with aggregate result, including noop aggregate casts, and
3724/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003725LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003726 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003727 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003728 case CK_BitCast:
3729 case CK_ArrayToPointerDecay:
3730 case CK_FunctionToPointerDecay:
3731 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003732 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003733 case CK_IntegralToPointer:
3734 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003735 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003736 case CK_VectorSplat:
3737 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00003738 case CK_BooleanToSignedIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003739 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003740 case CK_IntegralToFloating:
3741 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003742 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003743 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003744 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003745 case CK_FloatingComplexToReal:
3746 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003747 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003748 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003749 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003750 case CK_IntegralComplexToReal:
3751 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003752 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003753 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003754 case CK_DerivedToBaseMemberPointer:
3755 case CK_BaseToDerivedMemberPointer:
3756 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003757 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003758 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003759 case CK_ARCProduceObject:
3760 case CK_ARCConsumeObject:
3761 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003762 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003763 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003764 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003765 case CK_IntToOCLSampler:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003766 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3767
3768 case CK_Dependent:
3769 llvm_unreachable("dependent cast kind in IR gen!");
3770
3771 case CK_BuiltinFnToFnPtr:
3772 llvm_unreachable("builtin functions are handled elsewhere");
3773
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003774 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003775 case CK_NonAtomicToAtomic:
3776 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003777 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00003778
Anders Carlsson8a01a752011-04-11 02:03:26 +00003779 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00003780 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003781 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003782 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00003783 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00003784 }
3785
John McCalle3027922010-08-25 11:45:40 +00003786 case CK_ConstructorConversion:
3787 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00003788 case CK_CPointerToObjCPointerCast:
3789 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003790 case CK_NoOp:
3791 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003792 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00003793
John McCalle3027922010-08-25 11:45:40 +00003794 case CK_UncheckedDerivedToBase:
3795 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00003796 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00003797 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003798 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003799
Anders Carlssond95f9602009-09-12 16:16:49 +00003800 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003801 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00003802
Anders Carlssond95f9602009-09-12 16:16:49 +00003803 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00003804 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00003805 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3806 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00003807
John McCall7f416cc2015-09-08 08:05:57 +00003808 return MakeAddrLValue(Base, E->getType(), LV.getAlignmentSource());
Anders Carlssond95f9602009-09-12 16:16:49 +00003809 }
John McCalle3027922010-08-25 11:45:40 +00003810 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00003811 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00003812 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00003813 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003814 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003815
Anders Carlsson8c793172009-11-23 17:57:54 +00003816 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00003817
Anders Carlsson8c793172009-11-23 17:57:54 +00003818 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00003819 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00003820 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00003821 E->path_begin(), E->path_end(),
3822 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00003823
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003824 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3825 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00003826 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003827 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00003828 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003829
Peter Collingbourned2926c92015-03-14 02:42:25 +00003830 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003831 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3832 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003833 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003834
John McCall7f416cc2015-09-08 08:05:57 +00003835 return MakeAddrLValue(Derived, E->getType(), LV.getAlignmentSource());
Eli Friedman8c98dff2009-11-16 05:48:01 +00003836 }
John McCalle3027922010-08-25 11:45:40 +00003837 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00003838 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003839 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00003840
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00003841 CGM.EmitExplicitCastExprType(CE, this);
Anders Carlsson50cb3212009-11-14 21:21:42 +00003842 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003843 Address V = Builder.CreateBitCast(LV.getAddress(),
3844 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00003845
3846 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003847 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3848 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003849 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003850
John McCall7f416cc2015-09-08 08:05:57 +00003851 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Anders Carlsson50cb3212009-11-14 21:21:42 +00003852 }
John McCalle3027922010-08-25 11:45:40 +00003853 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003854 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003855 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3856 ConvertType(E->getType()));
3857 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003858 }
Egor Churaev89831422016-12-23 14:55:49 +00003859 case CK_ZeroToOCLQueue:
3860 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003861 case CK_ZeroToOCLEvent:
3862 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00003863 }
Craig Topper99e79272013-07-26 05:59:26 +00003864
Douglas Gregorcdb466e2010-07-15 18:58:16 +00003865 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003866}
3867
John McCall1bf58462011-02-16 08:02:54 +00003868LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00003869 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00003870 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00003871}
3872
Eli Friedman7f1ff602012-04-16 03:54:45 +00003873RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003874 const FieldDecl *FD,
3875 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003876 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003877 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00003878 switch (getEvaluationKind(FT)) {
3879 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003880 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00003881 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00003882 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00003883 case TEK_Scalar:
Reid Kleckner9d031092016-05-02 22:42:34 +00003884 // This routine is used to load fields one-by-one to perform a copy, so
3885 // don't load reference fields.
3886 if (FD->getType()->isReferenceType())
3887 return RValue::get(FieldLV.getPointer());
Nick Lewycky2d84e842013-10-02 02:29:49 +00003888 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00003889 }
3890 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003891}
Douglas Gregorfe314812011-06-21 17:03:29 +00003892
Chris Lattnere47e4402007-06-01 18:02:12 +00003893//===--------------------------------------------------------------------===//
3894// Expression Emission
3895//===--------------------------------------------------------------------===//
3896
Craig Topper99e79272013-07-26 05:59:26 +00003897RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00003898 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003899 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003900 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00003901 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003902
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003903 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003904 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003905
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003906 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00003907 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3908
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003909 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
John McCallb92ab1a2016-10-26 23:46:34 +00003910 if (const CXXMethodDecl *MD =
3911 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003912 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003913
John McCallb92ab1a2016-10-26 23:46:34 +00003914 CGCallee callee = EmitCallee(E->getCallee());
Craig Topper99e79272013-07-26 05:59:26 +00003915
John McCallb92ab1a2016-10-26 23:46:34 +00003916 if (callee.isBuiltin()) {
3917 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
3918 E, ReturnValue);
Douglas Gregorad8a3362009-09-04 17:36:40 +00003919 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003920
John McCallb92ab1a2016-10-26 23:46:34 +00003921 if (callee.isPseudoDestructor()) {
3922 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
3923 }
3924
3925 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
3926}
3927
3928/// Emit a CallExpr without considering whether it might be a subclass.
3929RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
3930 ReturnValueSlot ReturnValue) {
3931 CGCallee Callee = EmitCallee(E->getCallee());
3932 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
3933}
3934
3935static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
3936 if (auto builtinID = FD->getBuiltinID()) {
3937 return CGCallee::forBuiltin(builtinID, FD);
3938 }
3939
3940 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
3941 return CGCallee::forDirect(calleePtr, FD);
3942}
3943
3944CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
3945 E = E->IgnoreParens();
3946
3947 // Look through function-to-pointer decay.
3948 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
3949 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
3950 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
3951 return EmitCallee(ICE->getSubExpr());
3952 }
3953
3954 // Resolve direct calls.
3955 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
3956 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
3957 return EmitDirectCallee(*this, FD);
3958 }
3959 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
3960 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
3961 EmitIgnoredExpr(ME->getBase());
3962 return EmitDirectCallee(*this, FD);
3963 }
3964
3965 // Look through template substitutions.
3966 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
3967 return EmitCallee(NTTP->getReplacement());
3968
3969 // Treat pseudo-destructor calls differently.
3970 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
3971 return CGCallee::forPseudoDestructor(PDE);
3972 }
3973
3974 // Otherwise, we have an indirect reference.
3975 llvm::Value *calleePtr;
3976 QualType functionType;
3977 if (auto ptrType = E->getType()->getAs<PointerType>()) {
3978 calleePtr = EmitScalarExpr(E);
3979 functionType = ptrType->getPointeeType();
3980 } else {
3981 functionType = E->getType();
3982 calleePtr = EmitLValue(E).getPointer();
3983 }
3984 assert(functionType->isFunctionType());
3985 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
3986 E->getReferencedDeclOfCallee());
3987 CGCallee callee(calleeInfo, calleePtr);
3988 return callee;
Chris Lattner9e47ead2007-08-31 04:44:06 +00003989}
3990
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003991LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00003992 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00003993 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00003994 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00003995 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00003996 return EmitLValue(E->getRHS());
3997 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003998
John McCalle3027922010-08-25 11:45:40 +00003999 if (E->getOpcode() == BO_PtrMemD ||
4000 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004001 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004002
John McCalla2342eb2010-12-05 02:00:02 +00004003 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00004004
4005 // Note that in all of these cases, __block variables need the RHS
4006 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00004007
4008 switch (getEvaluationKind(E->getType())) {
4009 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00004010 switch (E->getLHS()->getType().getObjCLifetime()) {
4011 case Qualifiers::OCL_Strong:
4012 return EmitARCStoreStrong(E, /*ignored*/ false).first;
4013
4014 case Qualifiers::OCL_Autoreleasing:
4015 return EmitARCStoreAutoreleasing(E).first;
4016
4017 // No reason to do any of these differently.
4018 case Qualifiers::OCL_None:
4019 case Qualifiers::OCL_ExplicitNone:
4020 case Qualifiers::OCL_Weak:
4021 break;
4022 }
4023
John McCalld0a30012010-12-06 06:10:02 +00004024 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00004025 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
John McCall55e1fbc2011-06-25 02:11:03 +00004026 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00004027 return LV;
4028 }
John McCall4f29b492010-11-16 23:07:28 +00004029
John McCall47fb9502013-03-07 21:37:08 +00004030 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00004031 return EmitComplexAssignmentLValue(E);
4032
John McCall47fb9502013-03-07 21:37:08 +00004033 case TEK_Aggregate:
4034 return EmitAggExprToLValue(E);
4035 }
4036 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004037}
4038
Christopher Lambd91c3d42007-12-29 05:02:41 +00004039LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00004040 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00004041
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004042 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004043 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4044 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00004045
David Majnemerced8bdf2015-02-25 17:36:15 +00004046 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004047 "Can't have a scalar return unless the return type is a "
4048 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00004049
John McCall7f416cc2015-09-08 08:05:57 +00004050 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00004051}
4052
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004053LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4054 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00004055 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004056}
4057
Anders Carlsson3be22e22009-05-30 23:23:33 +00004058LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004059 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
4060 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004061 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00004062 EmitCXXConstructExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004063 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4064 AlignmentSource::Decl);
Anders Carlsson3be22e22009-05-30 23:23:33 +00004065}
4066
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004067LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00004068CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004069 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00004070}
4071
John McCall7f416cc2015-09-08 08:05:57 +00004072Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
4073 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4074 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00004075}
4076
4077LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004078 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
4079 AlignmentSource::Decl);
Nico Webercf4ff5862012-10-11 10:13:44 +00004080}
4081
Mike Stumpc9b231c2009-11-15 08:09:41 +00004082LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004083CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004084 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00004085 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00004086 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004087 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
4088 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4089 AlignmentSource::Decl);
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004090}
4091
Eli Friedman5bc17122012-02-08 05:34:55 +00004092LValue
4093CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00004094 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00004095 EmitLambdaExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004096 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4097 AlignmentSource::Decl);
Eli Friedman5bc17122012-02-08 05:34:55 +00004098}
4099
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004100LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004101 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00004102
Anders Carlsson280e61f12010-06-21 20:59:55 +00004103 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004104 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4105 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00004106
Alp Toker314cc812014-01-25 16:55:45 +00004107 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00004108 "Can't have a scalar return unless the return type is a "
4109 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00004110
John McCall7f416cc2015-09-08 08:05:57 +00004111 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004112}
4113
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004114LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004115 Address V =
4116 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
4117 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004118}
4119
Daniel Dunbar722f4242009-04-22 05:08:15 +00004120llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004121 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004122 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004123}
4124
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004125LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4126 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004127 const ObjCIvarDecl *Ivar,
4128 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00004129 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00004130 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004131}
4132
4133LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004134 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00004135 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004136 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00004137 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004138 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004139 if (E->isArrow()) {
4140 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004141 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00004142 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004143 } else {
4144 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00004145 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004146 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00004147 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004148 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004149
Craig Topper99e79272013-07-26 05:59:26 +00004150 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00004151 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4152 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00004153 setObjCGCLValueClass(getContext(), E, LV);
4154 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00004155}
4156
Chris Lattnera4185c52009-04-25 19:35:26 +00004157LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00004158 // Can only get l-value for message expression returning aggregate type
4159 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00004160 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4161 AlignmentSource::Decl);
Chris Lattnera4185c52009-04-25 19:35:26 +00004162}
4163
John McCallb92ab1a2016-10-26 23:46:34 +00004164RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004165 const CallExpr *E, ReturnValueSlot ReturnValue,
John McCallb92ab1a2016-10-26 23:46:34 +00004166 llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00004167 // Get the actual function type. The callee type will always be a pointer to
4168 // function type or a block pointer type.
4169 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00004170 "Call must have function pointer type!");
4171
John McCallb92ab1a2016-10-26 23:46:34 +00004172 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
Samuel Antao798f11c2015-11-23 22:04:44 +00004173
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004174 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
Eric Christopher39db7262015-11-14 01:56:04 +00004175 // We can only guarantee that a function is called from the correct
4176 // context/function based on the appropriate target attributes,
4177 // so only check in the case where we have both always_inline and target
4178 // since otherwise we could be making a conditional call after a check for
4179 // the proper cpu features (and it won't cause code generation issues due to
4180 // function based code generation).
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004181 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4182 TargetDecl->hasAttr<TargetAttr>())
4183 checkTargetFeatures(E, FD);
4184
John McCall6fd4c232009-10-23 08:22:42 +00004185 CalleeType = getContext().getCanonicalType(CalleeType);
4186
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004187 const auto *FnType =
4188 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00004189
John McCallb92ab1a2016-10-26 23:46:34 +00004190 CGCallee Callee = OrigCallee;
4191
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004192 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004193 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4194 if (llvm::Constant *PrefixSig =
4195 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00004196 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004197 llvm::Constant *FTRTTIConst =
4198 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4199 llvm::Type *PrefixStructTyElems[] = {
4200 PrefixSig->getType(),
4201 FTRTTIConst->getType()
4202 };
4203 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4204 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4205
John McCallb92ab1a2016-10-26 23:46:34 +00004206 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4207
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004208 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
John McCallb92ab1a2016-10-26 23:46:34 +00004209 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004210 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004211 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00004212 llvm::Value *CalleeSig =
4213 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004214 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4215
4216 llvm::BasicBlock *Cont = createBasicBlock("cont");
4217 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4218 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4219
4220 EmitBlock(TypeCheck);
4221 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004222 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
John McCall7f416cc2015-09-08 08:05:57 +00004223 llvm::Value *CalleeRTTI =
4224 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004225 llvm::Value *CalleeRTTIMatch =
4226 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4227 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004228 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004229 EmitCheckTypeDescriptor(CalleeType)
4230 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00004231 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004232 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004233
4234 Builder.CreateBr(Cont);
4235 EmitBlock(Cont);
4236 }
4237 }
4238
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004239 // If we are checking indirect calls and this call is indirect, check that the
4240 // function pointer is a member of the bit set for the function type.
4241 if (SanOpts.has(SanitizerKind::CFIICall) &&
4242 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4243 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00004244 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004245
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004246 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004247 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004248
John McCallb92ab1a2016-10-26 23:46:34 +00004249 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4250 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004251 llvm::Value *TypeTest = Builder.CreateCall(
4252 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004253
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004254 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004255 llvm::Constant *StaticData[] = {
4256 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4257 EmitCheckSourceLocation(E->getLocStart()),
4258 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4259 };
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004260 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4261 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004262 CastedCallee, StaticData);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004263 } else {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004264 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004265 SanitizerHandler::CFICheckFail, StaticData,
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004266 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004267 }
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004268 }
4269
Daniel Dunbarc722b852008-08-30 03:02:31 +00004270 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00004271 if (Chain)
4272 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4273 CGM.getContext().VoidPtrTy);
Richard Smith762672a2016-09-28 19:09:10 +00004274
4275 // C++17 requires that we evaluate arguments to a call using assignment syntax
Richard Smitha560ccf2016-09-29 21:30:12 +00004276 // right-to-left, and that we evaluate arguments to certain other operators
4277 // left-to-right. Note that we allow this to override the order dictated by
4278 // the calling convention on the MS ABI, which means that parameter
4279 // destruction order is not necessarily reverse construction order.
4280 // FIXME: Revisit this based on C++ committee response to unimplementability.
4281 EvaluationOrder Order = EvaluationOrder::Default;
4282 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4283 if (OCE->isAssignmentOp())
4284 Order = EvaluationOrder::ForceRightToLeft;
4285 else {
4286 switch (OCE->getOperator()) {
4287 case OO_LessLess:
4288 case OO_GreaterGreater:
4289 case OO_AmpAmp:
4290 case OO_PipePipe:
4291 case OO_Comma:
4292 case OO_ArrowStar:
4293 Order = EvaluationOrder::ForceLeftToRight;
4294 break;
4295 default:
4296 break;
4297 }
4298 }
4299 }
Richard Smith762672a2016-09-28 19:09:10 +00004300
David Blaikief05779e2015-07-21 18:37:18 +00004301 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
Richard Smitha560ccf2016-09-29 21:30:12 +00004302 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
Daniel Dunbarc722b852008-08-30 03:02:31 +00004303
Peter Collingbournef7706832014-12-12 23:41:25 +00004304 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4305 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00004306
4307 // C99 6.5.2.2p6:
4308 // If the expression that denotes the called function has a type
4309 // that does not include a prototype, [the default argument
4310 // promotions are performed]. If the number of arguments does not
4311 // equal the number of parameters, the behavior is undefined. If
4312 // the function is defined with a type that includes a prototype,
4313 // and either the prototype ends with an ellipsis (, ...) or the
4314 // types of the arguments after promotion are not compatible with
4315 // the types of the parameters, the behavior is undefined. If the
4316 // function is defined with a type that does not include a
4317 // prototype, and the types of the arguments after promotion are
4318 // not compatible with those of the parameters after promotion,
4319 // the behavior is undefined [except in some trivial cases].
4320 // That is, in the general case, we should assume that a call
4321 // through an unprototyped function type works like a *non-variadic*
4322 // call. The way we make this work is to cast to the exact type
4323 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00004324 //
4325 // Chain calls use this same code path to add the invisible chain parameter
4326 // to the function type.
4327 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00004328 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00004329 CalleeTy = CalleeTy->getPointerTo();
John McCallb92ab1a2016-10-26 23:46:34 +00004330
4331 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4332 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4333 Callee.setFunctionPointer(CalleePtr);
John McCallcbc038a2011-09-21 08:08:30 +00004334 }
4335
John McCallb92ab1a2016-10-26 23:46:34 +00004336 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00004337}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004338
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004339LValue CodeGenFunction::
4340EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004341 Address BaseAddr = Address::invalid();
4342 if (E->getOpcode() == BO_PtrMemI) {
4343 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4344 } else {
4345 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4346 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004347
John McCallc134eb52010-08-31 21:07:20 +00004348 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4349
4350 const MemberPointerType *MPT
4351 = E->getRHS()->getType()->getAs<MemberPointerType>();
4352
John McCall7f416cc2015-09-08 08:05:57 +00004353 AlignmentSource AlignSource;
4354 Address MemberAddr =
4355 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT,
4356 &AlignSource);
John McCallc134eb52010-08-31 21:07:20 +00004357
John McCall7f416cc2015-09-08 08:05:57 +00004358 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), AlignSource);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004359}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004360
John McCall47fb9502013-03-07 21:37:08 +00004361/// Given the address of a temporary variable, produce an r-value of
4362/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00004363RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004364 QualType type,
4365 SourceLocation loc) {
John McCall7f416cc2015-09-08 08:05:57 +00004366 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
John McCall47fb9502013-03-07 21:37:08 +00004367 switch (getEvaluationKind(type)) {
4368 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004369 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004370 case TEK_Aggregate:
4371 return lvalue.asAggregateRValue();
4372 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004373 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004374 }
4375 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004376}
4377
Duncan Sandse81111c2012-04-10 08:23:07 +00004378void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004379 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00004380 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004381 return;
4382
Duncan Sands65229ed2012-04-16 16:29:47 +00004383 llvm::MDBuilder MDHelper(getLLVMContext());
4384 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004385
Duncan Sands6fc46192012-04-14 12:37:26 +00004386 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004387}
John McCallfe96e0b2011-11-06 09:01:30 +00004388
4389namespace {
4390 struct LValueOrRValue {
4391 LValue LV;
4392 RValue RV;
4393 };
4394}
4395
4396static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4397 const PseudoObjectExpr *E,
4398 bool forLValue,
4399 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004400 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00004401
4402 // Find the result expression, if any.
4403 const Expr *resultExpr = E->getResultExpr();
4404 LValueOrRValue result;
4405
4406 for (PseudoObjectExpr::const_semantics_iterator
4407 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4408 const Expr *semantic = *i;
4409
4410 // If this semantic expression is an opaque value, bind it
4411 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004412 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00004413
4414 // If this is the result expression, we may need to evaluate
4415 // directly into the slot.
4416 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4417 OVMA opaqueData;
4418 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00004419 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00004420 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
4421
John McCall7f416cc2015-09-08 08:05:57 +00004422 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4423 AlignmentSource::Decl);
John McCallfe96e0b2011-11-06 09:01:30 +00004424 opaqueData = OVMA::bind(CGF, ov, LV);
4425 result.RV = slot.asRValue();
4426
4427 // Otherwise, emit as normal.
4428 } else {
4429 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4430
4431 // If this is the result, also evaluate the result now.
4432 if (ov == resultExpr) {
4433 if (forLValue)
4434 result.LV = CGF.EmitLValue(ov);
4435 else
4436 result.RV = CGF.EmitAnyExpr(ov, slot);
4437 }
4438 }
4439
4440 opaques.push_back(opaqueData);
4441
4442 // Otherwise, if the expression is the result, evaluate it
4443 // and remember the result.
4444 } else if (semantic == resultExpr) {
4445 if (forLValue)
4446 result.LV = CGF.EmitLValue(semantic);
4447 else
4448 result.RV = CGF.EmitAnyExpr(semantic, slot);
4449
4450 // Otherwise, evaluate the expression in an ignored context.
4451 } else {
4452 CGF.EmitIgnoredExpr(semantic);
4453 }
4454 }
4455
4456 // Unbind all the opaques now.
4457 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4458 opaques[i].unbind(CGF);
4459
4460 return result;
4461}
4462
4463RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4464 AggValueSlot slot) {
4465 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4466}
4467
4468LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4469 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4470}