blob: 0ae725532dc45f5e105bdbcbf934d635219c3edb [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,
Yaxun Liu84744c12017-06-19 17:03:41 +000064 const Twine &Name,
65 llvm::Value *ArraySize,
66 bool CastToDefaultAddrSpace) {
67 auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
John McCall7f416cc2015-09-08 08:05:57 +000068 Alloca->setAlignment(Align.getQuantity());
Yaxun Liu84744c12017-06-19 17:03:41 +000069 llvm::Value *V = Alloca;
70 // Alloca always returns a pointer in alloca address space, which may
71 // be different from the type defined by the language. For example,
72 // in C++ the auto variables are in the default address space. Therefore
73 // cast alloca to the default address space when necessary.
74 if (CastToDefaultAddrSpace && getASTAllocaAddressSpace() != LangAS::Default) {
75 auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
76 V = getTargetHooks().performAddrSpaceCast(
77 *this, V, getASTAllocaAddressSpace(), LangAS::Default,
78 Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
79 }
80
81 return Address(V, Align);
John McCall7f416cc2015-09-08 08:05:57 +000082}
83
Yaxun Liu84744c12017-06-19 17:03:41 +000084/// CreateTempAlloca - This creates an alloca and inserts it into the entry
85/// block if \p ArraySize is nullptr, otherwise inserts it at the current
86/// insertion point of the builder.
Chris Lattner2192fe52011-07-18 04:24:23 +000087llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Yaxun Liu84744c12017-06-19 17:03:41 +000088 const Twine &Name,
89 llvm::Value *ArraySize) {
90 if (ArraySize)
91 return Builder.CreateAlloca(Ty, ArraySize, Name);
Matt Arsenault502ad602017-04-10 22:28:02 +000092 return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
Yaxun Liu84744c12017-06-19 17:03:41 +000093 ArraySize, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +000094}
Chris Lattner8394d792007-06-05 20:53:16 +000095
John McCall7f416cc2015-09-08 08:05:57 +000096/// CreateDefaultAlignTempAlloca - This creates an alloca with the
97/// default alignment of the corresponding LLVM type, which is *not*
98/// guaranteed to be related in any way to the expected alignment of
99/// an AST type that might have been lowered to Ty.
100Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
101 const Twine &Name) {
102 CharUnits Align =
103 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
104 return CreateTempAlloca(Ty, Align, Name);
105}
106
107void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
108 assert(isa<llvm::AllocaInst>(Var.getPointer()));
109 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
110 Store->setAlignment(Var.getAlignment().getQuantity());
John McCall2e6567a2010-04-22 01:10:34 +0000111 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000112 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
John McCall2e6567a2010-04-22 01:10:34 +0000113}
114
John McCall7f416cc2015-09-08 08:05:57 +0000115Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +0000116 CharUnits Align = getContext().getTypeAlignInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +0000117 return CreateTempAlloca(ConvertType(Ty), Align, Name);
Daniel Dunbard0049182010-02-16 19:44:13 +0000118}
119
Yaxun Liu84744c12017-06-19 17:03:41 +0000120Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
121 bool CastToDefaultAddrSpace) {
Daniel Dunbara7566f12010-02-09 02:48:28 +0000122 // FIXME: Should we prefer the preferred type alignment here?
Yaxun Liu84744c12017-06-19 17:03:41 +0000123 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name,
124 CastToDefaultAddrSpace);
John McCall7f416cc2015-09-08 08:05:57 +0000125}
126
127Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
Yaxun Liu84744c12017-06-19 17:03:41 +0000128 const Twine &Name,
129 bool CastToDefaultAddrSpace) {
130 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name, nullptr,
131 CastToDefaultAddrSpace);
Daniel Dunbara7566f12010-02-09 02:48:28 +0000132}
133
Chris Lattner8394d792007-06-05 20:53:16 +0000134/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
135/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000136llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000137 PGO.setCurrentStmt(E);
John McCall7a9aac22010-08-23 01:21:21 +0000138 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +0000139 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +0000140 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +0000141 }
John McCall7a9aac22010-08-23 01:21:21 +0000142
143 QualType BoolTy = getContext().BoolTy;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000144 SourceLocation Loc = E->getExprLoc();
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000145 if (!E->getType()->isAnyComplexType())
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000146 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +0000147
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000148 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
149 Loc);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000150}
151
John McCalla2342eb2010-12-05 02:00:02 +0000152/// EmitIgnoredExpr - Emit code to compute the specified expression,
153/// ignoring the result.
154void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
155 if (E->isRValue())
156 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
157
158 // Just emit it as an l-value and drop the result.
159 EmitLValue(E);
160}
161
John McCall7a626f62010-09-15 10:14:12 +0000162/// EmitAnyExpr - Emit code to compute the specified expression which
163/// can have any type. The result is returned as an RValue struct.
164/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000165/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000166RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
167 AggValueSlot aggSlot,
168 bool ignoreResult) {
John McCall47fb9502013-03-07 21:37:08 +0000169 switch (getEvaluationKind(E->getType())) {
170 case TEK_Scalar:
John McCall4e8ca4f2012-07-02 23:58:38 +0000171 return RValue::get(EmitScalarExpr(E, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000172 case TEK_Complex:
John McCall4e8ca4f2012-07-02 23:58:38 +0000173 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000174 case TEK_Aggregate:
175 if (!ignoreResult && aggSlot.isIgnored())
176 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
177 EmitAggExpr(E, aggSlot);
178 return aggSlot.asRValue();
179 }
180 llvm_unreachable("bad evaluation kind");
Chris Lattner4647a212007-08-31 22:49:20 +0000181}
182
Mike Stump4a3999f2009-09-09 13:00:44 +0000183/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
184/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000185RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
186 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000187
John McCall47fb9502013-03-07 21:37:08 +0000188 if (hasAggregateEvaluationKind(E->getType()))
John McCall7a626f62010-09-15 10:14:12 +0000189 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
190 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000191}
192
John McCall21886962010-04-21 10:05:39 +0000193/// EmitAnyExprToMem - Evaluate an expression into a given memory
194/// location.
195void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000196 Address Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000197 Qualifiers Quals,
198 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000199 // FIXME: This function should take an LValue as an argument.
John McCall47fb9502013-03-07 21:37:08 +0000200 switch (getEvaluationKind(E->getType())) {
201 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000202 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
John McCall47fb9502013-03-07 21:37:08 +0000203 /*isInit*/ false);
204 return;
205
206 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000207 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000208 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000209 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000210 AggValueSlot::IsAliased_t(!IsInit)));
John McCall47fb9502013-03-07 21:37:08 +0000211 return;
212 }
213
214 case TEK_Scalar: {
John McCall21886962010-04-21 10:05:39 +0000215 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000216 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000217 EmitStoreThroughLValue(RV, LV);
John McCall47fb9502013-03-07 21:37:08 +0000218 return;
John McCall21886962010-04-21 10:05:39 +0000219 }
John McCall47fb9502013-03-07 21:37:08 +0000220 }
221 llvm_unreachable("bad evaluation kind");
John McCall21886962010-04-21 10:05:39 +0000222}
223
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000224static void
225pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
John McCall7f416cc2015-09-08 08:05:57 +0000226 const Expr *E, Address ReferenceTemporary) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000227 // Objective-C++ ARC:
228 // If we are binding a reference to a temporary that has ownership, we
229 // need to perform retain/release operations on the temporary.
Richard Smith736a9472013-06-12 20:42:33 +0000230 //
231 // FIXME: This should be looking at E, not M.
John McCall460ce582015-10-22 18:38:17 +0000232 if (auto Lifetime = M->getType().getObjCLifetime()) {
233 switch (Lifetime) {
Richard Smith736a9472013-06-12 20:42:33 +0000234 case Qualifiers::OCL_None:
235 case Qualifiers::OCL_ExplicitNone:
236 // Carry on to normal cleanup handling.
237 break;
Sebastian Redl29526f02011-11-27 16:50:07 +0000238
Richard Smith736a9472013-06-12 20:42:33 +0000239 case Qualifiers::OCL_Autoreleasing:
240 // Nothing to do; cleaned up by an autorelease pool.
241 return;
242
243 case Qualifiers::OCL_Strong:
244 case Qualifiers::OCL_Weak:
245 switch (StorageDuration Duration = M->getStorageDuration()) {
246 case SD_Static:
247 // Note: we intentionally do not register a cleanup to release
248 // the object on program termination.
249 return;
250
251 case SD_Thread:
252 // FIXME: We should probably register a cleanup in this case.
253 return;
254
255 case SD_Automatic:
256 case SD_FullExpression:
Richard Smith736a9472013-06-12 20:42:33 +0000257 CodeGenFunction::Destroyer *Destroy;
258 CleanupKind CleanupKind;
259 if (Lifetime == Qualifiers::OCL_Strong) {
260 const ValueDecl *VD = M->getExtendingDecl();
261 bool Precise =
262 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
263 CleanupKind = CGF.getARCCleanupKind();
264 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
265 : &CodeGenFunction::destroyARCStrongImprecise;
266 } else {
267 // __weak objects always get EH cleanups; otherwise, exceptions
268 // could cause really nasty crashes instead of mere leaks.
269 CleanupKind = NormalAndEHCleanup;
270 Destroy = &CodeGenFunction::destroyARCWeak;
271 }
272 if (Duration == SD_FullExpression)
273 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000274 M->getType(), *Destroy,
Richard Smith736a9472013-06-12 20:42:33 +0000275 CleanupKind & EHCleanup);
276 else
277 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000278 M->getType(),
Richard Smith736a9472013-06-12 20:42:33 +0000279 *Destroy, CleanupKind & EHCleanup);
280 return;
281
282 case SD_Dynamic:
283 llvm_unreachable("temporary cannot have dynamic storage duration");
284 }
285 llvm_unreachable("unknown storage duration");
286 }
287 }
288
Craig Topper8a13c412014-05-21 05:09:00 +0000289 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
Richard Smith736a9472013-06-12 20:42:33 +0000290 if (const RecordType *RT =
291 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
292 // Get the destructor for the reference temporary.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000293 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith736a9472013-06-12 20:42:33 +0000294 if (!ClassDecl->hasTrivialDestructor())
295 ReferenceTemporaryDtor = ClassDecl->getDestructor();
296 }
297
298 if (!ReferenceTemporaryDtor)
299 return;
300
301 // Call the destructor for the temporary.
302 switch (M->getStorageDuration()) {
303 case SD_Static:
304 case SD_Thread: {
305 llvm::Constant *CleanupFn;
306 llvm::Constant *CleanupArg;
307 if (E->getType()->isArrayType()) {
308 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
John McCall7f416cc2015-09-08 08:05:57 +0000309 ReferenceTemporary, E->getType(),
David Blaikieebe87e12013-08-27 23:57:18 +0000310 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
311 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
Richard Smith736a9472013-06-12 20:42:33 +0000312 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
313 } else {
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000314 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
315 StructorType::Complete);
John McCall7f416cc2015-09-08 08:05:57 +0000316 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
Richard Smith736a9472013-06-12 20:42:33 +0000317 }
318 CGF.CGM.getCXXABI().registerGlobalDtor(
319 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
320 break;
321 }
322
323 case SD_FullExpression:
324 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
325 CodeGenFunction::destroyCXXObject,
326 CGF.getLangOpts().Exceptions);
327 break;
328
329 case SD_Automatic:
330 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
331 ReferenceTemporary, E->getType(),
332 CodeGenFunction::destroyCXXObject,
333 CGF.getLangOpts().Exceptions);
334 break;
335
336 case SD_Dynamic:
337 llvm_unreachable("temporary cannot have dynamic storage duration");
338 }
339}
340
Yaxun Liucbf647c2017-07-08 13:24:52 +0000341static Address createReferenceTemporary(CodeGenFunction &CGF,
342 const MaterializeTemporaryExpr *M,
343 const Expr *Inner) {
344 auto &TCG = CGF.getTargetHooks();
Richard Smith736a9472013-06-12 20:42:33 +0000345 switch (M->getStorageDuration()) {
346 case SD_FullExpression:
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000347 case SD_Automatic: {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000348 // If we have a constant temporary array or record try to promote it into a
349 // constant global under the same rules a normal constant would've been
350 // promoted. This is easier on the optimizer and generally emits fewer
351 // instructions.
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000352 QualType Ty = Inner->getType();
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000353 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000354 (Ty->isArrayType() || Ty->isRecordType()) &&
355 CGF.CGM.isTypeConstant(Ty, true))
356 if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
Yaxun Liucbf647c2017-07-08 13:24:52 +0000357 if (auto AddrSpace = CGF.getTarget().getConstantAddressSpace()) {
358 auto AS = AddrSpace.getValue();
359 auto *GV = new llvm::GlobalVariable(
360 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
361 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
362 llvm::GlobalValue::NotThreadLocal,
363 CGF.getContext().getTargetAddressSpace(AS));
364 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
365 GV->setAlignment(alignment.getQuantity());
366 llvm::Constant *C = GV;
367 if (AS != LangAS::Default)
368 C = TCG.performAddrSpaceCast(
369 CGF.CGM, GV, AS, LangAS::Default,
370 GV->getValueType()->getPointerTo(
371 CGF.getContext().getTargetAddressSpace(LangAS::Default)));
372 // FIXME: Should we put the new global into a COMDAT?
373 return Address(C, alignment);
374 }
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000375 }
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000376 return CGF.CreateMemTemp(Ty, "ref.tmp");
377 }
Richard Smith736a9472013-06-12 20:42:33 +0000378 case SD_Thread:
379 case SD_Static:
Hans Wennborgf9d865b2015-03-17 16:38:58 +0000380 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
Richard Smith736a9472013-06-12 20:42:33 +0000381
382 case SD_Dynamic:
383 llvm_unreachable("temporary can't have dynamic storage duration");
384 }
385 llvm_unreachable("unknown storage duration");
386}
387
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000388LValue CodeGenFunction::
389EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000390 const Expr *E = M->GetTemporaryExpr();
Richard Smith7c5d4dc2013-06-11 02:41:00 +0000391
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000392 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
393 // as that will cause the lifetime adjustment to be lost for ARC
John McCall460ce582015-10-22 18:38:17 +0000394 auto ownership = M->getType().getObjCLifetime();
395 if (ownership != Qualifiers::OCL_None &&
396 ownership != Qualifiers::OCL_ExplicitNone) {
John McCall7f416cc2015-09-08 08:05:57 +0000397 Address Object = createReferenceTemporary(*this, M, E);
398 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
399 Object = Address(llvm::ConstantExpr::getBitCast(Var,
400 ConvertTypeForMem(E->getType())
401 ->getPointerTo(Object.getAddressSpace())),
402 Object.getAlignment());
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000403
404 // createReferenceTemporary will promote the temporary to a global with a
405 // constant initializer if it can. It can only do this to a value of
406 // ARC-manageable type if the value is global and therefore "immune" to
407 // ref-counting operations. Therefore we have no need to emit either a
408 // dynamic initialization or a cleanup and we can just return the address
409 // of the temporary.
410 if (Var->hasInitializer())
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000411 return MakeAddrLValue(Object, M->getType(),
412 LValueBaseInfo(AlignmentSource::Decl, false));
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000413
Richard Smitha509f2f2013-06-14 03:07:01 +0000414 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
415 }
John McCall7f416cc2015-09-08 08:05:57 +0000416 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000417 LValueBaseInfo(AlignmentSource::Decl,
418 false));
Richard Smitha509f2f2013-06-14 03:07:01 +0000419
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000420 switch (getEvaluationKind(E->getType())) {
421 default: llvm_unreachable("expected scalar or aggregate expression");
422 case TEK_Scalar:
423 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
424 break;
425 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000426 EmitAggExpr(E, AggValueSlot::forAddr(Object,
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000427 E->getType().getQualifiers(),
428 AggValueSlot::IsDestructed,
429 AggValueSlot::DoesNotNeedGCBarriers,
430 AggValueSlot::IsNotAliased));
431 break;
432 }
433 }
Richard Smith736a9472013-06-12 20:42:33 +0000434
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000435 pushTemporaryCleanup(*this, M, E, Object);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000436 return RefTempDst;
Jordan Roseb1312a52013-04-11 00:58:58 +0000437 }
438
Richard Smithf3fabd22013-06-03 00:17:11 +0000439 SmallVector<const Expr *, 2> CommaLHSs;
Jordan Roseb1312a52013-04-11 00:58:58 +0000440 SmallVector<SubobjectAdjustment, 2> Adjustments;
Richard Smithf3fabd22013-06-03 00:17:11 +0000441 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
442
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000443 for (const auto &Ignored : CommaLHSs)
444 EmitIgnoredExpr(Ignored);
Richard Smithf3fabd22013-06-03 00:17:11 +0000445
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000446 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
Richard Smith736a9472013-06-12 20:42:33 +0000447 if (opaque->getType()->isRecordType()) {
448 assert(Adjustments.empty());
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000449 return EmitOpaqueValueLValue(opaque);
Jordan Roseb1312a52013-04-11 00:58:58 +0000450 }
451 }
452
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000453 // Create and initialize the reference temporary.
John McCall7f416cc2015-09-08 08:05:57 +0000454 Address Object = createReferenceTemporary(*this, M, E);
Yaxun Liucbf647c2017-07-08 13:24:52 +0000455 if (auto *Var = dyn_cast<llvm::GlobalVariable>(
456 Object.getPointer()->stripPointerCasts())) {
John McCall7f416cc2015-09-08 08:05:57 +0000457 Object = Address(llvm::ConstantExpr::getBitCast(
Yaxun Liucbf647c2017-07-08 13:24:52 +0000458 cast<llvm::Constant>(Object.getPointer()),
459 ConvertTypeForMem(E->getType())->getPointerTo()),
John McCall7f416cc2015-09-08 08:05:57 +0000460 Object.getAlignment());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000461 // If the temporary is a global and has a constant initializer or is a
462 // constant temporary that we promoted to a global, we may have already
463 // initialized it.
Richard Smitha509f2f2013-06-14 03:07:01 +0000464 if (!Var->hasInitializer()) {
465 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
466 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
467 }
468 } else {
Tim Shen421119f2016-07-01 21:08:47 +0000469 switch (M->getStorageDuration()) {
470 case SD_Automatic:
471 case SD_FullExpression:
472 if (auto *Size = EmitLifetimeStart(
473 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
474 Object.getPointer())) {
475 if (M->getStorageDuration() == SD_Automatic)
476 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
477 Object, Size);
478 else
479 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
480 Size);
481 }
482 break;
483 default:
484 break;
485 }
Richard Smitha509f2f2013-06-14 03:07:01 +0000486 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
487 }
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000488 pushTemporaryCleanup(*this, M, E, Object);
Jordan Roseb1312a52013-04-11 00:58:58 +0000489
Richard Smith736a9472013-06-12 20:42:33 +0000490 // Perform derived-to-base casts and/or field accesses, to get from the
491 // temporary object we created (and, potentially, for which we extended
492 // the lifetime) to the subobject we're binding the reference to.
493 for (unsigned I = Adjustments.size(); I != 0; --I) {
494 SubobjectAdjustment &Adjustment = Adjustments[I-1];
495 switch (Adjustment.Kind) {
496 case SubobjectAdjustment::DerivedToBaseAdjustment:
497 Object =
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000498 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
499 Adjustment.DerivedToBase.BasePath->path_begin(),
500 Adjustment.DerivedToBase.BasePath->path_end(),
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000501 /*NullCheckValue=*/ false, E->getExprLoc());
Richard Smith736a9472013-06-12 20:42:33 +0000502 break;
Richard Smithf3fabd22013-06-03 00:17:11 +0000503
Richard Smith736a9472013-06-12 20:42:33 +0000504 case SubobjectAdjustment::FieldAdjustment: {
John McCall7f416cc2015-09-08 08:05:57 +0000505 LValue LV = MakeAddrLValue(Object, E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000506 LValueBaseInfo(AlignmentSource::Decl, false));
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000507 LV = EmitLValueForField(LV, Adjustment.Field);
Richard Smith736a9472013-06-12 20:42:33 +0000508 assert(LV.isSimple() &&
509 "materialized temporary field is not a simple lvalue");
510 Object = LV.getAddress();
511 break;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000512 }
513
Richard Smith736a9472013-06-12 20:42:33 +0000514 case SubobjectAdjustment::MemberPointerAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000515 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
John McCall7f416cc2015-09-08 08:05:57 +0000516 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
517 Adjustment.Ptr.MPT);
Richard Smith736a9472013-06-12 20:42:33 +0000518 break;
519 }
520 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000521 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000522
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000523 return MakeAddrLValue(Object, M->getType(),
524 LValueBaseInfo(AlignmentSource::Decl, false));
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000525}
526
527RValue
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000528CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
529 // Emit the expression as an lvalue.
530 LValue LV = EmitLValue(E);
531 assert(LV.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000532 llvm::Value *Value = LV.getPointer();
Richard Smith736a9472013-06-12 20:42:33 +0000533
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000534 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000535 // C++11 [dcl.ref]p5 (as amended by core issue 453):
536 // If a glvalue to which a reference is directly bound designates neither
537 // an existing object or function of an appropriate type nor a region of
538 // storage of suitable size and alignment to contain an object of the
539 // reference's type, the behavior is undefined.
540 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000541 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000542 }
John McCall8680f872010-07-21 06:29:51 +0000543
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000544 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000545}
546
547
Mike Stump4a3999f2009-09-09 13:00:44 +0000548/// getAccessedFieldNo - Given an encoded value and a result number, return the
549/// input field number being accessed.
550unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000551 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000552 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
553 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000554}
555
Richard Smith4d3110a2012-10-25 02:14:12 +0000556/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
557static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
558 llvm::Value *High) {
559 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
560 llvm::Value *K47 = Builder.getInt64(47);
561 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
562 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
563 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
564 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
565 return Builder.CreateMul(B1, KMul);
566}
567
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000568bool CodeGenFunction::sanitizePerformTypeCheck() const {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000569 return SanOpts.has(SanitizerKind::Null) |
570 SanOpts.has(SanitizerKind::Alignment) |
571 SanOpts.has(SanitizerKind::ObjectSize) |
572 SanOpts.has(SanitizerKind::Vptr);
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000573}
574
Richard Smithe30752c2012-10-09 19:52:38 +0000575void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +0000576 llvm::Value *Ptr, QualType Ty,
Vedant Kumar18348ea2017-02-17 23:22:55 +0000577 CharUnits Alignment,
578 SanitizerSet SkippedChecks) {
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000579 if (!sanitizePerformTypeCheck())
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000580 return;
581
Richard Smith2d8b2942012-11-01 07:22:08 +0000582 // Don't check pointers outside the default address space. The null check
583 // isn't correct, the object-size check isn't supported by LLVM, and we can't
584 // communicate the addresses to the runtime handler for the vptr check.
John McCall7f416cc2015-09-08 08:05:57 +0000585 if (Ptr->getType()->getPointerAddressSpace())
Richard Smith2d8b2942012-11-01 07:22:08 +0000586 return;
587
Vedant Kumarc420d142017-06-16 03:27:36 +0000588 // Don't check pointers to volatile data. The behavior here is implementation-
589 // defined.
590 if (Ty.isVolatileQualified())
591 return;
592
Alexey Samsonov24cad992014-07-17 18:46:27 +0000593 SanitizerScope SanScope(this);
594
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000595 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
Craig Topper8a13c412014-05-21 05:09:00 +0000596 llvm::BasicBlock *Done = nullptr;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000597
Vedant Kumare859ebb2017-04-26 02:17:21 +0000598 // Quickly determine whether we have a pointer to an alloca. It's possible
599 // to skip null checks, and some alignment checks, for these pointers. This
600 // can reduce compile-time significantly.
601 auto PtrToAlloca =
602 dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCastsNoFollowAliases());
603
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000604 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
605 TCK == TCK_UpcastToVirtualBase;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000606 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
Vedant Kumare859ebb2017-04-26 02:17:21 +0000607 !SkippedChecks.has(SanitizerKind::Null) && !PtrToAlloca) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000608 // The glvalue must not be an empty glvalue.
John McCall7f416cc2015-09-08 08:05:57 +0000609 llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr);
Richard Smith2c5868c2013-02-13 21:18:23 +0000610
Vedant Kumardbbdda42017-04-17 22:26:10 +0000611 // The IR builder can constant-fold the null check if the pointer points to
612 // a constant.
613 bool PtrIsNonNull =
614 IsNonNull == llvm::ConstantInt::getTrue(getLLVMContext());
615
616 // Skip the null check if the pointer is known to be non-null.
617 if (!PtrIsNonNull) {
618 if (AllowNullPointers) {
619 // When performing pointer casts, it's OK if the value is null.
620 // Skip the remaining checks in that case.
621 Done = createBasicBlock("null");
622 llvm::BasicBlock *Rest = createBasicBlock("not.null");
623 Builder.CreateCondBr(IsNonNull, Rest, Done);
624 EmitBlock(Rest);
625 } else {
626 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
627 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000628 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000629 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000630
Vedant Kumar18348ea2017-02-17 23:22:55 +0000631 if (SanOpts.has(SanitizerKind::ObjectSize) &&
632 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
633 !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000634 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000635
Richard Smith69d0d262012-08-24 00:54:33 +0000636 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000637 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000638 // to check this.
Matt Arsenault2f152632013-10-07 19:00:18 +0000639 // FIXME: Get object address space
640 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
641 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smith69d0d262012-08-24 00:54:33 +0000642 llvm::Value *Min = Builder.getFalse();
George Burgess IVa63f9152017-03-21 20:09:35 +0000643 llvm::Value *NullIsUnknown = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +0000644 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
George Burgess IVa63f9152017-03-21 20:09:35 +0000645 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
646 Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}),
647 llvm::ConstantInt::get(IntPtrTy, Size));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000648 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
Richard Smithe30752c2012-10-09 19:52:38 +0000649 }
Richard Smith69d0d262012-08-24 00:54:33 +0000650
Richard Smithb1b0ab42012-11-05 22:21:05 +0000651 uint64_t AlignVal = 0;
652
Vedant Kumar18348ea2017-02-17 23:22:55 +0000653 if (SanOpts.has(SanitizerKind::Alignment) &&
654 !SkippedChecks.has(SanitizerKind::Alignment)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000655 AlignVal = Alignment.getQuantity();
656 if (!Ty->isIncompleteType() && !AlignVal)
657 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
658
Richard Smith69d0d262012-08-24 00:54:33 +0000659 // The glvalue must be suitably aligned.
Vedant Kumare859ebb2017-04-26 02:17:21 +0000660 if (AlignVal > 1 &&
661 (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000662 llvm::Value *Align =
John McCall7f416cc2015-09-08 08:05:57 +0000663 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
Richard Smithb1b0ab42012-11-05 22:21:05 +0000664 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
665 llvm::Value *Aligned =
666 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000667 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000668 }
Richard Smith69d0d262012-08-24 00:54:33 +0000669 }
670
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000671 if (Checks.size() > 0) {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000672 // Make sure we're not losing information. Alignment needs to be a power of
673 // 2
674 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
Richard Smithe30752c2012-10-09 19:52:38 +0000675 llvm::Constant *StaticData[] = {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000676 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
677 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
678 llvm::ConstantInt::get(Int8Ty, TCK)};
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000679 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData, Ptr);
Richard Smithe30752c2012-10-09 19:52:38 +0000680 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000681
Richard Smithb1b0ab42012-11-05 22:21:05 +0000682 // If possible, check that the vptr indicates that there is a subobject of
683 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000684 //
685 // C++11 [basic.life]p5,6:
686 // [For storage which does not refer to an object within its lifetime]
687 // The program has undefined behavior if:
688 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000689 // or call a non-static member function
Richard Smith4d3110a2012-10-25 02:14:12 +0000690 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000691 if (SanOpts.has(SanitizerKind::Vptr) &&
Vedant Kumar18348ea2017-02-17 23:22:55 +0000692 !SkippedChecks.has(SanitizerKind::Vptr) &&
Richard Smith2c5868c2013-02-13 21:18:23 +0000693 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000694 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
695 TCK == TCK_UpcastToVirtualBase) &&
Richard Smith4d3110a2012-10-25 02:14:12 +0000696 RD && RD->hasDefinition() && RD->isDynamicClass()) {
Richard Smith4d3110a2012-10-25 02:14:12 +0000697 // Compute a hash of the mangled name of the type.
698 //
699 // FIXME: This is not guaranteed to be deterministic! Move to a
700 // fingerprinting mechanism once LLVM provides one. For the time
701 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000702 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000703 llvm::raw_svector_ostream Out(MangledName);
704 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
705 Out);
Richard Smith4d3110a2012-10-25 02:14:12 +0000706
Alexey Samsonov84856012014-07-10 22:34:19 +0000707 // Blacklist based on the mangled type.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000708 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
709 Out.str())) {
Alexey Samsonov84856012014-07-10 22:34:19 +0000710 llvm::hash_code TypeHash = hash_value(Out.str());
Richard Smith4d3110a2012-10-25 02:14:12 +0000711
Alexey Samsonov84856012014-07-10 22:34:19 +0000712 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
713 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
714 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
John McCall7f416cc2015-09-08 08:05:57 +0000715 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000716 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
717 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
Richard Smith4d3110a2012-10-25 02:14:12 +0000718
Alexey Samsonov84856012014-07-10 22:34:19 +0000719 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
720 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
Richard Smith4d3110a2012-10-25 02:14:12 +0000721
Alexey Samsonov84856012014-07-10 22:34:19 +0000722 // Look the hash up in our cache.
723 const int CacheSize = 128;
724 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
725 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
726 "__ubsan_vptr_type_cache");
727 llvm::Value *Slot = Builder.CreateAnd(Hash,
728 llvm::ConstantInt::get(IntPtrTy,
729 CacheSize-1));
730 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
731 llvm::Value *CacheVal =
John McCall7f416cc2015-09-08 08:05:57 +0000732 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
733 getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000734
735 // If the hash isn't in the cache, call a runtime handler to perform the
736 // hard work of checking whether the vptr is for an object of the right
737 // type. This will either fill in the cache and return, or produce a
738 // diagnostic.
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000739 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
Alexey Samsonov84856012014-07-10 22:34:19 +0000740 llvm::Constant *StaticData[] = {
741 EmitCheckSourceLocation(Loc),
742 EmitCheckTypeDescriptor(Ty),
743 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
744 llvm::ConstantInt::get(Int8Ty, TCK)
745 };
John McCall7f416cc2015-09-08 08:05:57 +0000746 llvm::Value *DynamicData[] = { Ptr, Hash };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000747 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000748 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
749 DynamicData);
Alexey Samsonov84856012014-07-10 22:34:19 +0000750 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000751 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000752
753 if (Done) {
754 Builder.CreateBr(Done);
755 EmitBlock(Done);
756 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000757}
Chris Lattner4647a212007-08-31 22:49:20 +0000758
Richard Smith539e4a72013-02-23 02:53:19 +0000759/// Determine whether this expression refers to a flexible array member in a
760/// struct. We disable array bounds checks for such members.
761static bool isFlexibleArrayMemberExpr(const Expr *E) {
762 // For compatibility with existing code, we treat arrays of length 0 or
763 // 1 as flexible array members.
764 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000765 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000766 if (CAT->getSize().ugt(1))
767 return false;
768 } else if (!isa<IncompleteArrayType>(AT))
769 return false;
770
771 E = E->IgnoreParens();
772
773 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000774 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000775 // FIXME: If the base type of the member expr is not FD->getParent(),
776 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000777 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith539e4a72013-02-23 02:53:19 +0000778 RecordDecl::field_iterator FI(
779 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
780 return ++FI == FD->getParent()->field_end();
781 }
Vedant Kumare356f1a2016-10-04 20:36:04 +0000782 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
783 return IRE->getDecl()->getNextIvar() == nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000784 }
785
786 return false;
787}
788
789/// If Base is known to point to the start of an array, return the length of
790/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000791static llvm::Value *getArrayIndexingBound(
792 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000793 // For the vector indexing extension, the bound is the number of elements.
794 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
795 IndexedType = Base->getType();
796 return CGF.Builder.getInt32(VT->getNumElements());
797 }
798
799 Base = Base->IgnoreParens();
800
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000801 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000802 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
803 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
804 IndexedType = CE->getSubExpr()->getType();
805 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000806 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000807 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000808 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000809 return CGF.getVLASize(VAT).first;
810 }
811 }
812
Craig Topper8a13c412014-05-21 05:09:00 +0000813 return nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000814}
815
816void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
817 llvm::Value *Index, QualType IndexType,
818 bool Accessed) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000819 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
Richard Smith6b53e222013-10-22 22:51:04 +0000820 "should not be called unless adding bounds checks");
Alexey Samsonov24cad992014-07-17 18:46:27 +0000821 SanitizerScope SanScope(this);
Richard Smith2847b222013-02-24 01:56:24 +0000822
Richard Smith539e4a72013-02-23 02:53:19 +0000823 QualType IndexedType;
824 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
825 if (!Bound)
826 return;
827
828 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
829 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
830 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
831
832 llvm::Constant *StaticData[] = {
833 EmitCheckSourceLocation(E->getExprLoc()),
834 EmitCheckTypeDescriptor(IndexedType),
835 EmitCheckTypeDescriptor(IndexType)
836 };
837 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
838 : Builder.CreateICmpULE(IndexVal, BoundVal);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000839 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
840 SanitizerHandler::OutOfBounds, StaticData, Index);
Richard Smith539e4a72013-02-23 02:53:19 +0000841}
842
Chris Lattner116ce8f2010-01-09 21:40:03 +0000843
Chris Lattner116ce8f2010-01-09 21:40:03 +0000844CodeGenFunction::ComplexPairTy CodeGenFunction::
845EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
846 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000847 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +0000848
Chris Lattner116ce8f2010-01-09 21:40:03 +0000849 llvm::Value *NextVal;
850 if (isa<llvm::IntegerType>(InVal.first->getType())) {
851 uint64_t AmountVal = isInc ? 1 : -1;
852 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +0000853
Chris Lattner116ce8f2010-01-09 21:40:03 +0000854 // Add the inc/dec to the real part.
855 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
856 } else {
857 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
858 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
859 if (!isInc)
860 FVal.changeSign();
861 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
Craig Topper99e79272013-07-26 05:59:26 +0000862
Chris Lattner116ce8f2010-01-09 21:40:03 +0000863 // Add the inc/dec to the real part.
864 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
865 }
Craig Topper99e79272013-07-26 05:59:26 +0000866
Chris Lattner116ce8f2010-01-09 21:40:03 +0000867 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +0000868
Chris Lattner116ce8f2010-01-09 21:40:03 +0000869 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +0000870 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Craig Topper99e79272013-07-26 05:59:26 +0000871
Chris Lattner116ce8f2010-01-09 21:40:03 +0000872 // If this is a postinc, return the value read from memory, otherwise use the
873 // updated value.
874 return isPre ? IncVal : InVal;
875}
876
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000877void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
878 CodeGenFunction *CGF) {
879 // Bind VLAs in the cast type.
880 if (CGF && E->getType()->isVariablyModifiedType())
881 CGF->EmitVariablyModifiedType(E->getType());
882
883 if (CGDebugInfo *DI = getModuleDebugInfo())
884 DI->EmitExplicitCastType(E->getType());
885}
886
Chris Lattnera45c5af2007-06-02 19:47:04 +0000887//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000888// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000889//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000890
John McCall7f416cc2015-09-08 08:05:57 +0000891/// EmitPointerWithAlignment - Given an expression of pointer type, try to
892/// derive a more accurate bound on the alignment of the pointer.
893Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000894 LValueBaseInfo *BaseInfo) {
John McCall7f416cc2015-09-08 08:05:57 +0000895 // We allow this with ObjC object pointers because of fragile ABIs.
896 assert(E->getType()->isPointerType() ||
897 E->getType()->isObjCObjectPointerType());
898 E = E->IgnoreParens();
899
900 // Casts:
901 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000902 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
903 CGM.EmitExplicitCastExprType(ECE, this);
John McCall7f416cc2015-09-08 08:05:57 +0000904
905 switch (CE->getCastKind()) {
906 // Non-converting casts (but not C's implicit conversion from void*).
907 case CK_BitCast:
908 case CK_NoOp:
909 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
910 if (PtrTy->getPointeeType()->isVoidType())
911 break;
912
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000913 LValueBaseInfo InnerInfo;
914 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerInfo);
915 if (BaseInfo) *BaseInfo = InnerInfo;
John McCall7f416cc2015-09-08 08:05:57 +0000916
917 // If this is an explicit bitcast, and the source l-value is
918 // opaque, honor the alignment of the casted-to type.
919 if (isa<ExplicitCastExpr>(CE) &&
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000920 InnerInfo.getAlignmentSource() != AlignmentSource::Decl) {
921 LValueBaseInfo ExpInfo;
922 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(),
923 &ExpInfo);
924 if (BaseInfo)
925 BaseInfo->mergeForCast(ExpInfo);
926 Addr = Address(Addr.getPointer(), Align);
John McCall7f416cc2015-09-08 08:05:57 +0000927 }
928
Peter Collingbourne574975e2016-01-14 02:49:48 +0000929 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
930 CE->getCastKind() == CK_BitCast) {
Peter Collingbourneee381ff2015-09-09 00:01:31 +0000931 if (auto PT = E->getType()->getAs<PointerType>())
932 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
933 /*MayBeNull=*/true,
934 CodeGenFunction::CFITCK_UnrelatedCast,
935 CE->getLocStart());
936 }
937
John McCall7f416cc2015-09-08 08:05:57 +0000938 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
939 }
940 break;
941
942 // Array-to-pointer decay.
943 case CK_ArrayToPointerDecay:
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000944 return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000945
946 // Derived-to-base conversions.
947 case CK_UncheckedDerivedToBase:
948 case CK_DerivedToBase: {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000949 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000950 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
951 return GetAddressOfBaseClass(Addr, Derived,
952 CE->path_begin(), CE->path_end(),
953 ShouldNullCheckClassCastValue(CE),
954 CE->getExprLoc());
955 }
956
957 // TODO: Is there any reason to treat base-to-derived conversions
958 // specially?
959 default:
960 break;
961 }
962 }
963
964 // Unary &.
965 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
966 if (UO->getOpcode() == UO_AddrOf) {
967 LValue LV = EmitLValue(UO->getSubExpr());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000968 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
John McCall7f416cc2015-09-08 08:05:57 +0000969 return LV.getAddress();
970 }
971 }
972
973 // TODO: conditional operators, comma.
974
975 // Otherwise, use the alignment of the type.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000976 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000977 return Address(EmitScalarExpr(E), Align);
978}
979
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000980RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000981 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +0000982 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +0000983
984 switch (getEvaluationKind(Ty)) {
985 case TEK_Complex: {
986 llvm::Type *EltTy =
987 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +0000988 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000989 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000990 }
Craig Topper99e79272013-07-26 05:59:26 +0000991
Chris Lattner65526f02010-08-23 05:26:13 +0000992 // If this is a use of an undefined aggregate type, the aggregate must have an
993 // identifiable address. Just because the contents of the value are undefined
994 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +0000995 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000996 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +0000997 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000998 }
John McCall47fb9502013-03-07 21:37:08 +0000999
1000 case TEK_Scalar:
1001 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1002 }
1003 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +00001004}
1005
Daniel Dunbarc79407f2009-02-05 07:09:07 +00001006RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
1007 const char *Name) {
1008 ErrorUnsupported(E, Name);
1009 return GetUndefRValue(E->getType());
1010}
1011
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001012LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
1013 const char *Name) {
1014 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001015 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00001016 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
1017 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001018}
1019
Vedant Kumarffd7c882017-04-14 22:03:34 +00001020bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001021 const Expr *Base = Obj;
1022 while (!isa<CXXThisExpr>(Base)) {
1023 // The result of a dynamic_cast can be null.
1024 if (isa<CXXDynamicCastExpr>(Base))
1025 return false;
1026
1027 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1028 Base = CE->getSubExpr();
1029 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
1030 Base = PE->getSubExpr();
1031 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1032 if (UO->getOpcode() == UO_Extension)
1033 Base = UO->getSubExpr();
1034 else
1035 return false;
1036 } else {
1037 return false;
1038 }
1039 }
1040 return true;
1041}
1042
Richard Smith4d1458e2012-09-08 02:08:36 +00001043LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +00001044 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001045 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +00001046 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1047 else
1048 LV = EmitLValue(E);
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001049 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1050 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00001051 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1052 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1053 if (IsBaseCXXThis)
1054 SkippedChecks.set(SanitizerKind::Alignment, true);
1055 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001056 SkippedChecks.set(SanitizerKind::Null, true);
Vedant Kumarffd7c882017-04-14 22:03:34 +00001057 }
John McCall7f416cc2015-09-08 08:05:57 +00001058 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001059 E->getType(), LV.getAlignment(), SkippedChecks);
1060 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +00001061 return LV;
1062}
1063
Chris Lattner8394d792007-06-05 20:53:16 +00001064/// EmitLValue - Emit code to compute a designator that specifies the location
1065/// of the expression.
1066///
Mike Stump4a3999f2009-09-09 13:00:44 +00001067/// This can return one of two things: a simple address or a bitfield reference.
1068/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1069/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +00001070///
Mike Stump4a3999f2009-09-09 13:00:44 +00001071/// If this returns a bitfield reference, nothing about the pointee type of the
1072/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +00001073///
Mike Stump4a3999f2009-09-09 13:00:44 +00001074/// If this returns a normal address, and if the lvalue's C type is fixed size,
1075/// this method guarantees that the returned pointer type will point to an LLVM
1076/// type of the same size of the lvalue's type. If the lvalue has a variable
1077/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +00001078///
Chris Lattnerd7f58862007-06-02 05:24:33 +00001079LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +00001080 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +00001081 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001082 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +00001083
John McCallc109a252011-11-07 03:59:57 +00001084 case Expr::ObjCPropertyRefExprClass:
1085 llvm_unreachable("cannot emit a property reference directly");
1086
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00001087 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +00001088 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00001089 case Expr::ObjCIsaExprClass:
1090 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001091 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00001092 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001093 case Expr::CompoundAssignOperatorClass: {
1094 QualType Ty = E->getType();
1095 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1096 Ty = AT->getValueType();
1097 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +00001098 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1099 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001100 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001101 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +00001102 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001103 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001104 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001105 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00001106 case Expr::VAArgExprClass:
1107 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001108 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001109 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +00001110 case Expr::ParenExprClass:
1111 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +00001112 case Expr::GenericSelectionExprClass:
1113 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +00001114 case Expr::PredefinedExprClass:
1115 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +00001116 case Expr::StringLiteralClass:
1117 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001118 case Expr::ObjCEncodeExprClass:
1119 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +00001120 case Expr::PseudoObjectExprClass:
1121 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001122 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +00001123 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +00001124 case Expr::CXXTemporaryObjectExprClass:
1125 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001126 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1127 case Expr::CXXBindTemporaryExprClass:
1128 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +00001129 case Expr::CXXUuidofExprClass:
1130 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +00001131 case Expr::LambdaExprClass:
1132 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +00001133
1134 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001135 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +00001136 enterFullExpression(cleanups);
1137 RunCleanupsScope Scope(*this);
Reid Kleckner092d0652017-03-06 22:18:34 +00001138 LValue LV = EmitLValue(cleanups->getSubExpr());
1139 if (LV.isSimple()) {
1140 // Defend against branches out of gnu statement expressions surrounded by
1141 // cleanups.
1142 llvm::Value *V = LV.getPointer();
1143 Scope.ForceCleanup({&V});
1144 return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001145 getContext(), LV.getBaseInfo(),
Reid Kleckner092d0652017-03-06 22:18:34 +00001146 LV.getTBAAInfo());
1147 }
1148 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1149 // bitfield lvalue or some other non-simple lvalue?
1150 return LV;
John McCall08ef4662011-11-10 08:15:53 +00001151 }
1152
Anders Carlsson52ce3bb2009-11-14 01:51:50 +00001153 case Expr::CXXDefaultArgExprClass:
1154 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001155 case Expr::CXXDefaultInitExprClass: {
1156 CXXDefaultInitExprScope Scope(*this);
1157 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1158 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001159 case Expr::CXXTypeidExprClass:
1160 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001161
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001162 case Expr::ObjCMessageExprClass:
1163 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001164 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001165 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001166 case Expr::StmtExprClass:
1167 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001168 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001169 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001170 case Expr::ArraySubscriptExprClass:
1171 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001172 case Expr::OMPArraySectionExprClass:
1173 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001174 case Expr::ExtVectorElementExprClass:
1175 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001176 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001177 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001178 case Expr::CompoundLiteralExprClass:
1179 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001180 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001181 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001182 case Expr::BinaryConditionalOperatorClass:
1183 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001184 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001185 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001186 case Expr::OpaqueValueExprClass:
1187 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001188 case Expr::SubstNonTypeTemplateParmExprClass:
1189 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001190 case Expr::ImplicitCastExprClass:
1191 case Expr::CStyleCastExprClass:
1192 case Expr::CXXFunctionalCastExprClass:
1193 case Expr::CXXStaticCastExprClass:
1194 case Expr::CXXDynamicCastExprClass:
1195 case Expr::CXXReinterpretCastExprClass:
1196 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001197 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001198 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001199
Douglas Gregorfe314812011-06-21 17:03:29 +00001200 case Expr::MaterializeTemporaryExprClass:
1201 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Eric Fiseliercddaf872017-06-15 19:43:36 +00001202
1203 case Expr::CoawaitExprClass:
1204 return EmitCoawaitLValue(cast<CoawaitExpr>(E));
1205 case Expr::CoyieldExprClass:
1206 return EmitCoyieldLValue(cast<CoyieldExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001207 }
1208}
1209
John McCall71335052012-03-10 03:05:10 +00001210/// Given an object of the given canonical type, can we safely copy a
1211/// value out of it based on its initializer?
1212static bool isConstantEmittableObjectType(QualType type) {
1213 assert(type.isCanonical());
1214 assert(!type->isReferenceType());
1215
1216 // Must be const-qualified but non-volatile.
1217 Qualifiers qs = type.getLocalQualifiers();
1218 if (!qs.hasConst() || qs.hasVolatile()) return false;
1219
1220 // Otherwise, all object types satisfy this except C++ classes with
1221 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001222 if (const auto *RT = dyn_cast<RecordType>(type))
1223 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001224 if (RD->hasMutableFields() || !RD->isTrivial())
1225 return false;
1226
1227 return true;
1228}
1229
1230/// Can we constant-emit a load of a reference to a variable of the
1231/// given type? This is different from predicates like
1232/// Decl::isUsableInConstantExpressions because we do want it to apply
1233/// in situations that don't necessarily satisfy the language's rules
1234/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1235/// to do this with const float variables even if those variables
1236/// aren't marked 'constexpr'.
1237enum ConstantEmissionKind {
1238 CEK_None,
1239 CEK_AsReferenceOnly,
1240 CEK_AsValueOrReference,
1241 CEK_AsValueOnly
1242};
1243static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1244 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001245 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001246 if (isConstantEmittableObjectType(ref->getPointeeType()))
1247 return CEK_AsValueOrReference;
1248 return CEK_AsReferenceOnly;
1249 }
1250 if (isConstantEmittableObjectType(type))
1251 return CEK_AsValueOnly;
1252 return CEK_None;
1253}
1254
1255/// Try to emit a reference to the given value without producing it as
1256/// an l-value. This is actually more than an optimization: we can't
1257/// produce an l-value for variables that we never actually captured
1258/// in a block or lambda, which means const int variables or constexpr
1259/// literals or similar.
1260CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001261CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1262 ValueDecl *value = refExpr->getDecl();
1263
John McCall71335052012-03-10 03:05:10 +00001264 // The value needs to be an enum constant or a constant variable.
1265 ConstantEmissionKind CEK;
1266 if (isa<ParmVarDecl>(value)) {
1267 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001268 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001269 CEK = checkVarTypeForConstantEmission(var->getType());
1270 } else if (isa<EnumConstantDecl>(value)) {
1271 CEK = CEK_AsValueOnly;
1272 } else {
1273 CEK = CEK_None;
1274 }
1275 if (CEK == CEK_None) return ConstantEmission();
1276
John McCall71335052012-03-10 03:05:10 +00001277 Expr::EvalResult result;
1278 bool resultIsReference;
1279 QualType resultType;
1280
1281 // It's best to evaluate all the way as an r-value if that's permitted.
1282 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001283 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001284 resultIsReference = false;
1285 resultType = refExpr->getType();
1286
1287 // Otherwise, try to evaluate as an l-value.
1288 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001289 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001290 resultIsReference = true;
1291 resultType = value->getType();
1292
1293 // Failure.
1294 } else {
1295 return ConstantEmission();
1296 }
1297
1298 // In any case, if the initializer has side-effects, abandon ship.
1299 if (result.HasSideEffects)
1300 return ConstantEmission();
1301
1302 // Emit as a constant.
1303 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1304
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001305 // Make sure we emit a debug reference to the global variable.
1306 // This should probably fire even for
1307 if (isa<VarDecl>(value)) {
1308 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001309 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001310 } else {
1311 assert(isa<EnumConstantDecl>(value));
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001312 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001313 }
John McCall71335052012-03-10 03:05:10 +00001314
1315 // If we emitted a reference constant, we need to dereference that.
1316 if (resultIsReference)
1317 return ConstantEmission::forReference(C);
1318
1319 return ConstantEmission::forValue(C);
1320}
1321
Nick Lewycky2d84e842013-10-02 02:29:49 +00001322llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1323 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +00001324 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001325 lvalue.getType(), Loc, lvalue.getBaseInfo(),
John McCall7f416cc2015-09-08 08:05:57 +00001326 lvalue.getTBAAInfo(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001327 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1328 lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001329}
1330
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001331static bool hasBooleanRepresentation(QualType Ty) {
1332 if (Ty->isBooleanType())
1333 return true;
1334
1335 if (const EnumType *ET = Ty->getAs<EnumType>())
1336 return ET->getDecl()->getIntegerType()->isBooleanType();
1337
Douglas Gregor298f43d2012-04-12 20:42:30 +00001338 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1339 return hasBooleanRepresentation(AT->getValueType());
1340
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001341 return false;
1342}
1343
Richard Smith1629da92012-12-13 07:11:50 +00001344static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1345 llvm::APInt &Min, llvm::APInt &End,
Vedant Kumar4593a462016-12-09 23:48:18 +00001346 bool StrictEnums, bool IsBool) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001347 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001348 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1349 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001350 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001351 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001352
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001353 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001354 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1355 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001356 } else {
1357 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001358 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001359 unsigned Bitwidth = LTy->getScalarSizeInBits();
1360 unsigned NumNegativeBits = ED->getNumNegativeBits();
1361 unsigned NumPositiveBits = ED->getNumPositiveBits();
1362
1363 if (NumNegativeBits) {
1364 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1365 assert(NumBits <= Bitwidth);
1366 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1367 Min = -End;
1368 } else {
1369 assert(NumPositiveBits <= Bitwidth);
1370 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1371 Min = llvm::APInt(Bitwidth, 0);
1372 }
1373 }
Richard Smith1629da92012-12-13 07:11:50 +00001374 return true;
1375}
1376
1377llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1378 llvm::APInt Min, End;
Vedant Kumar4593a462016-12-09 23:48:18 +00001379 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1380 hasBooleanRepresentation(Ty)))
Craig Topper8a13c412014-05-21 05:09:00 +00001381 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001382
Duncan Sandsc720e782012-04-15 18:04:54 +00001383 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001384 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001385}
1386
Vedant Kumar5a972652017-02-27 19:46:19 +00001387bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1388 SourceLocation Loc) {
1389 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1390 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1391 if (!HasBoolCheck && !HasEnumCheck)
1392 return false;
1393
1394 bool IsBool = hasBooleanRepresentation(Ty) ||
1395 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1396 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1397 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1398 if (!NeedsBoolCheck && !NeedsEnumCheck)
1399 return false;
1400
Vedant Kumar129edab2017-03-09 16:06:27 +00001401 // Single-bit booleans don't need to be checked. Special-case this to avoid
1402 // a bit width mismatch when handling bitfield values. This is handled by
1403 // EmitFromMemory for the non-bitfield case.
1404 if (IsBool &&
1405 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1406 return false;
1407
Vedant Kumar5a972652017-02-27 19:46:19 +00001408 llvm::APInt Min, End;
1409 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1410 return true;
1411
1412 SanitizerScope SanScope(this);
1413 llvm::Value *Check;
1414 --End;
1415 if (!Min) {
1416 Check = Builder.CreateICmpULE(
1417 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1418 } else {
1419 llvm::Value *Upper = Builder.CreateICmpSLE(
1420 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1421 llvm::Value *Lower = Builder.CreateICmpSGE(
1422 Value, llvm::ConstantInt::get(getLLVMContext(), Min));
1423 Check = Builder.CreateAnd(Upper, Lower);
1424 }
1425 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1426 EmitCheckTypeDescriptor(Ty)};
1427 SanitizerMask Kind =
1428 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1429 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1430 StaticArgs, EmitCheckValue(Value));
1431 return true;
1432}
1433
John McCall7f416cc2015-09-08 08:05:57 +00001434llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1435 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001436 SourceLocation Loc,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001437 LValueBaseInfo BaseInfo,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001438 llvm::MDNode *TBAAInfo,
1439 QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001440 uint64_t TBAAOffset,
1441 bool isNontemporal) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001442 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1443 // For better performance, handle vector loads differently.
1444 if (Ty->isVectorType()) {
1445 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001446
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001447 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001448
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001449 // Handle vectors of size 3 like size 4 for better performance.
1450 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001451
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001452 // Bitcast to vec4 type.
1453 llvm::VectorType *vec4Ty =
1454 llvm::VectorType::get(VTy->getElementType(), 4);
1455 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1456 // Now load value.
1457 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001458
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001459 // Shuffle vector to get vec3.
1460 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1461 {0, 1, 2}, "extractVec");
1462 return EmitFromMemory(V, Ty);
1463 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001464 }
1465 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001466
1467 // Atomic operations have to be done on integral types.
David Majnemera38c9f12016-05-24 16:09:25 +00001468 LValue AtomicLValue =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001469 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
David Majnemera38c9f12016-05-24 16:09:25 +00001470 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1471 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001472 }
Craig Topper99e79272013-07-26 05:59:26 +00001473
John McCall7f416cc2015-09-08 08:05:57 +00001474 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001475 if (isNontemporal) {
1476 llvm::MDNode *Node = llvm::MDNode::get(
1477 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1478 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1479 }
Manman Renc451e572013-04-04 21:53:22 +00001480 if (TBAAInfo) {
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00001481 bool MayAlias = BaseInfo.getMayAlias();
1482 llvm::MDNode *TBAA = MayAlias
1483 ? CGM.getTBAAInfo(getContext().CharTy)
1484 : CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo, TBAAOffset);
1485 if (TBAA)
1486 CGM.DecorateInstructionWithTBAA(Load, TBAA, MayAlias);
Manman Renc451e572013-04-04 21:53:22 +00001487 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001488
Vedant Kumar5a972652017-02-27 19:46:19 +00001489 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1490 // In order to prevent the optimizer from throwing away the check, don't
1491 // attach range metadata to the load.
Richard Smith1629da92012-12-13 07:11:50 +00001492 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001493 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1494 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001495
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001496 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001497}
1498
John McCall3a7f6922010-10-27 20:58:56 +00001499llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1500 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001501 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001502 // This should really always be an i1, but sometimes it's already
1503 // an i8, and it's awkward to track those cases down.
1504 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001505 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1506 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1507 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001508 }
1509
1510 return Value;
1511}
1512
1513llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1514 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001515 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001516 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1517 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001518 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1519 }
1520
1521 return Value;
1522}
1523
John McCall7f416cc2015-09-08 08:05:57 +00001524void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1525 bool Volatile, QualType Ty,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001526 LValueBaseInfo BaseInfo,
John McCall7f416cc2015-09-08 08:05:57 +00001527 llvm::MDNode *TBAAInfo,
Manman Renc451e572013-04-04 21:53:22 +00001528 bool isInit, QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001529 uint64_t TBAAOffset,
1530 bool isNontemporal) {
Craig Topper99e79272013-07-26 05:59:26 +00001531
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001532 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1533 // Handle vectors differently to get better performance.
1534 if (Ty->isVectorType()) {
1535 llvm::Type *SrcTy = Value->getType();
Simon Pilgrima5dbbc62017-06-01 20:13:34 +00001536 auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001537 // Handle vec3 special.
Simon Pilgrima5dbbc62017-06-01 20:13:34 +00001538 if (VecTy && VecTy->getNumElements() == 3) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001539 // Our source is a vec3, do a shuffle vector to make it a vec4.
1540 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1541 Builder.getInt32(2),
1542 llvm::UndefValue::get(Builder.getInt32Ty())};
1543 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1544 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
1545 MaskV, "extractVec");
1546 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1547 }
1548 if (Addr.getElementType() != SrcTy) {
1549 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1550 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001551 }
1552 }
Craig Topper99e79272013-07-26 05:59:26 +00001553
John McCall3a7f6922010-10-27 20:58:56 +00001554 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001555
David Majnemera38c9f12016-05-24 16:09:25 +00001556 LValue AtomicLValue =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001557 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
David Majnemera5b195a2015-02-14 01:35:12 +00001558 if (Ty->isAtomicType() ||
David Majnemera38c9f12016-05-24 16:09:25 +00001559 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1560 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
John McCalla8ec7eb2013-03-07 21:37:17 +00001561 return;
1562 }
1563
Daniel Dunbar03816342010-08-21 02:24:36 +00001564 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001565 if (isNontemporal) {
1566 llvm::MDNode *Node =
1567 llvm::MDNode::get(Store->getContext(),
1568 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1569 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1570 }
Manman Renc451e572013-04-04 21:53:22 +00001571 if (TBAAInfo) {
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00001572 bool MayAlias = BaseInfo.getMayAlias();
1573 llvm::MDNode *TBAA = MayAlias
1574 ? CGM.getTBAAInfo(getContext().CharTy)
1575 : CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo, TBAAOffset);
1576 if (TBAA)
1577 CGM.DecorateInstructionWithTBAA(Store, TBAA, MayAlias);
Manman Renc451e572013-04-04 21:53:22 +00001578 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001579}
1580
David Chisnallfa35df62012-01-16 17:27:18 +00001581void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001582 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001583 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001584 lvalue.getType(), lvalue.getBaseInfo(),
Manman Renc451e572013-04-04 21:53:22 +00001585 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001586 lvalue.getTBAAOffset(), lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001587}
1588
Mike Stump4a3999f2009-09-09 13:00:44 +00001589/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1590/// method emits the address of the lvalue, then loads the result as an rvalue,
1591/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001592RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001593 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001594 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001595 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001596 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1597 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001598 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001599 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001600 // In MRC mode, we do a load+autorelease.
1601 if (!getLangOpts().ObjCAutoRefCount) {
1602 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1603 }
1604
1605 // In ARC mode, we load retained and then consume the value.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001606 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1607 Object = EmitObjCConsumeObject(LV.getType(), Object);
1608 return RValue::get(Object);
1609 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001610
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001611 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001612 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001613
John McCalla1dee5302010-08-22 10:59:02 +00001614 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001615 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001616 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001617
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001618 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001619 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001620 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001621 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001622 "vecext"));
1623 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001624
1625 // If this is a reference to a subset of the elements of a vector, either
1626 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001627 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001628 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001629
Renato Golin230c5eb2014-05-19 18:15:42 +00001630 // Global Register variables always invoke intrinsics
1631 if (LV.isGlobalReg())
1632 return EmitLoadOfGlobalRegLValue(LV);
1633
John McCallc109a252011-11-07 03:59:57 +00001634 assert(LV.isBitField() && "Unknown LValue type!");
Vedant Kumar129edab2017-03-09 16:06:27 +00001635 return EmitLoadOfBitfieldLValue(LV, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +00001636}
1637
Vedant Kumar129edab2017-03-09 16:06:27 +00001638RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1639 SourceLocation Loc) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001640 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001641
Daniel Dunbar3447a022010-04-13 23:34:15 +00001642 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001643 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001644
John McCall7f416cc2015-09-08 08:05:57 +00001645 Address Ptr = LV.getBitFieldAddress();
1646 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001647
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001648 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001649 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001650 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1651 if (HighBits)
1652 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1653 if (Info.Offset + HighBits)
1654 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1655 } else {
1656 if (Info.Offset)
1657 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001658 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001659 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1660 Info.Size),
1661 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001662 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001663 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Vedant Kumar129edab2017-03-09 16:06:27 +00001664 EmitScalarRangeCheck(Val, LV.getType(), Loc);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001665 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001666}
1667
Nate Begemanb699c9b2009-01-18 06:42:49 +00001668// If this is a reference to a subset of the elements of a vector, create an
1669// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001670RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001671 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1672 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001673
Nate Begemanf322eab2008-05-09 06:41:27 +00001674 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001675
1676 // If the result of the expression is a non-vector type, we must be extracting
1677 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001678 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001679 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001680 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001681 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001682 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001683 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001684
1685 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001686 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001687
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001688 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001689 for (unsigned i = 0; i != NumResultElts; ++i)
1690 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001691
Chris Lattner91c08ad2011-02-15 00:14:06 +00001692 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1693 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001694 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001695 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001696}
1697
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001698/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001699Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1700 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001701 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1702 QualType EQT = ExprVT->getElementType();
1703 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001704
John McCall7f416cc2015-09-08 08:05:57 +00001705 Address CastToPointerElement =
1706 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1707 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001708
1709 const llvm::Constant *Elts = LV.getExtVectorElts();
1710 unsigned ix = getAccessedFieldNo(0, Elts);
1711
John McCall7f416cc2015-09-08 08:05:57 +00001712 Address VectorBasePtrPlusIx =
1713 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1714 getContext().getTypeSizeInChars(EQT),
1715 "vector.elt");
1716
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001717 return VectorBasePtrPlusIx;
1718}
1719
Renato Golin230c5eb2014-05-19 18:15:42 +00001720/// @brief Load of global gamed gegisters are always calls to intrinsics.
1721RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001722 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1723 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001724 llvm::MDNode *RegName = cast<llvm::MDNode>(
1725 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001726
1727 // We accept integer and pointer types only
1728 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1729 llvm::Type *Ty = OrigTy;
1730 if (OrigTy->isPointerTy())
1731 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1732 llvm::Type *Types[] = { Ty };
1733
Renato Golin230c5eb2014-05-19 18:15:42 +00001734 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001735 llvm::Value *Call = Builder.CreateCall(
1736 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001737 if (OrigTy->isPointerTy())
1738 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001739 return RValue::get(Call);
1740}
Chris Lattner40ff7012007-08-03 16:18:34 +00001741
Chris Lattner9369a562007-06-29 16:31:29 +00001742
Chris Lattner8394d792007-06-05 20:53:16 +00001743/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1744/// lvalue, where both are guaranteed to the have the same type, and that type
1745/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001746void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001747 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001748 if (!Dst.isSimple()) {
1749 if (Dst.isVectorElt()) {
1750 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001751 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1752 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001753 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001754 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001755 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1756 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001757 return;
1758 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001759
Nate Begemance4d7fc2008-04-18 23:10:10 +00001760 // If this is an update of extended vector elements, insert them as
1761 // appropriate.
1762 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001763 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001764
Renato Golin230c5eb2014-05-19 18:15:42 +00001765 if (Dst.isGlobalReg())
1766 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1767
John McCallc109a252011-11-07 03:59:57 +00001768 assert(Dst.isBitField() && "Unknown LValue type");
1769 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001770 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001771
John McCall31168b02011-06-15 23:02:42 +00001772 // There's special magic for assigning into an ARC-qualified l-value.
1773 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1774 switch (Lifetime) {
1775 case Qualifiers::OCL_None:
1776 llvm_unreachable("present but none");
1777
1778 case Qualifiers::OCL_ExplicitNone:
1779 // nothing special
1780 break;
1781
1782 case Qualifiers::OCL_Strong:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001783 if (isInit) {
1784 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1785 break;
1786 }
John McCall55e1fbc2011-06-25 02:11:03 +00001787 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001788 return;
1789
1790 case Qualifiers::OCL_Weak:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001791 if (isInit)
1792 // Initialize and then skip the primitive store.
1793 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1794 else
1795 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001796 return;
1797
1798 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001799 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1800 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001801 // fall into the normal path
1802 break;
1803 }
1804 }
1805
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001806 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001807 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001808 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001809 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001810 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001811 return;
1812 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001813
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001814 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001815 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001816 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001817 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001818 if (Dst.isObjCIvar()) {
1819 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001820 llvm::Type *ResultType = IntPtrTy;
1821 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1822 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001823 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001824 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001825 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1826 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001827 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001828 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001829 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001830 } else if (Dst.isGlobalObjCRef()) {
1831 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1832 Dst.isThreadLocalRef());
1833 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001834 else
1835 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001836 return;
1837 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001838
Chris Lattner6278e6a2007-08-11 00:04:45 +00001839 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001840 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001841}
1842
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001843void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001844 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001845 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001846 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001847 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001848
Daniel Dunbar67aba792010-04-15 03:47:33 +00001849 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001850 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001851
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001852 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001853 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001854 /*IsSigned=*/false);
1855 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001856
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001857 // See if there are other bits in the bitfield's storage we'll need to load
1858 // and mask together with source before storing.
1859 if (Info.StorageSize != Info.Size) {
1860 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001861 llvm::Value *Val =
1862 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001863
1864 // Mask the source value as needed.
1865 if (!hasBooleanRepresentation(Dst.getType()))
1866 SrcVal = Builder.CreateAnd(SrcVal,
1867 llvm::APInt::getLowBitsSet(Info.StorageSize,
1868 Info.Size),
1869 "bf.value");
1870 MaskedVal = SrcVal;
1871 if (Info.Offset)
1872 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1873
1874 // Mask out the original value.
1875 Val = Builder.CreateAnd(Val,
1876 ~llvm::APInt::getBitsSet(Info.StorageSize,
1877 Info.Offset,
1878 Info.Offset + Info.Size),
1879 "bf.clear");
1880
1881 // Or together the unchanged values and the source value.
1882 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1883 } else {
1884 assert(Info.Offset == 0);
1885 }
1886
1887 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001888 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001889
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001890 // Return the new value of the bit-field, if requested.
1891 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001892 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001893
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001894 // Sign extend the value if needed.
1895 if (Info.IsSigned) {
1896 assert(Info.Size <= Info.StorageSize);
1897 unsigned HighBits = Info.StorageSize - Info.Size;
1898 if (HighBits) {
1899 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1900 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1901 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001902 }
1903
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001904 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1905 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001906 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001907 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001908}
1909
Nate Begemance4d7fc2008-04-18 23:10:10 +00001910void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001911 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001912 // This access turns into a read/modify/write of the vector. Load the input
1913 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001914 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1915 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001916 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001917
Chris Lattner4647a212007-08-31 22:49:20 +00001918 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001919
John McCall55e1fbc2011-06-25 02:11:03 +00001920 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001921 unsigned NumSrcElts = VTy->getNumElements();
Craig Topperf2f1a092016-07-08 02:17:35 +00001922 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001923 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001924 // Use shuffle vector is the src and destination are the same number of
1925 // elements and restore the vector mask since it is on the side it will be
1926 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001927 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001928 for (unsigned i = 0; i != NumSrcElts; ++i)
1929 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001930
Chris Lattner91c08ad2011-02-15 00:14:06 +00001931 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001932 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001933 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001934 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001935 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001936 // Extended the source vector to the same length and then shuffle it
1937 // into the destination.
1938 // FIXME: since we're shuffling with undef, can we just use the indices
1939 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001940 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001941 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001942 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001943 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001944 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001945 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001946 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001947 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001948 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001949 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001950 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001951 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001952 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001953
Joey Goulycf4143b2013-11-21 17:09:05 +00001954 // When the vector size is odd and .odd or .hi is used, the last element
1955 // of the Elts constant array will be one past the size of the vector.
1956 // Ignore the last element here, if it is greater than the mask size.
1957 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1958 NumSrcElts--;
1959
Nate Begemanb699c9b2009-01-18 06:42:49 +00001960 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001961 for (unsigned i = 0; i != NumSrcElts; ++i)
1962 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001963 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001964 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001965 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001966 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001967 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001968 }
1969 } else {
1970 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001971 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001972 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001973 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001974 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001975
John McCall7f416cc2015-09-08 08:05:57 +00001976 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1977 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001978}
1979
Renato Golin230c5eb2014-05-19 18:15:42 +00001980/// @brief Store of global named registers are always calls to intrinsics.
1981void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001982 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1983 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001984 llvm::MDNode *RegName = cast<llvm::MDNode>(
1985 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00001986 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00001987
1988 // We accept integer and pointer types only
1989 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1990 llvm::Type *Ty = OrigTy;
1991 if (OrigTy->isPointerTy())
1992 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1993 llvm::Type *Types[] = { Ty };
1994
Renato Golin230c5eb2014-05-19 18:15:42 +00001995 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1996 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00001997 if (OrigTy->isPointerTy())
1998 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00001999 Builder.CreateCall(
2000 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00002001}
2002
Eric Christopherc9e2a682014-05-20 17:10:39 +00002003// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002004// generating write-barries API. It is currently a global, ivar,
2005// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002006static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002007 LValue &LV,
2008 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002009 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002010 return;
Craig Topper99e79272013-07-26 05:59:26 +00002011
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002012 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002013 QualType ExpTy = E->getType();
2014 if (IsMemberAccess && ExpTy->isPointerType()) {
2015 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00002016 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002017 // writer-barrier conservatively.
2018 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2019 if (ExpTy->isRecordType()) {
2020 LV.setObjCIvar(false);
2021 return;
2022 }
2023 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002024 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002025 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002026 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002027 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002028 return;
2029 }
Craig Topper99e79272013-07-26 05:59:26 +00002030
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002031 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
2032 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00002033 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002034 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00002035 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002036 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002037 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002038 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002039 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002040 }
Craig Topper99e79272013-07-26 05:59:26 +00002041
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002042 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002043 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002044 return;
2045 }
Craig Topper99e79272013-07-26 05:59:26 +00002046
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002047 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002048 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002049 if (LV.isObjCIvar()) {
2050 // If cast is to a structure pointer, follow gcc's behavior and make it
2051 // a non-ivar write-barrier.
2052 QualType ExpTy = E->getType();
2053 if (ExpTy->isPointerType())
2054 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2055 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00002056 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002057 }
2058 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002059 }
Peter Collingbourne91147592011-04-15 00:35:48 +00002060
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002061 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00002062 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2063 return;
2064 }
2065
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002066 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002067 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002068 return;
2069 }
Craig Topper99e79272013-07-26 05:59:26 +00002070
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002071 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002072 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002073 return;
2074 }
John McCall31168b02011-06-15 23:02:42 +00002075
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002076 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002077 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00002078 return;
2079 }
2080
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002081 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002082 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00002083 if (LV.isObjCIvar() && !LV.isObjCArray())
2084 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002085 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00002086 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002087 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00002088 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002089 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002090 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002091 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002092 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002093
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002094 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002095 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002096 // We don't know if member is an 'ivar', but this flag is looked at
2097 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002098 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002099 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002100 }
2101}
2102
Chris Lattner3f32d692011-07-12 06:52:18 +00002103static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00002104EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00002105 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002106 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00002107 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00002108 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00002109}
2110
Alexey Bataev97720002014-11-11 04:05:39 +00002111static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00002112 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2113 llvm::Type *RealVarTy, SourceLocation Loc) {
2114 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2115 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002116 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2117 return CGF.MakeAddrLValue(Addr, T, BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +00002118}
2119
2120Address CodeGenFunction::EmitLoadOfReference(Address Addr,
2121 const ReferenceType *RefTy,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002122 LValueBaseInfo *BaseInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002123 llvm::Value *Ptr = Builder.CreateLoad(Addr);
2124 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002125 BaseInfo, /*forPointee*/ true));
John McCall7f416cc2015-09-08 08:05:57 +00002126}
2127
2128LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
2129 const ReferenceType *RefTy) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002130 LValueBaseInfo BaseInfo;
2131 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &BaseInfo);
2132 return MakeAddrLValue(Addr, RefTy->getPointeeType(), BaseInfo);
Alexey Bataev97720002014-11-11 04:05:39 +00002133}
2134
Alexey Bataev31300ed2016-02-04 11:27:03 +00002135Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2136 const PointerType *PtrTy,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002137 LValueBaseInfo *BaseInfo) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00002138 llvm::Value *Addr = Builder.CreateLoad(Ptr);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002139 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(),
2140 BaseInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00002141 /*forPointeeType=*/true));
2142}
2143
2144LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2145 const PointerType *PtrTy) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002146 LValueBaseInfo BaseInfo;
2147 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo);
2148 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00002149}
2150
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002151static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2152 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00002153 QualType T = E->getType();
2154
2155 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00002156 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2157 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00002158 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2159
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002160 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002161 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2162 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00002163 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00002164 Address Addr(V, Alignment);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002165 LValue LV;
Alexey Bataev97720002014-11-11 04:05:39 +00002166 // Emit reference to the private copy of the variable if it is an OpenMP
2167 // threadprivate variable.
2168 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00002169 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002170 E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00002171 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2172 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002173 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002174 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2175 LV = CGF.MakeAddrLValue(Addr, T, BaseInfo);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002176 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002177 setObjCGCLValueClass(CGF.getContext(), E, LV);
2178 return LV;
2179}
2180
John McCallb92ab1a2016-10-26 23:46:34 +00002181static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2182 const FunctionDecl *FD) {
2183 if (FD->hasAttr<WeakRefAttr>()) {
2184 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2185 return aliasee.getPointer();
2186 }
2187
2188 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002189 if (!FD->hasPrototype()) {
2190 if (const FunctionProtoType *Proto =
2191 FD->getType()->getAs<FunctionProtoType>()) {
2192 // Ugly case: for a K&R-style definition, the type of the definition
2193 // isn't the same as the type of a use. Correct for this with a
2194 // bitcast.
2195 QualType NoProtoType =
John McCallb92ab1a2016-10-26 23:46:34 +00002196 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2197 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2198 V = llvm::ConstantExpr::getBitCast(V,
2199 CGM.getTypes().ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002200 }
2201 }
John McCallb92ab1a2016-10-26 23:46:34 +00002202 return V;
2203}
2204
2205static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2206 const Expr *E, const FunctionDecl *FD) {
2207 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
Eli Friedmana0544d62011-12-03 04:14:32 +00002208 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002209 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2210 return CGF.MakeAddrLValue(V, E->getType(), Alignment, BaseInfo);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002211}
2212
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00002213static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2214 llvm::Value *ThisValue) {
2215 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2216 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2217 return CGF.EmitLValueForField(LV, FD);
2218}
2219
Renato Golin230c5eb2014-05-19 18:15:42 +00002220/// Named Registers are named metadata pointing to the register name
2221/// which will be read from/written to as an argument to the intrinsic
2222/// @llvm.read/write_register.
2223/// So far, only the name is being passed down, but other options such as
2224/// register type, allocation type or even optimization options could be
2225/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002226static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002227 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002228 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002229 assert(Asm->getLabel().size() < 64-Name.size() &&
2230 "Register name too big");
2231 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002232 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002233 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002234 if (M->getNumOperands() == 0) {
2235 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2236 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002237 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002238 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2239 }
John McCall7f416cc2015-09-08 08:05:57 +00002240
2241 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2242
2243 llvm::Value *Ptr =
2244 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2245 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002246}
2247
Chris Lattnerd7f58862007-06-02 05:24:33 +00002248LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002249 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002250 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002251
Renato Goline7b3d5d2014-05-27 16:46:27 +00002252 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2253 // Global Named registers access via intrinsics only
2254 if (VD->getStorageClass() == SC_Register &&
2255 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002256 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002257
Renato Goline7b3d5d2014-05-27 16:46:27 +00002258 // A DeclRefExpr for a reference initialized by a constant expression can
2259 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002260 const Expr *Init = VD->getAnyInitializer(VD);
2261 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2262 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002263 VD->checkInitIsICE() &&
2264 // Do not emit if it is private OpenMP variable.
2265 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2266 LocalDeclMap.count(VD))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002267 llvm::Constant *Val =
2268 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2269 assert(Val && "failed to emit reference constant expression");
2270 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002271
2272 // Should we be using the alignment of the constant pointer we emitted?
2273 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2274 /*pointee*/ true);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002275 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2276 return MakeAddrLValue(Address(Val, Alignment), T, BaseInfo);
Richard Smith5a1104b2012-10-20 01:38:33 +00002277 }
David Majnemer602cfe72015-01-01 09:49:44 +00002278
2279 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002280 if (E->refersToEnclosingVariableOrCapture()) {
David Majnemer602cfe72015-01-01 09:49:44 +00002281 if (auto *FD = LambdaCaptureFields.lookup(VD))
2282 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2283 else if (CapturedStmtInfo) {
Alexey Bataevac5eabb2016-11-07 11:16:04 +00002284 auto I = LocalDeclMap.find(VD);
2285 if (I != LocalDeclMap.end()) {
2286 if (auto RefTy = VD->getType()->getAs<ReferenceType>())
2287 return EmitLoadOfReferenceLValue(I->second, RefTy);
2288 return MakeAddrLValue(I->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002289 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002290 LValue CapLVal =
2291 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2292 CapturedStmtInfo->getContextValue());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002293 bool MayAlias = CapLVal.getBaseInfo().getMayAlias();
Alexey Bataevc71a4092015-09-11 10:29:41 +00002294 return MakeAddrLValue(
2295 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002296 CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl, MayAlias));
David Majnemer602cfe72015-01-01 09:49:44 +00002297 }
John McCall7f416cc2015-09-08 08:05:57 +00002298
David Majnemer602cfe72015-01-01 09:49:44 +00002299 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002300 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002301 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2302 return MakeAddrLValue(addr, T, BaseInfo);
David Majnemer602cfe72015-01-01 09:49:44 +00002303 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002304 }
2305
Eli Friedman5720e342012-01-21 04:52:58 +00002306 // FIXME: We should be able to assert this for FunctionDecls as well!
2307 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2308 // those with a valid source location.
2309 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2310 !E->getLocation().isValid()) &&
2311 "Should not use decl without marking it used!");
2312
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002313 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002314 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002315 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002316 return MakeAddrLValue(Aliasee, T,
2317 LValueBaseInfo(AlignmentSource::Decl, false));
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002318 }
2319
Renato Goline7b3d5d2014-05-27 16:46:27 +00002320 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002321 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002322 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002323 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002324
John McCall7f416cc2015-09-08 08:05:57 +00002325 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002326
John McCall7f416cc2015-09-08 08:05:57 +00002327 // The variable should generally be present in the local decl map.
2328 auto iter = LocalDeclMap.find(VD);
2329 if (iter != LocalDeclMap.end()) {
2330 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002331
John McCall7f416cc2015-09-08 08:05:57 +00002332 // Otherwise, it might be static local we haven't emitted yet for
2333 // some reason; most likely, because it's in an outer function.
2334 } else if (VD->isStaticLocal()) {
2335 addr = Address(CGM.getOrCreateStaticVarDecl(
2336 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2337 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002338
John McCall7f416cc2015-09-08 08:05:57 +00002339 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002340 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002341 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2342 }
2343
2344
2345 // Check for OpenMP threadprivate variables.
2346 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2347 return EmitThreadPrivateVarDeclLValue(
2348 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2349 E->getExprLoc());
2350 }
2351
2352 // Drill into block byref variables.
2353 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2354 if (isBlockByref) {
2355 addr = emitBlockByrefAddress(addr, VD);
2356 }
2357
2358 // Drill into reference types.
2359 LValue LV;
2360 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2361 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2362 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002363 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2364 LV = MakeAddrLValue(addr, T, BaseInfo);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002365 }
Chris Lattner3f32d692011-07-12 06:52:18 +00002366
John McCallcdda29c2013-03-13 03:10:54 +00002367 bool isLocalStorage = VD->hasLocalStorage();
2368
2369 bool NonGCable = isLocalStorage &&
2370 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002371 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002372 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002373 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002374 LV.setNonGC(true);
2375 }
John McCallcdda29c2013-03-13 03:10:54 +00002376
2377 bool isImpreciseLifetime =
2378 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2379 if (isImpreciseLifetime)
2380 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002381 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002382 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002383 }
John McCallf3a88602011-02-03 08:15:49 +00002384
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002385 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002386 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002387
Richard Smithda383632016-08-15 01:33:41 +00002388 // FIXME: While we're emitting a binding from an enclosing scope, all other
2389 // DeclRefExprs we see should be implicitly treated as if they also refer to
2390 // an enclosing scope.
2391 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2392 return EmitLValue(BD->getBinding());
2393
David Blaikie83d382b2011-09-23 05:06:16 +00002394 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002395}
Chris Lattnere47e4402007-06-01 18:02:12 +00002396
Chris Lattner8394d792007-06-05 20:53:16 +00002397LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2398 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002399 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002400 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002401
Chris Lattner0f398c42008-07-26 22:37:01 +00002402 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002403 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002404 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002405 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002406 QualType T = E->getSubExpr()->getType()->getPointeeType();
2407 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002408
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002409 LValueBaseInfo BaseInfo;
2410 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo);
2411 LValue LV = MakeAddrLValue(Addr, T, BaseInfo);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002412 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002413
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002414 // We should not generate __weak write barrier on indirect reference
2415 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2416 // But, we continue to generate __strong write barrier on indirect write
2417 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002418 if (getLangOpts().ObjC1 &&
2419 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002420 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002421 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002422 return LV;
2423 }
John McCalle3027922010-08-25 11:45:40 +00002424 case UO_Real:
2425 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002426 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002427 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002428
Richard Smith0b6b8e42012-02-18 20:53:32 +00002429 // __real is valid on scalars. This is a faster way of testing that.
2430 // __imag can only produce an rvalue on scalars.
2431 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002432 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002433 assert(E->getSubExpr()->getType()->isArithmeticType());
2434 return LV;
2435 }
2436
Alexey Bataev611b0a12016-11-07 18:15:02 +00002437 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
John McCalla2342eb2010-12-05 02:00:02 +00002438
John McCall7f416cc2015-09-08 08:05:57 +00002439 Address Component =
2440 (E->getOpcode() == UO_Real
2441 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2442 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002443 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo());
Alexey Bataev611b0a12016-11-07 18:15:02 +00002444 ElemLV.getQuals().addQualifiers(LV.getQuals());
2445 return ElemLV;
Chris Lattner595db862007-10-30 22:53:42 +00002446 }
John McCalle3027922010-08-25 11:45:40 +00002447 case UO_PreInc:
2448 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002449 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002450 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002451
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002452 if (E->getType()->isAnyComplexType())
2453 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2454 else
2455 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2456 return LV;
2457 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002458 }
Chris Lattner8394d792007-06-05 20:53:16 +00002459}
2460
Chris Lattner4347e3692007-06-06 04:54:52 +00002461LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002462 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002463 E->getType(),
2464 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattner4347e3692007-06-06 04:54:52 +00002465}
2466
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002467LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002468 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002469 E->getType(),
2470 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002471}
2472
Mike Stump4a3999f2009-09-09 13:00:44 +00002473LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002474 auto SL = E->getFunctionName();
2475 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2476 StringRef FnName = CurFn->getName();
2477 if (FnName.startswith("\01"))
2478 FnName = FnName.substr(1);
2479 StringRef NameItems[] = {
2480 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2481 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002482 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002483 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2484 std::string Name = SL->getString();
2485 if (!Name.empty()) {
2486 unsigned Discriminator =
2487 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2488 if (Discriminator)
2489 Name += "_" + Twine(Discriminator + 1).str();
2490 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002491 return MakeAddrLValue(C, E->getType(), BaseInfo);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002492 } else {
2493 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002494 return MakeAddrLValue(C, E->getType(), BaseInfo);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002495 }
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002496 }
Alexey Bataevec474782014-10-09 08:45:04 +00002497 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002498 return MakeAddrLValue(C, E->getType(), BaseInfo);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002499}
2500
Richard Smithe30752c2012-10-09 19:52:38 +00002501/// Emit a type description suitable for use by a runtime sanitizer library. The
2502/// format of a type descriptor is
2503///
2504/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002505/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002506/// \endcode
2507///
Richard Smith683398a2012-10-09 23:55:19 +00002508/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2509/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002510llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002511 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002512 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002513 return C;
2514
Richard Smithe30752c2012-10-09 19:52:38 +00002515 uint16_t TypeKind = -1;
2516 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002517
Richard Smithe30752c2012-10-09 19:52:38 +00002518 if (T->isIntegerType()) {
2519 TypeKind = 0;
2520 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002521 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002522 } else if (T->isFloatingType()) {
2523 TypeKind = 1;
2524 TypeInfo = getContext().getTypeSize(T);
2525 }
2526
2527 // Format the type name as if for a diagnostic, including quotes and
2528 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002529 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002530 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2531 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002532 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002533 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002534
2535 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002536 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2537 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002538 };
2539 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2540
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002541 auto *GV = new llvm::GlobalVariable(
2542 CGM.getModule(), Descriptor->getType(),
2543 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002544 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002545 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002546
2547 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002548 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002549
Richard Smithe30752c2012-10-09 19:52:38 +00002550 return GV;
2551}
2552
2553llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2554 llvm::Type *TargetTy = IntPtrTy;
2555
Richard Smith48366f72013-03-22 00:47:07 +00002556 // Floating-point types which fit into intptr_t are bitcast to integers
2557 // and then passed directly (after zero-extension, if necessary).
2558 if (V->getType()->isFloatingPointTy()) {
2559 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2560 if (Bits <= TargetTy->getIntegerBitWidth())
2561 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2562 Bits));
2563 }
2564
Richard Smithe30752c2012-10-09 19:52:38 +00002565 // Integers which fit in intptr_t are zero-extended and passed directly.
2566 if (V->getType()->isIntegerTy() &&
2567 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2568 return Builder.CreateZExt(V, TargetTy);
2569
2570 // Pointers are passed directly, everything else is passed by address.
2571 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002572 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002573 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002574 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002575 }
2576 return Builder.CreatePtrToInt(V, TargetTy);
2577}
2578
2579/// \brief Emit a representation of a SourceLocation for passing to a handler
2580/// in a sanitizer runtime library. The format for this data is:
2581/// \code
2582/// struct SourceLocation {
2583/// const char *Filename;
2584/// int32_t Line, Column;
2585/// };
2586/// \endcode
2587/// For an invalid SourceLocation, the Filename pointer is null.
2588llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002589 llvm::Constant *Filename;
2590 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002591
Alexey Samsonov6c124142014-07-18 17:50:06 +00002592 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2593 if (PLoc.isValid()) {
Filipe Cabecinhasab731f72016-05-12 16:51:36 +00002594 StringRef FilenameString = PLoc.getFilename();
2595
2596 int PathComponentsToStrip =
2597 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2598 if (PathComponentsToStrip < 0) {
2599 assert(PathComponentsToStrip != INT_MIN);
2600 int PathComponentsToKeep = -PathComponentsToStrip;
2601 auto I = llvm::sys::path::rbegin(FilenameString);
2602 auto E = llvm::sys::path::rend(FilenameString);
2603 while (I != E && --PathComponentsToKeep)
2604 ++I;
2605
2606 FilenameString = FilenameString.substr(I - E);
2607 } else if (PathComponentsToStrip > 0) {
2608 auto I = llvm::sys::path::begin(FilenameString);
2609 auto E = llvm::sys::path::end(FilenameString);
2610 while (I != E && PathComponentsToStrip--)
2611 ++I;
2612
2613 if (I != E)
2614 FilenameString =
2615 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2616 else
2617 FilenameString = llvm::sys::path::filename(FilenameString);
2618 }
2619
2620 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002621 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2622 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2623 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002624 Line = PLoc.getLine();
2625 Column = PLoc.getColumn();
2626 } else {
2627 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2628 Line = Column = 0;
2629 }
2630
2631 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2632 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002633
2634 return llvm::ConstantStruct::getAnon(Data);
2635}
2636
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002637namespace {
2638/// \brief Specify under what conditions this check can be recovered
2639enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002640 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002641 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002642 /// Check supports recovering, runtime has both fatal (noreturn) and
2643 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002644 Recoverable,
2645 /// Runtime conditionally aborts, always need to support recovery.
2646 AlwaysRecoverable
2647};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002648}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002649
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002650static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2651 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002652 switch (Kind) {
2653 case SanitizerKind::Vptr:
2654 return CheckRecoverableKind::AlwaysRecoverable;
2655 case SanitizerKind::Return:
2656 case SanitizerKind::Unreachable:
2657 return CheckRecoverableKind::Unrecoverable;
2658 default:
2659 return CheckRecoverableKind::Recoverable;
2660 }
2661}
2662
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002663namespace {
2664struct SanitizerHandlerInfo {
2665 char const *const Name;
2666 unsigned Version;
2667};
Saleem Abdulrasoolca6e2b42016-12-13 03:27:35 +00002668}
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002669
2670const SanitizerHandlerInfo SanitizerHandlers[] = {
2671#define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2672 LIST_SANITIZER_CHECKS
2673#undef SANITIZER_CHECK
2674};
2675
Alexey Samsonov88459522015-01-12 22:39:12 +00002676static void emitCheckHandlerCall(CodeGenFunction &CGF,
2677 llvm::FunctionType *FnType,
2678 ArrayRef<llvm::Value *> FnArgs,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002679 SanitizerHandler CheckHandler,
Alexey Samsonov88459522015-01-12 22:39:12 +00002680 CheckRecoverableKind RecoverKind, bool IsFatal,
2681 llvm::BasicBlock *ContBB) {
2682 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2683 bool NeedsAbortSuffix =
2684 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002685 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2686 const StringRef CheckName = CheckInfo.Name;
2687 std::string FnName =
2688 ("__ubsan_handle_" + CheckName +
Vedant Kumar4881bdf2016-12-12 18:47:33 +00002689 (CheckInfo.Version ? "_v" + llvm::utostr(CheckInfo.Version) : "") +
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002690 (NeedsAbortSuffix ? "_abort" : ""))
2691 .str();
Alexey Samsonov88459522015-01-12 22:39:12 +00002692 bool MayReturn =
2693 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2694
2695 llvm::AttrBuilder B;
2696 if (!MayReturn) {
2697 B.addAttribute(llvm::Attribute::NoReturn)
2698 .addAttribute(llvm::Attribute::NoUnwind);
2699 }
2700 B.addAttribute(llvm::Attribute::UWTable);
2701
2702 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2703 FnType, FnName,
Reid Klecknerde864822017-03-21 16:57:30 +00002704 llvm::AttributeList::get(CGF.getLLVMContext(),
2705 llvm::AttributeList::FunctionIndex, B),
Saleem Abdulrasool05b8fde2016-12-15 16:30:20 +00002706 /*Local=*/true);
Alexey Samsonov88459522015-01-12 22:39:12 +00002707 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2708 if (!MayReturn) {
2709 HandlerCall->setDoesNotReturn();
2710 CGF.Builder.CreateUnreachable();
2711 } else {
2712 CGF.Builder.CreateBr(ContBB);
2713 }
2714}
2715
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002716void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002717 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002718 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002719 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002720 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002721 assert(Checked.size() > 0);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002722 assert(CheckHandler >= 0 &&
2723 CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers));
2724 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
Alexey Samsonov88459522015-01-12 22:39:12 +00002725
2726 llvm::Value *FatalCond = nullptr;
2727 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002728 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002729 for (int i = 0, n = Checked.size(); i < n; ++i) {
2730 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002731 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002732 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002733 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2734 ? TrapCond
2735 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2736 ? RecoverableCond
2737 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002738 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2739 }
2740
Peter Collingbourne9881b782015-06-18 23:59:22 +00002741 if (TrapCond)
2742 EmitTrapCheck(TrapCond);
2743 if (!FatalCond && !RecoverableCond)
2744 return;
2745
Alexey Samsonov88459522015-01-12 22:39:12 +00002746 llvm::Value *JointCond;
2747 if (FatalCond && RecoverableCond)
2748 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2749 else
2750 JointCond = FatalCond ? FatalCond : RecoverableCond;
2751 assert(JointCond);
2752
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002753 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002754 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002755#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002756 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002757 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002758 "All recoverable kinds in a single check must be same!");
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002759 assert(SanOpts.has(Checked[i].second));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002760 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002761#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002762
Richard Smith4d1458e2012-09-08 02:08:36 +00002763 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002764 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2765 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002766 // Give hint that we very much don't expect to execute the handler
2767 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2768 llvm::MDBuilder MDHelper(getLLVMContext());
2769 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2770 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002771 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002772
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002773 // Handler functions take an i8* pointing to the (handler-specific) static
2774 // information block, followed by a sequence of intptr_t arguments
2775 // representing operand values.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002776 SmallVector<llvm::Value *, 4> Args;
2777 SmallVector<llvm::Type *, 4> ArgTypes;
Richard Smithe30752c2012-10-09 19:52:38 +00002778 Args.reserve(DynamicArgs.size() + 1);
2779 ArgTypes.reserve(DynamicArgs.size() + 1);
2780
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002781 // Emit handler arguments and create handler function type.
2782 if (!StaticArgs.empty()) {
2783 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2784 auto *InfoPtr =
2785 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2786 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002787 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002788 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2789 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2790 ArgTypes.push_back(Int8PtrTy);
2791 }
2792
Richard Smithe30752c2012-10-09 19:52:38 +00002793 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2794 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2795 ArgTypes.push_back(IntPtrTy);
2796 }
2797
2798 llvm::FunctionType *FnType =
2799 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002800
Alexey Samsonov88459522015-01-12 22:39:12 +00002801 if (!FatalCond || !RecoverableCond) {
2802 // Simple case: we need to generate a single handler call, either
2803 // fatal, or non-fatal.
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002804 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
Alexey Samsonov88459522015-01-12 22:39:12 +00002805 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002806 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002807 // Emit two handler calls: first one for set of unrecoverable checks,
2808 // another one for recoverable.
2809 llvm::BasicBlock *NonFatalHandlerBB =
2810 createBasicBlock("non_fatal." + CheckName);
2811 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2812 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2813 EmitBlock(FatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002814 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
Alexey Samsonov88459522015-01-12 22:39:12 +00002815 NonFatalHandlerBB);
2816 EmitBlock(NonFatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002817 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
Alexey Samsonov88459522015-01-12 22:39:12 +00002818 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002819 }
Richard Smithe30752c2012-10-09 19:52:38 +00002820
Richard Smith4d1458e2012-09-08 02:08:36 +00002821 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002822}
2823
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002824void CodeGenFunction::EmitCfiSlowPathCheck(
2825 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2826 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002827 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2828
2829 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2830 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2831
2832 llvm::MDBuilder MDHelper(getLLVMContext());
2833 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2834 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2835
2836 EmitBlock(CheckBB);
2837
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002838 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2839
2840 llvm::CallInst *CheckCall;
2841 if (WithDiag) {
2842 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2843 auto *InfoPtr =
2844 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2845 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002846 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002847 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2848
2849 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2850 "__cfi_slowpath_diag",
2851 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2852 false));
2853 CheckCall = Builder.CreateCall(
2854 SlowPathDiagFn,
2855 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2856 } else {
2857 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2858 "__cfi_slowpath",
2859 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2860 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2861 }
2862
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002863 CheckCall->setDoesNotThrow();
2864
2865 EmitBlock(Cont);
2866}
2867
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +00002868// Emit a stub for __cfi_check function so that the linker knows about this
2869// symbol in LTO mode.
2870void CodeGenFunction::EmitCfiCheckStub() {
2871 llvm::Module *M = &CGM.getModule();
2872 auto &Ctx = M->getContext();
2873 llvm::Function *F = llvm::Function::Create(
2874 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
2875 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
2876 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
2877 // FIXME: consider emitting an intrinsic call like
2878 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
2879 // which can be lowered in CrossDSOCFI pass to the actual contents of
2880 // __cfi_check. This would allow inlining of __cfi_check calls.
2881 llvm::CallInst::Create(
2882 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
2883 llvm::ReturnInst::Create(Ctx, nullptr, BB);
2884}
2885
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002886// This function is basically a switch over the CFI failure kind, which is
2887// extracted from CFICheckFailData (1st function argument). Each case is either
2888// llvm.trap or a call to one of the two runtime handlers, based on
2889// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2890// failure kind) traps, but this should really never happen. CFICheckFailData
2891// can be nullptr if the calling module has -fsanitize-trap behavior for this
2892// check kind; in this case __cfi_check_fail traps as well.
2893void CodeGenFunction::EmitCfiCheckFail() {
2894 SanitizerScope SanScope(this);
2895 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002896 ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
2897 ImplicitParamDecl::Other);
2898 ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
2899 ImplicitParamDecl::Other);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002900 Args.push_back(&ArgData);
2901 Args.push_back(&ArgAddr);
2902
John McCallc56a8b32016-03-11 04:30:31 +00002903 const CGFunctionInfo &FI =
2904 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002905
2906 llvm::Function *F = llvm::Function::Create(
2907 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2908 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2909 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2910
2911 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2912 SourceLocation());
2913
2914 llvm::Value *Data =
2915 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2916 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2917 llvm::Value *Addr =
2918 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2919 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2920
2921 // Data == nullptr means the calling module has trap behaviour for this check.
2922 llvm::Value *DataIsNotNullPtr =
2923 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2924 EmitTrapCheck(DataIsNotNullPtr);
2925
2926 llvm::StructType *SourceLocationTy =
Serge Guelton1d993272017-05-09 19:31:30 +00002927 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002928 llvm::StructType *CfiCheckFailDataTy =
Serge Guelton1d993272017-05-09 19:31:30 +00002929 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002930
2931 llvm::Value *V = Builder.CreateConstGEP2_32(
2932 CfiCheckFailDataTy,
2933 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2934 0);
2935 Address CheckKindAddr(V, getIntAlign());
2936 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2937
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002938 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2939 CGM.getLLVMContext(),
2940 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2941 llvm::Value *ValidVtable = Builder.CreateZExt(
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002942 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002943 {Addr, AllVtables}),
2944 IntPtrTy);
2945
Evgeniy Stepanov4d3b0872016-01-25 23:45:37 +00002946 const std::pair<int, SanitizerMask> CheckKinds[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002947 {CFITCK_VCall, SanitizerKind::CFIVCall},
2948 {CFITCK_NVCall, SanitizerKind::CFINVCall},
2949 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
2950 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
2951 {CFITCK_ICall, SanitizerKind::CFIICall}};
2952
2953 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
2954 for (auto CheckKindMaskPair : CheckKinds) {
2955 int Kind = CheckKindMaskPair.first;
2956 SanitizerMask Mask = CheckKindMaskPair.second;
2957 llvm::Value *Cond =
2958 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002959 if (CGM.getLangOpts().Sanitize.has(Mask))
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002960 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002961 {Data, Addr, ValidVtable});
2962 else
2963 EmitTrapCheck(Cond);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002964 }
2965
2966 FinishFunction();
2967 // The only reference to this function will be created during LTO link.
2968 // Make sure it survives until then.
2969 CGM.addUsedGlobal(F);
2970}
2971
Chad Rosierae229d52013-01-29 23:31:22 +00002972void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00002973 llvm::BasicBlock *Cont = createBasicBlock("cont");
2974
2975 // If we're optimizing, collapse all calls to trap down to just one per
2976 // function to save on code size.
2977 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2978 TrapBB = createBasicBlock("trap");
2979 Builder.CreateCondBr(Checked, Cont, TrapBB);
2980 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002981 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00002982 TrapCall->setDoesNotReturn();
2983 TrapCall->setDoesNotThrow();
2984 Builder.CreateUnreachable();
2985 } else {
2986 Builder.CreateCondBr(Checked, Cont, TrapBB);
2987 }
2988
2989 EmitBlock(Cont);
2990}
2991
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002992llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00002993 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002994
Amaury Sechet21f51b32016-09-09 04:42:49 +00002995 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
2996 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
2997 CGM.getCodeGenOpts().TrapFuncName);
Reid Klecknerde864822017-03-21 16:57:30 +00002998 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
Amaury Sechet21f51b32016-09-09 04:42:49 +00002999 }
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003000
3001 return TrapCall;
3002}
3003
John McCall7f416cc2015-09-08 08:05:57 +00003004Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003005 LValueBaseInfo *BaseInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00003006 assert(E->getType()->isArrayType() &&
3007 "Array to pointer decay must have array source type!");
3008
3009 // Expressions of array type can't be bitfields or vector elements.
3010 LValue LV = EmitLValue(E);
3011 Address Addr = LV.getAddress();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003012 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
John McCall7f416cc2015-09-08 08:05:57 +00003013
3014 // If the array type was an incomplete type, we need to make sure
3015 // the decay ends up being the right type.
3016 llvm::Type *NewTy = ConvertType(E->getType());
3017 Addr = Builder.CreateElementBitCast(Addr, NewTy);
3018
3019 // Note that VLA pointers are always decayed, so we don't need to do
3020 // anything here.
3021 if (!E->getType()->isVariableArrayType()) {
3022 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3023 "Expected pointer to array");
3024 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
3025 }
3026
3027 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
3028 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
3029}
3030
Chris Lattner6c5abe82010-06-26 23:03:20 +00003031/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
3032/// array to pointer, return the array subexpression.
3033static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
3034 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003035 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00003036 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00003037 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00003038
Chris Lattner6c5abe82010-06-26 23:03:20 +00003039 // If this is a decay from variable width array, bail out.
3040 const Expr *SubExpr = CE->getSubExpr();
3041 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00003042 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00003043
Chris Lattner6c5abe82010-06-26 23:03:20 +00003044 return SubExpr;
3045}
3046
John McCall7f416cc2015-09-08 08:05:57 +00003047static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3048 llvm::Value *ptr,
3049 ArrayRef<llvm::Value*> indices,
3050 bool inbounds,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003051 bool signedIndices,
Vedant Kumara125eb52017-06-01 19:22:18 +00003052 SourceLocation loc,
John McCall7f416cc2015-09-08 08:05:57 +00003053 const llvm::Twine &name = "arrayidx") {
3054 if (inbounds) {
Vedant Kumar175b6d12017-07-13 20:55:26 +00003055 return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices,
3056 CodeGenFunction::NotSubtraction, loc,
3057 name);
John McCall7f416cc2015-09-08 08:05:57 +00003058 } else {
3059 return CGF.Builder.CreateGEP(ptr, indices, name);
3060 }
3061}
3062
3063static CharUnits getArrayElementAlign(CharUnits arrayAlign,
3064 llvm::Value *idx,
3065 CharUnits eltSize) {
3066 // If we have a constant index, we can use the exact offset of the
3067 // element we're accessing.
3068 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3069 CharUnits offset = constantIdx->getZExtValue() * eltSize;
3070 return arrayAlign.alignmentAtOffset(offset);
3071
3072 // Otherwise, use the worst-case alignment for any element.
3073 } else {
3074 return arrayAlign.alignmentOfArrayElement(eltSize);
3075 }
3076}
3077
3078static QualType getFixedSizeElementType(const ASTContext &ctx,
3079 const VariableArrayType *vla) {
3080 QualType eltType;
3081 do {
3082 eltType = vla->getElementType();
3083 } while ((vla = ctx.getAsVariableArrayType(eltType)));
3084 return eltType;
3085}
3086
3087static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
Vedant Kumara125eb52017-06-01 19:22:18 +00003088 ArrayRef<llvm::Value *> indices,
John McCall7f416cc2015-09-08 08:05:57 +00003089 QualType eltType, bool inbounds,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003090 bool signedIndices, SourceLocation loc,
John McCall7f416cc2015-09-08 08:05:57 +00003091 const llvm::Twine &name = "arrayidx") {
3092 // All the indices except that last must be zero.
3093#ifndef NDEBUG
3094 for (auto idx : indices.drop_back())
3095 assert(isa<llvm::ConstantInt>(idx) &&
3096 cast<llvm::ConstantInt>(idx)->isZero());
3097#endif
3098
3099 // Determine the element size of the statically-sized base. This is
3100 // the thing that the indices are expressed in terms of.
3101 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3102 eltType = getFixedSizeElementType(CGF.getContext(), vla);
3103 }
3104
3105 // We can use that to compute the best alignment of the element.
3106 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3107 CharUnits eltAlign =
3108 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3109
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003110 llvm::Value *eltPtr = emitArraySubscriptGEP(
3111 CGF, addr.getPointer(), indices, inbounds, signedIndices, loc, name);
John McCall7f416cc2015-09-08 08:05:57 +00003112 return Address(eltPtr, eltAlign);
3113}
3114
Richard Smith539e4a72013-02-23 02:53:19 +00003115LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3116 bool Accessed) {
Richard Smith9e67b992016-09-26 23:49:47 +00003117 // The index must always be an integer, which is not an aggregate. Emit it
3118 // in lexical order (this complexity is, sadly, required by C++17).
3119 llvm::Value *IdxPre =
3120 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003121 bool SignedIndices = false;
Richard Smith40885712016-09-27 00:53:24 +00003122 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
Richard Smith9e67b992016-09-26 23:49:47 +00003123 auto *Idx = IdxPre;
3124 if (E->getLHS() != E->getIdx()) {
3125 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3126 Idx = EmitScalarExpr(E->getIdx());
3127 }
Eli Friedman07bbeca2009-06-06 19:09:26 +00003128
Richard Smith9e67b992016-09-26 23:49:47 +00003129 QualType IdxTy = E->getIdx()->getType();
3130 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003131 SignedIndices |= IdxSigned;
Richard Smith9e67b992016-09-26 23:49:47 +00003132
3133 if (SanOpts.has(SanitizerKind::ArrayBounds))
3134 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3135
3136 // Extend or truncate the index type to 32 or 64-bits.
3137 if (Promote && Idx->getType() != IntPtrTy)
3138 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3139
3140 return Idx;
3141 };
3142 IdxPre = nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +00003143
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003144 // If the base is a vector type, then we are forming a vector element lvalue
3145 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003146 if (E->getBase()->getType()->isVectorType() &&
3147 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003148 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00003149 LValue LHS = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003150 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
Ted Kremenekc81614d2007-08-20 16:18:38 +00003151 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Eli Friedman327944b2008-06-13 23:01:12 +00003152 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
John McCall7f416cc2015-09-08 08:05:57 +00003153 E->getBase()->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003154 LHS.getBaseInfo());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003155 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003156
John McCall7f416cc2015-09-08 08:05:57 +00003157 // All the other cases basically behave like simple offsetting.
3158
John McCall7f416cc2015-09-08 08:05:57 +00003159 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003160 if (isa<ExtVectorElementExpr>(E->getBase())) {
3161 LValue LV = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003162 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003163 Address Addr = EmitExtVectorElementLValue(LV);
3164
3165 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
Vedant Kumara125eb52017-06-01 19:22:18 +00003166 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003167 SignedIndices, E->getExprLoc());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003168 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo());
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003169 }
John McCall7f416cc2015-09-08 08:05:57 +00003170
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003171 LValueBaseInfo BaseInfo;
John McCall7f416cc2015-09-08 08:05:57 +00003172 Address Addr = Address::invalid();
3173 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003174 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00003175 // The base must be a pointer, which is not an aggregate. Emit
3176 // it. It needs to be emitted first in case it's what captures
3177 // the VLA bounds.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003178 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003179 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Mike Stump4a3999f2009-09-09 13:00:44 +00003180
John McCall23c29fe2011-06-24 21:55:10 +00003181 // The element count here is the total number of non-VLA elements.
3182 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00003183
John McCall77527a82011-06-25 01:32:37 +00003184 // Effectively, the multiply by the VLA size is part of the GEP.
3185 // GEP indexes are signed, and scaling an index isn't permitted to
3186 // signed-overflow, so we use the same semantics for our explicit
3187 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003188 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00003189 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003190 } else {
3191 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003192 }
John McCall7f416cc2015-09-08 08:05:57 +00003193
3194 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003195 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003196 SignedIndices, E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00003197
Chris Lattner6c5abe82010-06-26 23:03:20 +00003198 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3199 // Indexing over an interface, as in "NSString *P; P[4];"
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003200
John McCall7f416cc2015-09-08 08:05:57 +00003201 // Emit the base pointer.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003202 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003203 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3204
3205 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3206 llvm::Value *InterfaceSizeVal =
3207 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3208
3209 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
John McCall7f416cc2015-09-08 08:05:57 +00003210
3211 // We don't necessarily build correct LLVM struct types for ObjC
3212 // interfaces, so we can't rely on GEP to do this scaling
3213 // correctly, so we need to cast to i8*. FIXME: is this actually
3214 // true? A lot of other things in the fragile ABI would break...
3215 llvm::Type *OrigBaseTy = Addr.getType();
3216 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3217
3218 // Do the GEP.
3219 CharUnits EltAlign =
3220 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003221 llvm::Value *EltPtr =
3222 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false,
3223 SignedIndices, E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00003224 Addr = Address(EltPtr, EltAlign);
3225
3226 // Cast back.
3227 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00003228 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3229 // If this is A[i] where A is an array, the frontend will have decayed the
3230 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3231 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3232 // "gep x, i" here. Emit one "gep A, 0, i".
3233 assert(Array->getType()->isArrayType() &&
3234 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00003235 LValue ArrayLV;
3236 // For simple multidimensional array indexing, set the 'accessed' flag for
3237 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003238 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00003239 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3240 else
3241 ArrayLV = EmitLValue(Array);
Richard Smith9e67b992016-09-26 23:49:47 +00003242 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Craig Topper99e79272013-07-26 05:59:26 +00003243
Daniel Dunbar82634272011-04-01 00:49:43 +00003244 // Propagate the alignment from the array itself to the result.
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003245 Addr = emitArraySubscriptGEP(
3246 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3247 E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3248 E->getExprLoc());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003249 BaseInfo = ArrayLV.getBaseInfo();
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003250 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003251 // The base must be a pointer; emit it with an estimate of its alignment.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003252 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003253 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003254 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003255 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003256 SignedIndices, E->getExprLoc());
Anders Carlsson3d312f82008-12-21 00:11:23 +00003257 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003258
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003259 LValue LV = MakeAddrLValue(Addr, E->getType(), BaseInfo);
Mike Stump4a3999f2009-09-09 13:00:44 +00003260
John McCall7f416cc2015-09-08 08:05:57 +00003261 // TODO: Preserve/extend path TBAA metadata?
John McCall8ccfcb52009-09-24 19:53:00 +00003262
Richard Smith9c6890a2012-11-01 22:30:59 +00003263 if (getLangOpts().ObjC1 &&
3264 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00003265 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00003266 setObjCGCLValueClass(getContext(), E, LV);
3267 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00003268 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00003269}
3270
Alexey Bataev31300ed2016-02-04 11:27:03 +00003271static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003272 LValueBaseInfo &BaseInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003273 QualType BaseTy, QualType ElTy,
3274 bool IsLowerBound) {
3275 LValue BaseLVal;
3276 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3277 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3278 if (BaseTy->isArrayType()) {
3279 Address Addr = BaseLVal.getAddress();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003280 BaseInfo = BaseLVal.getBaseInfo();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003281
3282 // If the array type was an incomplete type, we need to make sure
3283 // the decay ends up being the right type.
3284 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3285 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3286
3287 // Note that VLA pointers are always decayed, so we don't need to do
3288 // anything here.
3289 if (!BaseTy->isVariableArrayType()) {
3290 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3291 "Expected pointer to array");
3292 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3293 "arraydecay");
3294 }
3295
3296 return CGF.Builder.CreateElementBitCast(Addr,
3297 CGF.ConvertTypeForMem(ElTy));
3298 }
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003299 LValueBaseInfo TypeInfo;
3300 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &TypeInfo);
3301 BaseInfo.mergeForCast(TypeInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003302 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3303 }
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003304 return CGF.EmitPointerWithAlignment(Base, &BaseInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003305}
3306
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003307LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3308 bool IsLowerBound) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003309 QualType BaseTy;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003310 if (auto *ASE =
3311 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
Alexey Bataev31300ed2016-02-04 11:27:03 +00003312 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003313 else
Alexey Bataev31300ed2016-02-04 11:27:03 +00003314 BaseTy = E->getBase()->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003315 QualType ResultExprTy;
3316 if (auto *AT = getContext().getAsArrayType(BaseTy))
3317 ResultExprTy = AT->getElementType();
3318 else
3319 ResultExprTy = BaseTy->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003320 llvm::Value *Idx = nullptr;
Benjamin Kramer5ff67472016-04-11 08:26:13 +00003321 if (IsLowerBound || E->getColonLoc().isInvalid()) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003322 // Requesting lower bound or upper bound, but without provided length and
3323 // without ':' symbol for the default length -> length = 1.
3324 // Idx = LowerBound ?: 0;
3325 if (auto *LowerBound = E->getLowerBound()) {
3326 Idx = Builder.CreateIntCast(
3327 EmitScalarExpr(LowerBound), IntPtrTy,
3328 LowerBound->getType()->hasSignedIntegerRepresentation());
3329 } else
3330 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3331 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003332 // Try to emit length or lower bound as constant. If this is possible, 1
3333 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3334 // IR (LB + Len) - 1.
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003335 auto &C = CGM.getContext();
3336 auto *Length = E->getLength();
3337 llvm::APSInt ConstLength;
3338 if (Length) {
3339 // Idx = LowerBound + Length - 1;
3340 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3341 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3342 Length = nullptr;
3343 }
3344 auto *LowerBound = E->getLowerBound();
3345 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3346 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3347 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3348 LowerBound = nullptr;
3349 }
3350 if (!Length)
3351 --ConstLength;
3352 else if (!LowerBound)
3353 --ConstLowerBound;
3354
3355 if (Length || LowerBound) {
3356 auto *LowerBoundVal =
3357 LowerBound
3358 ? Builder.CreateIntCast(
3359 EmitScalarExpr(LowerBound), IntPtrTy,
3360 LowerBound->getType()->hasSignedIntegerRepresentation())
3361 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3362 auto *LengthVal =
3363 Length
3364 ? Builder.CreateIntCast(
3365 EmitScalarExpr(Length), IntPtrTy,
3366 Length->getType()->hasSignedIntegerRepresentation())
3367 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3368 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3369 /*HasNUW=*/false,
3370 !getLangOpts().isSignedOverflowDefined());
3371 if (Length && LowerBound) {
3372 Idx = Builder.CreateSub(
3373 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3374 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3375 }
3376 } else
3377 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3378 } else {
3379 // Idx = ArraySize - 1;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003380 QualType ArrayTy = BaseTy->isPointerType()
3381 ? E->getBase()->IgnoreParenImpCasts()->getType()
3382 : BaseTy;
3383 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003384 Length = VAT->getSizeExpr();
3385 if (Length->isIntegerConstantExpr(ConstLength, C))
3386 Length = nullptr;
3387 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003388 auto *CAT = C.getAsConstantArrayType(ArrayTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003389 ConstLength = CAT->getSize();
3390 }
3391 if (Length) {
3392 auto *LengthVal = Builder.CreateIntCast(
3393 EmitScalarExpr(Length), IntPtrTy,
3394 Length->getType()->hasSignedIntegerRepresentation());
3395 Idx = Builder.CreateSub(
3396 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3397 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3398 } else {
3399 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3400 --ConstLength;
3401 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3402 }
3403 }
3404 }
3405 assert(Idx);
3406
Alexey Bataev31300ed2016-02-04 11:27:03 +00003407 Address EltPtr = Address::invalid();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003408 LValueBaseInfo BaseInfo;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003409 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003410 // The base must be a pointer, which is not an aggregate. Emit
3411 // it. It needs to be emitted first in case it's what captures
3412 // the VLA bounds.
3413 Address Base =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003414 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, BaseTy,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003415 VLA->getElementType(), IsLowerBound);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003416 // The element count here is the total number of non-VLA elements.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003417 llvm::Value *NumElements = getVLASize(VLA).first;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003418
3419 // Effectively, the multiply by the VLA size is part of the GEP.
3420 // GEP indexes are signed, and scaling an index isn't permitted to
3421 // signed-overflow, so we use the same semantics for our explicit
3422 // multiply. We suppress this if overflow is not undefined behavior.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003423 if (getLangOpts().isSignedOverflowDefined())
3424 Idx = Builder.CreateMul(Idx, NumElements);
3425 else
3426 Idx = Builder.CreateNSWMul(Idx, NumElements);
3427 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003428 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003429 /*SignedIndices=*/false, E->getExprLoc());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003430 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3431 // If this is A[i] where A is an array, the frontend will have decayed the
3432 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3433 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3434 // "gep x, i" here. Emit one "gep A, 0, i".
3435 assert(Array->getType()->isArrayType() &&
3436 "Array to pointer decay must have array source type!");
3437 LValue ArrayLV;
3438 // For simple multidimensional array indexing, set the 'accessed' flag for
3439 // better bounds-checking of the base expression.
3440 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3441 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3442 else
3443 ArrayLV = EmitLValue(Array);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003444
Alexey Bataev31300ed2016-02-04 11:27:03 +00003445 // Propagate the alignment from the array itself to the result.
3446 EltPtr = emitArraySubscriptGEP(
3447 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
Vedant Kumara125eb52017-06-01 19:22:18 +00003448 ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003449 /*SignedIndices=*/false, E->getExprLoc());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003450 BaseInfo = ArrayLV.getBaseInfo();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003451 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003452 Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003453 BaseTy, ResultExprTy, IsLowerBound);
3454 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
Vedant Kumara125eb52017-06-01 19:22:18 +00003455 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003456 /*SignedIndices=*/false, E->getExprLoc());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003457 }
3458
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003459 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003460}
3461
Chris Lattner9e751ca2007-08-02 23:37:31 +00003462LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00003463EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00003464 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003465 LValue Base;
3466
3467 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00003468 if (E->isArrow()) {
3469 // If it is a pointer to a vector, emit the address and form an lvalue with
3470 // it.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003471 LValueBaseInfo BaseInfo;
3472 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003473 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003474 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo);
Daniel Dunbarf166a522010-08-21 03:44:13 +00003475 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00003476 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00003477 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3478 // emit the base as an lvalue.
3479 assert(E->getBase()->getType()->isVectorType());
3480 Base = EmitLValue(E->getBase());
3481 } else {
3482 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00003483 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00003484 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00003485 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00003486
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00003487 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00003488 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00003489 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00003490 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003491 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattner4e1a3232009-12-23 21:31:11 +00003492 }
John McCall1553b192011-06-16 04:16:24 +00003493
3494 QualType type =
3495 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00003496
Nate Begemand3862152008-05-13 21:03:02 +00003497 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00003498 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00003499 E->getEncodedElementAccess(Indices);
3500
3501 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00003502 llvm::Constant *CV =
3503 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00003504 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003505 Base.getBaseInfo());
Nate Begemand3862152008-05-13 21:03:02 +00003506 }
3507 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3508
3509 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003510 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00003511
Chris Lattner595ba3a2012-01-30 06:20:36 +00003512 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3513 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00003514 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00003515 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003516 Base.getBaseInfo());
Chris Lattner9e751ca2007-08-02 23:37:31 +00003517}
3518
Devang Patel30efa2e2007-10-23 20:28:39 +00003519LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00003520 Expr *BaseExpr = E->getBase();
Chris Lattner4e4186b2007-12-02 18:52:07 +00003521 // 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 +00003522 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00003523 if (E->isArrow()) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003524 LValueBaseInfo BaseInfo;
3525 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo);
Richard Smith69d0d262012-08-24 00:54:33 +00003526 QualType PtrTy = BaseExpr->getType()->getPointeeType();
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003527 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00003528 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
3529 if (IsBaseCXXThis)
3530 SkippedChecks.set(SanitizerKind::Alignment, true);
3531 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003532 SkippedChecks.set(SanitizerKind::Null, true);
3533 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
3534 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003535 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo);
Richard Smith69d0d262012-08-24 00:54:33 +00003536 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003537 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003538
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003539 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003540 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003541 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003542 setObjCGCLValueClass(getContext(), E, LV);
3543 return LV;
3544 }
Craig Topper99e79272013-07-26 05:59:26 +00003545
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003546 if (auto *VD = dyn_cast<VarDecl>(ND))
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00003547 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003548
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003549 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003550 return EmitFunctionDeclLValue(*this, E, FD);
3551
David Blaikie83d382b2011-09-23 05:06:16 +00003552 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003553}
Devang Patel30efa2e2007-10-23 20:28:39 +00003554
John McCalldec348f72013-05-03 07:33:41 +00003555/// Given that we are currently emitting a lambda, emit an l-value for
3556/// one of its members.
3557LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3558 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3559 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3560 QualType LambdaTagType =
3561 getContext().getTagDeclType(Field->getParent());
3562 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3563 return EmitLValueForField(LambdaLV, Field);
3564}
3565
John McCall7f416cc2015-09-08 08:05:57 +00003566/// Drill down to the storage of a field without walking into
3567/// reference types.
3568///
3569/// The resulting address doesn't necessarily have the right type.
3570static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3571 const FieldDecl *field) {
3572 const RecordDecl *rec = field->getParent();
3573
3574 unsigned idx =
3575 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3576
3577 CharUnits offset;
3578 // Adjust the alignment down to the given offset.
3579 // As a special case, if the LLVM field index is 0, we know that this
3580 // is zero.
3581 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3582 .getFieldOffset(field->getFieldIndex()) == 0) &&
3583 "LLVM field at index zero had non-zero offset?");
3584 if (idx != 0) {
3585 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3586 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3587 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3588 }
3589
3590 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3591}
3592
Piotr Padlewskic1d26062017-06-01 18:39:34 +00003593static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
3594 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
3595 if (!RD)
3596 return false;
3597
3598 if (RD->isDynamicClass())
3599 return true;
3600
3601 for (const auto &Base : RD->bases())
3602 if (hasAnyVptr(Base.getType(), Context))
3603 return true;
3604
3605 for (const FieldDecl *Field : RD->fields())
3606 if (hasAnyVptr(Field->getType(), Context))
3607 return true;
3608
3609 return false;
3610}
3611
Eli Friedman7f1ff602012-04-16 03:54:45 +00003612LValue CodeGenFunction::EmitLValueForField(LValue base,
3613 const FieldDecl *field) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003614 LValueBaseInfo BaseInfo = base.getBaseInfo();
John McCall7f416cc2015-09-08 08:05:57 +00003615 AlignmentSource fieldAlignSource =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003616 getFieldAlignmentSource(BaseInfo.getAlignmentSource());
3617 LValueBaseInfo FieldBaseInfo(fieldAlignSource, BaseInfo.getMayAlias());
John McCall7f416cc2015-09-08 08:05:57 +00003618
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00003619 const RecordDecl *rec = field->getParent();
3620 if (rec->isUnion() || rec->hasAttr<MayAliasAttr>())
3621 FieldBaseInfo.setMayAlias(true);
3622 bool mayAlias = FieldBaseInfo.getMayAlias();
3623
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003624 if (field->isBitField()) {
3625 const CGRecordLayout &RL =
3626 CGM.getTypes().getCGRecordLayout(field->getParent());
3627 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003628 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003629 unsigned Idx = RL.getLLVMFieldNo(field);
3630 if (Idx != 0)
3631 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003632 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3633 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003634 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003635 llvm::Type *FieldIntTy =
3636 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3637 if (Addr.getElementType() != FieldIntTy)
3638 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003639
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003640 QualType fieldType =
3641 field->getType().withCVRQualifiers(base.getVRQualifiers());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003642 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo);
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003643 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003644
John McCall53fcbd22011-02-26 08:07:02 +00003645 QualType type = field->getType();
John McCall7f416cc2015-09-08 08:05:57 +00003646 Address addr = base.getAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003647 unsigned cvr = base.getVRQualifiers();
Manman Renc451e572013-04-04 21:53:22 +00003648 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
John McCall53fcbd22011-02-26 08:07:02 +00003649 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003650 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00003651 assert(!type->isReferenceType() && "union has reference member");
Manman Renc451e572013-04-04 21:53:22 +00003652 // TODO: handle path-aware TBAA for union.
3653 TBAAPath = false;
Piotr Padlewskic1d26062017-06-01 18:39:34 +00003654
3655 const auto FieldType = field->getType();
3656 if (CGM.getCodeGenOpts().StrictVTablePointers &&
3657 hasAnyVptr(FieldType, getContext()))
3658 // Because unions can easily skip invariant.barriers, we need to add
3659 // a barrier every time CXXRecord field with vptr is referenced.
3660 addr = Address(Builder.CreateInvariantGroupBarrier(addr.getPointer()),
3661 addr.getAlignment());
John McCall53fcbd22011-02-26 08:07:02 +00003662 } else {
3663 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003664 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003665
3666 // If this is a reference field, load the reference right now.
3667 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3668 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3669 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3670
Manman Renc451e572013-04-04 21:53:22 +00003671 // Loading the reference will disable path-aware TBAA.
3672 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003673 if (CGM.shouldUseTBAA()) {
3674 llvm::MDNode *tbaa;
3675 if (mayAlias)
3676 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3677 else
3678 tbaa = CGM.getTBAAInfo(type);
Manman Ren4f755de2013-10-08 00:08:49 +00003679 if (tbaa)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00003680 CGM.DecorateInstructionWithTBAA(load, tbaa);
John McCall53fcbd22011-02-26 08:07:02 +00003681 }
3682
John McCall53fcbd22011-02-26 08:07:02 +00003683 mayAlias = false;
3684 type = refType->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003685
3686 CharUnits alignment =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003687 getNaturalTypeAlignment(type, &FieldBaseInfo, /*pointee*/ true);
3688 FieldBaseInfo.setMayAlias(false);
John McCall7f416cc2015-09-08 08:05:57 +00003689 addr = Address(load, alignment);
3690
3691 // Qualifiers on the struct don't apply to the referencee, and
3692 // we'll pick up CVR from the actual type later, so reset these
3693 // additional qualifiers now.
3694 cvr = 0;
John McCall53fcbd22011-02-26 08:07:02 +00003695 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003696 }
Craig Topper99e79272013-07-26 05:59:26 +00003697
Chris Lattner13ee4f42011-07-10 05:34:54 +00003698 // Make sure that the address is pointing to the right type. This is critical
3699 // for both unions and structs. A union needs a bitcast, a struct element
3700 // will need a bitcast if the LLVM type laid out doesn't match the desired
3701 // type.
John McCall7f416cc2015-09-08 08:05:57 +00003702 addr = Builder.CreateElementBitCast(addr,
3703 CGM.getTypes().ConvertTypeForMem(type),
3704 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003705
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003706 if (field->hasAttr<AnnotateAttr>())
3707 addr = EmitFieldAnnotations(field, addr);
3708
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003709 LValue LV = MakeAddrLValue(addr, type, FieldBaseInfo);
John McCall53fcbd22011-02-26 08:07:02 +00003710 LV.getQuals().addCVRQualifiers(cvr);
Manman Renc451e572013-04-04 21:53:22 +00003711 if (TBAAPath) {
3712 const ASTRecordLayout &Layout =
3713 getContext().getASTRecordLayout(field->getParent());
3714 // Set the base type to be the base type of the base LValue and
3715 // update offset to be relative to the base type.
Manman Ren0e521662013-04-27 00:39:37 +00003716 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3717 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
Manman Renc451e572013-04-04 21:53:22 +00003718 Layout.getFieldOffset(field->getFieldIndex()) /
3719 getContext().getCharWidth());
3720 }
Daniel Dunbarf166a522010-08-21 03:44:13 +00003721
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003722 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003723 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3724 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003725
3726 // Fields of may_alias structs act like 'char' for TBAA purposes.
3727 // FIXME: this should get propagated down through anonymous structs
3728 // and unions.
3729 if (mayAlias && LV.getTBAAInfo())
3730 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3731
Daniel Dunbarf166a522010-08-21 03:44:13 +00003732 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003733}
3734
Craig Topper99e79272013-07-26 05:59:26 +00003735LValue
3736CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003737 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003738 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003739
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003740 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003741 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003742
John McCall7f416cc2015-09-08 08:05:57 +00003743 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003744
John McCall7f416cc2015-09-08 08:05:57 +00003745 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003746 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003747 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003748
John McCall7f416cc2015-09-08 08:05:57 +00003749 // TODO: access-path TBAA?
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003750 LValueBaseInfo BaseInfo = Base.getBaseInfo();
3751 LValueBaseInfo FieldBaseInfo(
3752 getFieldAlignmentSource(BaseInfo.getAlignmentSource()),
3753 BaseInfo.getMayAlias());
3754 return MakeAddrLValue(V, FieldType, FieldBaseInfo);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003755}
3756
Chris Lattnerf53c0962010-09-06 00:11:41 +00003757LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003758 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
Richard Smith2d988f02011-11-22 22:48:32 +00003759 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003760 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003761 return MakeAddrLValue(GlobalPtr, E->getType(), BaseInfo);
Richard Smith2d988f02011-11-22 22:48:32 +00003762 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003763 if (E->getType()->isVariablyModifiedType())
3764 // make sure to emit the VLA size.
3765 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003766
John McCall7f416cc2015-09-08 08:05:57 +00003767 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003768 const Expr *InitExpr = E->getInitializer();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003769 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), BaseInfo);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003770
Chad Rosier615ed1a2012-03-29 17:37:10 +00003771 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3772 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003773
3774 return Result;
3775}
3776
Richard Smithbb653bd2012-05-14 21:57:21 +00003777LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3778 if (!E->isGLValue())
3779 // Initializing an aggregate temporary in C++11: T{...}.
3780 return EmitAggExprToLValue(E);
3781
3782 // An lvalue initializer list must be initializing a reference.
Richard Smith122f88d2016-12-06 23:52:28 +00003783 assert(E->isTransparent() && "non-transparent glvalue init list");
Richard Smithbb653bd2012-05-14 21:57:21 +00003784 return EmitLValue(E->getInit(0));
3785}
3786
Richard Smithf3076ff2014-06-20 18:43:47 +00003787/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3788/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3789/// LValue is returned and the current block has been terminated.
3790static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3791 const Expr *Operand) {
3792 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3793 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3794 return None;
3795 }
3796
3797 return CGF.EmitLValue(Operand);
3798}
3799
John McCallc07a0c72011-02-17 10:25:35 +00003800LValue CodeGenFunction::
3801EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3802 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003803 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003804 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003805 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003806 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003807 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003808
Eli Friedman59954892012-01-25 05:04:17 +00003809 OpaqueValueMapping binding(*this, expr);
3810
John McCallc07a0c72011-02-17 10:25:35 +00003811 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003812 bool CondExprBool;
3813 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003814 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003815 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003816
Justin Bogneref512b92014-01-06 22:27:43 +00003817 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003818 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003819 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003820 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003821 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003822 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003823 }
3824
John McCallc07a0c72011-02-17 10:25:35 +00003825 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3826 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3827 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003828
3829 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003830 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003831
John McCall0a6bf2e2011-01-26 19:21:13 +00003832 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003833 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003834 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003835 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003836 Optional<LValue> lhs =
3837 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003838 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003839
Richard Smithf3076ff2014-06-20 18:43:47 +00003840 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003841 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003842
John McCallc07a0c72011-02-17 10:25:35 +00003843 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003844 if (lhs)
3845 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003846
John McCall0a6bf2e2011-01-26 19:21:13 +00003847 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003848 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003849 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003850 Optional<LValue> rhs =
3851 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003852 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003853 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003854 return EmitUnsupportedLValue(expr, "conditional operator");
3855 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003856
John McCallc07a0c72011-02-17 10:25:35 +00003857 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003858
Richard Smithf3076ff2014-06-20 18:43:47 +00003859 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003860 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003861 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003862 phi->addIncoming(lhs->getPointer(), lhsBlock);
3863 phi->addIncoming(rhs->getPointer(), rhsBlock);
3864 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3865 AlignmentSource alignSource =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003866 std::max(lhs->getBaseInfo().getAlignmentSource(),
3867 rhs->getBaseInfo().getAlignmentSource());
3868 bool MayAlias = lhs->getBaseInfo().getMayAlias() ||
3869 rhs->getBaseInfo().getMayAlias();
3870 return MakeAddrLValue(result, expr->getType(),
3871 LValueBaseInfo(alignSource, MayAlias));
Richard Smithf3076ff2014-06-20 18:43:47 +00003872 } else {
3873 assert((lhs || rhs) &&
3874 "both operands of glvalue conditional are throw-expressions?");
3875 return lhs ? *lhs : *rhs;
3876 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003877}
3878
Richard Smithbb653bd2012-05-14 21:57:21 +00003879/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3880/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003881/// otherwise if a cast is needed by the code generator in an lvalue context,
3882/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003883/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003884/// are permitted with aggregate result, including noop aggregate casts, and
3885/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003886LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003887 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003888 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003889 case CK_BitCast:
3890 case CK_ArrayToPointerDecay:
3891 case CK_FunctionToPointerDecay:
3892 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003893 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003894 case CK_IntegralToPointer:
3895 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003896 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003897 case CK_VectorSplat:
3898 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00003899 case CK_BooleanToSignedIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003900 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003901 case CK_IntegralToFloating:
3902 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003903 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003904 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003905 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003906 case CK_FloatingComplexToReal:
3907 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003908 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003909 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003910 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003911 case CK_IntegralComplexToReal:
3912 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003913 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003914 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003915 case CK_DerivedToBaseMemberPointer:
3916 case CK_BaseToDerivedMemberPointer:
3917 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003918 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003919 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003920 case CK_ARCProduceObject:
3921 case CK_ARCConsumeObject:
3922 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003923 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003924 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003925 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003926 case CK_IntToOCLSampler:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003927 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3928
3929 case CK_Dependent:
3930 llvm_unreachable("dependent cast kind in IR gen!");
3931
3932 case CK_BuiltinFnToFnPtr:
3933 llvm_unreachable("builtin functions are handled elsewhere");
3934
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003935 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003936 case CK_NonAtomicToAtomic:
3937 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003938 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00003939
Anders Carlsson8a01a752011-04-11 02:03:26 +00003940 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00003941 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003942 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003943 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00003944 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00003945 }
3946
John McCalle3027922010-08-25 11:45:40 +00003947 case CK_ConstructorConversion:
3948 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00003949 case CK_CPointerToObjCPointerCast:
3950 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003951 case CK_NoOp:
3952 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003953 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00003954
John McCalle3027922010-08-25 11:45:40 +00003955 case CK_UncheckedDerivedToBase:
3956 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00003957 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00003958 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003959 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003960
Anders Carlssond95f9602009-09-12 16:16:49 +00003961 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003962 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00003963
Anders Carlssond95f9602009-09-12 16:16:49 +00003964 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00003965 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00003966 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3967 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00003968
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003969 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo());
Anders Carlssond95f9602009-09-12 16:16:49 +00003970 }
John McCalle3027922010-08-25 11:45:40 +00003971 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00003972 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00003973 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00003974 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003975 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003976
Anders Carlsson8c793172009-11-23 17:57:54 +00003977 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00003978
Anders Carlsson8c793172009-11-23 17:57:54 +00003979 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00003980 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00003981 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00003982 E->path_begin(), E->path_end(),
3983 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00003984
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003985 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3986 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00003987 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003988 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00003989 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003990
Peter Collingbourned2926c92015-03-14 02:42:25 +00003991 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003992 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3993 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003994 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003995
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003996 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo());
Eli Friedman8c98dff2009-11-16 05:48:01 +00003997 }
John McCalle3027922010-08-25 11:45:40 +00003998 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00003999 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004000 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00004001
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00004002 CGM.EmitExplicitCastExprType(CE, this);
Anders Carlsson50cb3212009-11-14 21:21:42 +00004003 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004004 Address V = Builder.CreateBitCast(LV.getAddress(),
4005 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00004006
4007 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00004008 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
4009 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00004010 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00004011
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004012 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo());
Anders Carlsson50cb3212009-11-14 21:21:42 +00004013 }
John McCalle3027922010-08-25 11:45:40 +00004014 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004015 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004016 Address V = Builder.CreateElementBitCast(LV.getAddress(),
4017 ConvertType(E->getType()));
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004018 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004019 }
Egor Churaev89831422016-12-23 14:55:49 +00004020 case CK_ZeroToOCLQueue:
4021 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004022 case CK_ZeroToOCLEvent:
4023 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00004024 }
Craig Topper99e79272013-07-26 05:59:26 +00004025
Douglas Gregorcdb466e2010-07-15 18:58:16 +00004026 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00004027}
4028
John McCall1bf58462011-02-16 08:02:54 +00004029LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00004030 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00004031 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00004032}
4033
Eli Friedman7f1ff602012-04-16 03:54:45 +00004034RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004035 const FieldDecl *FD,
4036 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004037 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00004038 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00004039 switch (getEvaluationKind(FT)) {
4040 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004041 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00004042 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00004043 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00004044 case TEK_Scalar:
Reid Kleckner9d031092016-05-02 22:42:34 +00004045 // This routine is used to load fields one-by-one to perform a copy, so
4046 // don't load reference fields.
4047 if (FD->getType()->isReferenceType())
4048 return RValue::get(FieldLV.getPointer());
Nick Lewycky2d84e842013-10-02 02:29:49 +00004049 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00004050 }
4051 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004052}
Douglas Gregorfe314812011-06-21 17:03:29 +00004053
Chris Lattnere47e4402007-06-01 18:02:12 +00004054//===--------------------------------------------------------------------===//
4055// Expression Emission
4056//===--------------------------------------------------------------------===//
4057
Craig Topper99e79272013-07-26 05:59:26 +00004058RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00004059 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00004060 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00004061 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00004062 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00004063
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004064 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00004065 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00004066
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004067 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00004068 return EmitCUDAKernelCallExpr(CE, ReturnValue);
4069
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004070 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
John McCallb92ab1a2016-10-26 23:46:34 +00004071 if (const CXXMethodDecl *MD =
4072 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
Anders Carlssonbfb36712009-12-24 21:13:40 +00004073 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00004074
John McCallb92ab1a2016-10-26 23:46:34 +00004075 CGCallee callee = EmitCallee(E->getCallee());
Craig Topper99e79272013-07-26 05:59:26 +00004076
John McCallb92ab1a2016-10-26 23:46:34 +00004077 if (callee.isBuiltin()) {
4078 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
4079 E, ReturnValue);
Douglas Gregorad8a3362009-09-04 17:36:40 +00004080 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004081
John McCallb92ab1a2016-10-26 23:46:34 +00004082 if (callee.isPseudoDestructor()) {
4083 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
4084 }
4085
4086 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
4087}
4088
4089/// Emit a CallExpr without considering whether it might be a subclass.
4090RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
4091 ReturnValueSlot ReturnValue) {
4092 CGCallee Callee = EmitCallee(E->getCallee());
4093 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
4094}
4095
4096static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
4097 if (auto builtinID = FD->getBuiltinID()) {
4098 return CGCallee::forBuiltin(builtinID, FD);
4099 }
4100
4101 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
4102 return CGCallee::forDirect(calleePtr, FD);
4103}
4104
4105CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
4106 E = E->IgnoreParens();
4107
4108 // Look through function-to-pointer decay.
4109 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
4110 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
4111 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
4112 return EmitCallee(ICE->getSubExpr());
4113 }
4114
4115 // Resolve direct calls.
4116 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
4117 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
4118 return EmitDirectCallee(*this, FD);
4119 }
4120 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
4121 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
4122 EmitIgnoredExpr(ME->getBase());
4123 return EmitDirectCallee(*this, FD);
4124 }
4125
4126 // Look through template substitutions.
4127 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4128 return EmitCallee(NTTP->getReplacement());
4129
4130 // Treat pseudo-destructor calls differently.
4131 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4132 return CGCallee::forPseudoDestructor(PDE);
4133 }
4134
4135 // Otherwise, we have an indirect reference.
4136 llvm::Value *calleePtr;
4137 QualType functionType;
4138 if (auto ptrType = E->getType()->getAs<PointerType>()) {
4139 calleePtr = EmitScalarExpr(E);
4140 functionType = ptrType->getPointeeType();
4141 } else {
4142 functionType = E->getType();
4143 calleePtr = EmitLValue(E).getPointer();
4144 }
4145 assert(functionType->isFunctionType());
4146 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
4147 E->getReferencedDeclOfCallee());
4148 CGCallee callee(calleeInfo, calleePtr);
4149 return callee;
Chris Lattner9e47ead2007-08-31 04:44:06 +00004150}
4151
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004152LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00004153 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00004154 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00004155 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00004156 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00004157 return EmitLValue(E->getRHS());
4158 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004159
John McCalle3027922010-08-25 11:45:40 +00004160 if (E->getOpcode() == BO_PtrMemD ||
4161 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004162 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004163
John McCalla2342eb2010-12-05 02:00:02 +00004164 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00004165
4166 // Note that in all of these cases, __block variables need the RHS
4167 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00004168
4169 switch (getEvaluationKind(E->getType())) {
4170 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00004171 switch (E->getLHS()->getType().getObjCLifetime()) {
4172 case Qualifiers::OCL_Strong:
4173 return EmitARCStoreStrong(E, /*ignored*/ false).first;
4174
4175 case Qualifiers::OCL_Autoreleasing:
4176 return EmitARCStoreAutoreleasing(E).first;
4177
4178 // No reason to do any of these differently.
4179 case Qualifiers::OCL_None:
4180 case Qualifiers::OCL_ExplicitNone:
4181 case Qualifiers::OCL_Weak:
4182 break;
4183 }
4184
John McCalld0a30012010-12-06 06:10:02 +00004185 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00004186 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
Vedant Kumar6b22dda2017-04-26 21:55:17 +00004187 if (RV.isScalar())
4188 EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
John McCall55e1fbc2011-06-25 02:11:03 +00004189 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00004190 return LV;
4191 }
John McCall4f29b492010-11-16 23:07:28 +00004192
John McCall47fb9502013-03-07 21:37:08 +00004193 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00004194 return EmitComplexAssignmentLValue(E);
4195
John McCall47fb9502013-03-07 21:37:08 +00004196 case TEK_Aggregate:
4197 return EmitAggExprToLValue(E);
4198 }
4199 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004200}
4201
Christopher Lambd91c3d42007-12-29 05:02:41 +00004202LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00004203 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00004204
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004205 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004206 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004207 LValueBaseInfo(AlignmentSource::Decl, false));
Craig Topper99e79272013-07-26 05:59:26 +00004208
David Majnemerced8bdf2015-02-25 17:36:15 +00004209 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004210 "Can't have a scalar return unless the return type is a "
4211 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00004212
John McCall7f416cc2015-09-08 08:05:57 +00004213 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00004214}
4215
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004216LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4217 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00004218 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004219}
4220
Anders Carlsson3be22e22009-05-30 23:23:33 +00004221LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004222 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
4223 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004224 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00004225 EmitCXXConstructExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004226 return MakeAddrLValue(Slot.getAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004227 LValueBaseInfo(AlignmentSource::Decl, false));
Anders Carlsson3be22e22009-05-30 23:23:33 +00004228}
4229
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004230LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00004231CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004232 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00004233}
4234
John McCall7f416cc2015-09-08 08:05:57 +00004235Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
4236 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4237 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00004238}
4239
4240LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004241 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004242 LValueBaseInfo(AlignmentSource::Decl, false));
Nico Webercf4ff5862012-10-11 10:13:44 +00004243}
4244
Mike Stumpc9b231c2009-11-15 08:09:41 +00004245LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004246CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004247 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00004248 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00004249 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004250 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
4251 return MakeAddrLValue(Slot.getAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004252 LValueBaseInfo(AlignmentSource::Decl, false));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004253}
4254
Eli Friedman5bc17122012-02-08 05:34:55 +00004255LValue
4256CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00004257 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00004258 EmitLambdaExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004259 return MakeAddrLValue(Slot.getAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004260 LValueBaseInfo(AlignmentSource::Decl, false));
Eli Friedman5bc17122012-02-08 05:34:55 +00004261}
4262
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004263LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004264 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00004265
Anders Carlsson280e61f12010-06-21 20:59:55 +00004266 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004267 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004268 LValueBaseInfo(AlignmentSource::Decl, false));
Craig Topper99e79272013-07-26 05:59:26 +00004269
Alp Toker314cc812014-01-25 16:55:45 +00004270 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00004271 "Can't have a scalar return unless the return type is a "
4272 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00004273
John McCall7f416cc2015-09-08 08:05:57 +00004274 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004275}
4276
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004277LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004278 Address V =
4279 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004280 return MakeAddrLValue(V, E->getType(),
4281 LValueBaseInfo(AlignmentSource::Decl, false));
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004282}
4283
Daniel Dunbar722f4242009-04-22 05:08:15 +00004284llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004285 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004286 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004287}
4288
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004289LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4290 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004291 const ObjCIvarDecl *Ivar,
4292 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00004293 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00004294 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004295}
4296
4297LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004298 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00004299 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004300 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00004301 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004302 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004303 if (E->isArrow()) {
4304 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004305 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00004306 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004307 } else {
4308 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00004309 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004310 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00004311 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004312 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004313
Craig Topper99e79272013-07-26 05:59:26 +00004314 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00004315 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4316 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00004317 setObjCGCLValueClass(getContext(), E, LV);
4318 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00004319}
4320
Chris Lattnera4185c52009-04-25 19:35:26 +00004321LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00004322 // Can only get l-value for message expression returning aggregate type
4323 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00004324 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004325 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattnera4185c52009-04-25 19:35:26 +00004326}
4327
John McCallb92ab1a2016-10-26 23:46:34 +00004328RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004329 const CallExpr *E, ReturnValueSlot ReturnValue,
John McCallb92ab1a2016-10-26 23:46:34 +00004330 llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00004331 // Get the actual function type. The callee type will always be a pointer to
4332 // function type or a block pointer type.
4333 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00004334 "Call must have function pointer type!");
4335
John McCallb92ab1a2016-10-26 23:46:34 +00004336 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
Samuel Antao798f11c2015-11-23 22:04:44 +00004337
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004338 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
Eric Christopher39db7262015-11-14 01:56:04 +00004339 // We can only guarantee that a function is called from the correct
4340 // context/function based on the appropriate target attributes,
4341 // so only check in the case where we have both always_inline and target
4342 // since otherwise we could be making a conditional call after a check for
4343 // the proper cpu features (and it won't cause code generation issues due to
4344 // function based code generation).
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004345 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4346 TargetDecl->hasAttr<TargetAttr>())
4347 checkTargetFeatures(E, FD);
4348
John McCall6fd4c232009-10-23 08:22:42 +00004349 CalleeType = getContext().getCanonicalType(CalleeType);
4350
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004351 const auto *FnType =
4352 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00004353
John McCallb92ab1a2016-10-26 23:46:34 +00004354 CGCallee Callee = OrigCallee;
4355
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004356 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004357 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4358 if (llvm::Constant *PrefixSig =
4359 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00004360 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004361 llvm::Constant *FTRTTIConst =
4362 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4363 llvm::Type *PrefixStructTyElems[] = {
4364 PrefixSig->getType(),
4365 FTRTTIConst->getType()
4366 };
4367 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4368 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4369
John McCallb92ab1a2016-10-26 23:46:34 +00004370 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4371
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004372 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
John McCallb92ab1a2016-10-26 23:46:34 +00004373 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004374 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004375 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00004376 llvm::Value *CalleeSig =
4377 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004378 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4379
4380 llvm::BasicBlock *Cont = createBasicBlock("cont");
4381 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4382 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4383
4384 EmitBlock(TypeCheck);
4385 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004386 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
John McCall7f416cc2015-09-08 08:05:57 +00004387 llvm::Value *CalleeRTTI =
4388 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004389 llvm::Value *CalleeRTTIMatch =
4390 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4391 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004392 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004393 EmitCheckTypeDescriptor(CalleeType)
4394 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00004395 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004396 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004397
4398 Builder.CreateBr(Cont);
4399 EmitBlock(Cont);
4400 }
4401 }
4402
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004403 // If we are checking indirect calls and this call is indirect, check that the
4404 // function pointer is a member of the bit set for the function type.
4405 if (SanOpts.has(SanitizerKind::CFIICall) &&
4406 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4407 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00004408 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004409
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004410 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004411 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004412
John McCallb92ab1a2016-10-26 23:46:34 +00004413 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4414 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004415 llvm::Value *TypeTest = Builder.CreateCall(
4416 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004417
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004418 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004419 llvm::Constant *StaticData[] = {
4420 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4421 EmitCheckSourceLocation(E->getLocStart()),
4422 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4423 };
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004424 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4425 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004426 CastedCallee, StaticData);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004427 } else {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004428 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004429 SanitizerHandler::CFICheckFail, StaticData,
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004430 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004431 }
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004432 }
4433
Daniel Dunbarc722b852008-08-30 03:02:31 +00004434 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00004435 if (Chain)
4436 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4437 CGM.getContext().VoidPtrTy);
Richard Smith762672a2016-09-28 19:09:10 +00004438
4439 // C++17 requires that we evaluate arguments to a call using assignment syntax
Richard Smitha560ccf2016-09-29 21:30:12 +00004440 // right-to-left, and that we evaluate arguments to certain other operators
4441 // left-to-right. Note that we allow this to override the order dictated by
4442 // the calling convention on the MS ABI, which means that parameter
4443 // destruction order is not necessarily reverse construction order.
4444 // FIXME: Revisit this based on C++ committee response to unimplementability.
4445 EvaluationOrder Order = EvaluationOrder::Default;
4446 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4447 if (OCE->isAssignmentOp())
4448 Order = EvaluationOrder::ForceRightToLeft;
4449 else {
4450 switch (OCE->getOperator()) {
4451 case OO_LessLess:
4452 case OO_GreaterGreater:
4453 case OO_AmpAmp:
4454 case OO_PipePipe:
4455 case OO_Comma:
4456 case OO_ArrowStar:
4457 Order = EvaluationOrder::ForceLeftToRight;
4458 break;
4459 default:
4460 break;
4461 }
4462 }
4463 }
Richard Smith762672a2016-09-28 19:09:10 +00004464
David Blaikief05779e2015-07-21 18:37:18 +00004465 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
Richard Smitha560ccf2016-09-29 21:30:12 +00004466 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
Daniel Dunbarc722b852008-08-30 03:02:31 +00004467
Peter Collingbournef7706832014-12-12 23:41:25 +00004468 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4469 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00004470
4471 // C99 6.5.2.2p6:
4472 // If the expression that denotes the called function has a type
4473 // that does not include a prototype, [the default argument
4474 // promotions are performed]. If the number of arguments does not
4475 // equal the number of parameters, the behavior is undefined. If
4476 // the function is defined with a type that includes a prototype,
4477 // and either the prototype ends with an ellipsis (, ...) or the
4478 // types of the arguments after promotion are not compatible with
4479 // the types of the parameters, the behavior is undefined. If the
4480 // function is defined with a type that does not include a
4481 // prototype, and the types of the arguments after promotion are
4482 // not compatible with those of the parameters after promotion,
4483 // the behavior is undefined [except in some trivial cases].
4484 // That is, in the general case, we should assume that a call
4485 // through an unprototyped function type works like a *non-variadic*
4486 // call. The way we make this work is to cast to the exact type
4487 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00004488 //
4489 // Chain calls use this same code path to add the invisible chain parameter
4490 // to the function type.
4491 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00004492 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00004493 CalleeTy = CalleeTy->getPointerTo();
John McCallb92ab1a2016-10-26 23:46:34 +00004494
4495 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4496 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4497 Callee.setFunctionPointer(CalleePtr);
John McCallcbc038a2011-09-21 08:08:30 +00004498 }
4499
John McCallb92ab1a2016-10-26 23:46:34 +00004500 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00004501}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004502
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004503LValue CodeGenFunction::
4504EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004505 Address BaseAddr = Address::invalid();
4506 if (E->getOpcode() == BO_PtrMemI) {
4507 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4508 } else {
4509 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4510 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004511
John McCallc134eb52010-08-31 21:07:20 +00004512 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4513
4514 const MemberPointerType *MPT
4515 = E->getRHS()->getType()->getAs<MemberPointerType>();
4516
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004517 LValueBaseInfo BaseInfo;
John McCall7f416cc2015-09-08 08:05:57 +00004518 Address MemberAddr =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004519 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo);
John McCallc134eb52010-08-31 21:07:20 +00004520
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004521 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004522}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004523
John McCall47fb9502013-03-07 21:37:08 +00004524/// Given the address of a temporary variable, produce an r-value of
4525/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00004526RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004527 QualType type,
4528 SourceLocation loc) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004529 LValue lvalue = MakeAddrLValue(addr, type,
4530 LValueBaseInfo(AlignmentSource::Decl, false));
John McCall47fb9502013-03-07 21:37:08 +00004531 switch (getEvaluationKind(type)) {
4532 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004533 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004534 case TEK_Aggregate:
4535 return lvalue.asAggregateRValue();
4536 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004537 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004538 }
4539 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004540}
4541
Duncan Sandse81111c2012-04-10 08:23:07 +00004542void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004543 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00004544 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004545 return;
4546
Duncan Sands65229ed2012-04-16 16:29:47 +00004547 llvm::MDBuilder MDHelper(getLLVMContext());
4548 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004549
Duncan Sands6fc46192012-04-14 12:37:26 +00004550 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004551}
John McCallfe96e0b2011-11-06 09:01:30 +00004552
4553namespace {
4554 struct LValueOrRValue {
4555 LValue LV;
4556 RValue RV;
4557 };
4558}
4559
4560static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4561 const PseudoObjectExpr *E,
4562 bool forLValue,
4563 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004564 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00004565
4566 // Find the result expression, if any.
4567 const Expr *resultExpr = E->getResultExpr();
4568 LValueOrRValue result;
4569
4570 for (PseudoObjectExpr::const_semantics_iterator
4571 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4572 const Expr *semantic = *i;
4573
4574 // If this semantic expression is an opaque value, bind it
4575 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004576 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00004577
4578 // If this is the result expression, we may need to evaluate
4579 // directly into the slot.
4580 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4581 OVMA opaqueData;
4582 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00004583 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00004584 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004585 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
John McCall7f416cc2015-09-08 08:05:57 +00004586 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004587 BaseInfo);
John McCallfe96e0b2011-11-06 09:01:30 +00004588 opaqueData = OVMA::bind(CGF, ov, LV);
4589 result.RV = slot.asRValue();
4590
4591 // Otherwise, emit as normal.
4592 } else {
4593 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4594
4595 // If this is the result, also evaluate the result now.
4596 if (ov == resultExpr) {
4597 if (forLValue)
4598 result.LV = CGF.EmitLValue(ov);
4599 else
4600 result.RV = CGF.EmitAnyExpr(ov, slot);
4601 }
4602 }
4603
4604 opaques.push_back(opaqueData);
4605
4606 // Otherwise, if the expression is the result, evaluate it
4607 // and remember the result.
4608 } else if (semantic == resultExpr) {
4609 if (forLValue)
4610 result.LV = CGF.EmitLValue(semantic);
4611 else
4612 result.RV = CGF.EmitAnyExpr(semantic, slot);
4613
4614 // Otherwise, evaluate the expression in an ignored context.
4615 } else {
4616 CGF.EmitIgnoredExpr(semantic);
4617 }
4618 }
4619
4620 // Unbind all the opaques now.
4621 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4622 opaques[i].unbind(CGF);
4623
4624 return result;
4625}
4626
4627RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4628 AggValueSlot slot) {
4629 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4630}
4631
4632LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4633 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4634}