blob: c8df3a4f64677f24710c22039603e4970a10c5c3 [file] [log] [blame]
Chris Lattnere47e4402007-06-01 18:02:12 +00001//===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnere47e4402007-06-01 18:02:12 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit Expr nodes as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
John McCall5d865c322010-08-31 07:33:07 +000013#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "CGCall.h"
Tim Shen421119f2016-07-01 21:08:47 +000015#include "CGCleanup.h"
Devang Pateld3a6b0f2011-03-04 18:54:42 +000016#include "CGDebugInfo.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000017#include "CGObjCRuntime.h"
Alexey Bataev97720002014-11-11 04:05:39 +000018#include "CGOpenMPRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "CGRecordLayout.h"
Tim Shen421119f2016-07-01 21:08:47 +000020#include "CodeGenFunction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "CodeGenModule.h"
John McCallde0fe072017-08-15 21:42:52 +000022#include "ConstantEmitter.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"
Richard Trieu63688182018-12-11 03:18:39 +000028#include "clang/Basic/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 =
Yaxun Liu39195062017-08-04 18:16:31 +000051 cast<llvm::PointerType>(value->getType())->getAddressSpace();
John McCallad7c5c12011-02-08 08:22:06 +000052
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.
Yaxun Liuaefdb8e2018-06-15 15:33:22 +000063Address CodeGenFunction::CreateTempAllocaWithoutCast(llvm::Type *Ty,
64 CharUnits Align,
65 const Twine &Name,
66 llvm::Value *ArraySize) {
67 auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
68 Alloca->setAlignment(Align.getQuantity());
69 return Address(Alloca, Align);
70}
71
72/// CreateTempAlloca - This creates a alloca and inserts it into the entry
73/// block. The alloca is casted to default address space if necessary.
John McCall7f416cc2015-09-08 08:05:57 +000074Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
Yaxun Liu84744c12017-06-19 17:03:41 +000075 const Twine &Name,
76 llvm::Value *ArraySize,
Yaxun Liuaefdb8e2018-06-15 15:33:22 +000077 Address *AllocaAddr) {
78 auto Alloca = CreateTempAllocaWithoutCast(Ty, Align, Name, ArraySize);
Yaxun Liua2a9cfa2018-05-17 11:16:35 +000079 if (AllocaAddr)
Yaxun Liuaefdb8e2018-06-15 15:33:22 +000080 *AllocaAddr = Alloca;
81 llvm::Value *V = Alloca.getPointer();
Yaxun Liu84744c12017-06-19 17:03:41 +000082 // Alloca always returns a pointer in alloca address space, which may
83 // be different from the type defined by the language. For example,
84 // in C++ the auto variables are in the default address space. Therefore
85 // cast alloca to the default address space when necessary.
Yaxun Liuaefdb8e2018-06-15 15:33:22 +000086 if (getASTAllocaAddressSpace() != LangAS::Default) {
Yaxun Liu84744c12017-06-19 17:03:41 +000087 auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
Yaxun Liue45b3d52017-10-24 19:14:43 +000088 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
Yaxun Liu561ac062017-10-30 14:38:30 +000089 // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
90 // otherwise alloca is inserted at the current insertion point of the
91 // builder.
92 if (!ArraySize)
93 Builder.SetInsertPoint(AllocaInsertPt);
Yaxun Liu84744c12017-06-19 17:03:41 +000094 V = getTargetHooks().performAddrSpaceCast(
95 *this, V, getASTAllocaAddressSpace(), LangAS::Default,
96 Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
97 }
98
99 return Address(V, Align);
John McCall7f416cc2015-09-08 08:05:57 +0000100}
101
Yaxun Liu84744c12017-06-19 17:03:41 +0000102/// CreateTempAlloca - This creates an alloca and inserts it into the entry
103/// block if \p ArraySize is nullptr, otherwise inserts it at the current
104/// insertion point of the builder.
Chris Lattner2192fe52011-07-18 04:24:23 +0000105llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Yaxun Liu84744c12017-06-19 17:03:41 +0000106 const Twine &Name,
107 llvm::Value *ArraySize) {
108 if (ArraySize)
109 return Builder.CreateAlloca(Ty, ArraySize, Name);
Matt Arsenault502ad602017-04-10 22:28:02 +0000110 return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
Yaxun Liu84744c12017-06-19 17:03:41 +0000111 ArraySize, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +0000112}
Chris Lattner8394d792007-06-05 20:53:16 +0000113
John McCall7f416cc2015-09-08 08:05:57 +0000114/// CreateDefaultAlignTempAlloca - This creates an alloca with the
115/// default alignment of the corresponding LLVM type, which is *not*
116/// guaranteed to be related in any way to the expected alignment of
117/// an AST type that might have been lowered to Ty.
118Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
119 const Twine &Name) {
120 CharUnits Align =
121 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
122 return CreateTempAlloca(Ty, Align, Name);
123}
124
125void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
126 assert(isa<llvm::AllocaInst>(Var.getPointer()));
127 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
128 Store->setAlignment(Var.getAlignment().getQuantity());
John McCall2e6567a2010-04-22 01:10:34 +0000129 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000130 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
John McCall2e6567a2010-04-22 01:10:34 +0000131}
132
John McCall7f416cc2015-09-08 08:05:57 +0000133Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +0000134 CharUnits Align = getContext().getTypeAlignInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +0000135 return CreateTempAlloca(ConvertType(Ty), Align, Name);
Daniel Dunbard0049182010-02-16 19:44:13 +0000136}
137
Yaxun Liu84744c12017-06-19 17:03:41 +0000138Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
Yaxun Liuaefdb8e2018-06-15 15:33:22 +0000139 Address *Alloca) {
Daniel Dunbara7566f12010-02-09 02:48:28 +0000140 // FIXME: Should we prefer the preferred type alignment here?
Yaxun Liuaefdb8e2018-06-15 15:33:22 +0000141 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name, Alloca);
John McCall7f416cc2015-09-08 08:05:57 +0000142}
143
144Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
Yaxun Liuaefdb8e2018-06-15 15:33:22 +0000145 const Twine &Name, Address *Alloca) {
Yaxun Liua2a9cfa2018-05-17 11:16:35 +0000146 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name,
Yaxun Liuaefdb8e2018-06-15 15:33:22 +0000147 /*ArraySize=*/nullptr, Alloca);
148}
149
150Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty, CharUnits Align,
151 const Twine &Name) {
152 return CreateTempAllocaWithoutCast(ConvertTypeForMem(Ty), Align, Name);
153}
154
155Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty,
156 const Twine &Name) {
157 return CreateMemTempWithoutCast(Ty, getContext().getTypeAlignInChars(Ty),
158 Name);
Daniel Dunbara7566f12010-02-09 02:48:28 +0000159}
160
Chris Lattner8394d792007-06-05 20:53:16 +0000161/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
162/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000163llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000164 PGO.setCurrentStmt(E);
John McCall7a9aac22010-08-23 01:21:21 +0000165 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +0000166 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +0000167 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +0000168 }
John McCall7a9aac22010-08-23 01:21:21 +0000169
170 QualType BoolTy = getContext().BoolTy;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000171 SourceLocation Loc = E->getExprLoc();
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000172 if (!E->getType()->isAnyComplexType())
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000173 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +0000174
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000175 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
176 Loc);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000177}
178
John McCalla2342eb2010-12-05 02:00:02 +0000179/// EmitIgnoredExpr - Emit code to compute the specified expression,
180/// ignoring the result.
181void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
182 if (E->isRValue())
183 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
184
185 // Just emit it as an l-value and drop the result.
186 EmitLValue(E);
187}
188
John McCall7a626f62010-09-15 10:14:12 +0000189/// EmitAnyExpr - Emit code to compute the specified expression which
190/// can have any type. The result is returned as an RValue struct.
191/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000192/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000193RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
194 AggValueSlot aggSlot,
195 bool ignoreResult) {
John McCall47fb9502013-03-07 21:37:08 +0000196 switch (getEvaluationKind(E->getType())) {
197 case TEK_Scalar:
John McCall4e8ca4f2012-07-02 23:58:38 +0000198 return RValue::get(EmitScalarExpr(E, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000199 case TEK_Complex:
John McCall4e8ca4f2012-07-02 23:58:38 +0000200 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000201 case TEK_Aggregate:
202 if (!ignoreResult && aggSlot.isIgnored())
203 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
204 EmitAggExpr(E, aggSlot);
205 return aggSlot.asRValue();
206 }
207 llvm_unreachable("bad evaluation kind");
Chris Lattner4647a212007-08-31 22:49:20 +0000208}
209
George Burgess IVab1e5a12018-03-08 00:22:04 +0000210/// EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will
Mike Stump4a3999f2009-09-09 13:00:44 +0000211/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000212RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
213 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000214
John McCall47fb9502013-03-07 21:37:08 +0000215 if (hasAggregateEvaluationKind(E->getType()))
John McCall7a626f62010-09-15 10:14:12 +0000216 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
217 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000218}
219
John McCall21886962010-04-21 10:05:39 +0000220/// EmitAnyExprToMem - Evaluate an expression into a given memory
221/// location.
222void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000223 Address Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000224 Qualifiers Quals,
225 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000226 // FIXME: This function should take an LValue as an argument.
John McCall47fb9502013-03-07 21:37:08 +0000227 switch (getEvaluationKind(E->getType())) {
228 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000229 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
John McCall47fb9502013-03-07 21:37:08 +0000230 /*isInit*/ false);
231 return;
232
233 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000234 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000235 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000236 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +0000237 AggValueSlot::IsAliased_t(!IsInit),
238 AggValueSlot::MayOverlap));
John McCall47fb9502013-03-07 21:37:08 +0000239 return;
240 }
241
242 case TEK_Scalar: {
John McCall21886962010-04-21 10:05:39 +0000243 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000244 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000245 EmitStoreThroughLValue(RV, LV);
John McCall47fb9502013-03-07 21:37:08 +0000246 return;
John McCall21886962010-04-21 10:05:39 +0000247 }
John McCall47fb9502013-03-07 21:37:08 +0000248 }
249 llvm_unreachable("bad evaluation kind");
John McCall21886962010-04-21 10:05:39 +0000250}
251
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000252static void
253pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
John McCall7f416cc2015-09-08 08:05:57 +0000254 const Expr *E, Address ReferenceTemporary) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000255 // Objective-C++ ARC:
256 // If we are binding a reference to a temporary that has ownership, we
257 // need to perform retain/release operations on the temporary.
Richard Smith736a9472013-06-12 20:42:33 +0000258 //
259 // FIXME: This should be looking at E, not M.
John McCall460ce582015-10-22 18:38:17 +0000260 if (auto Lifetime = M->getType().getObjCLifetime()) {
261 switch (Lifetime) {
Richard Smith736a9472013-06-12 20:42:33 +0000262 case Qualifiers::OCL_None:
263 case Qualifiers::OCL_ExplicitNone:
264 // Carry on to normal cleanup handling.
265 break;
Sebastian Redl29526f02011-11-27 16:50:07 +0000266
Richard Smith736a9472013-06-12 20:42:33 +0000267 case Qualifiers::OCL_Autoreleasing:
268 // Nothing to do; cleaned up by an autorelease pool.
269 return;
270
271 case Qualifiers::OCL_Strong:
272 case Qualifiers::OCL_Weak:
273 switch (StorageDuration Duration = M->getStorageDuration()) {
274 case SD_Static:
275 // Note: we intentionally do not register a cleanup to release
276 // the object on program termination.
277 return;
278
279 case SD_Thread:
280 // FIXME: We should probably register a cleanup in this case.
281 return;
282
283 case SD_Automatic:
284 case SD_FullExpression:
Richard Smith736a9472013-06-12 20:42:33 +0000285 CodeGenFunction::Destroyer *Destroy;
286 CleanupKind CleanupKind;
287 if (Lifetime == Qualifiers::OCL_Strong) {
288 const ValueDecl *VD = M->getExtendingDecl();
289 bool Precise =
290 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
291 CleanupKind = CGF.getARCCleanupKind();
292 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
293 : &CodeGenFunction::destroyARCStrongImprecise;
294 } else {
295 // __weak objects always get EH cleanups; otherwise, exceptions
296 // could cause really nasty crashes instead of mere leaks.
297 CleanupKind = NormalAndEHCleanup;
298 Destroy = &CodeGenFunction::destroyARCWeak;
299 }
300 if (Duration == SD_FullExpression)
301 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000302 M->getType(), *Destroy,
Richard Smith736a9472013-06-12 20:42:33 +0000303 CleanupKind & EHCleanup);
304 else
305 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000306 M->getType(),
Richard Smith736a9472013-06-12 20:42:33 +0000307 *Destroy, CleanupKind & EHCleanup);
308 return;
309
310 case SD_Dynamic:
311 llvm_unreachable("temporary cannot have dynamic storage duration");
312 }
313 llvm_unreachable("unknown storage duration");
314 }
315 }
316
Craig Topper8a13c412014-05-21 05:09:00 +0000317 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
Richard Smith736a9472013-06-12 20:42:33 +0000318 if (const RecordType *RT =
319 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
320 // Get the destructor for the reference temporary.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000321 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith736a9472013-06-12 20:42:33 +0000322 if (!ClassDecl->hasTrivialDestructor())
323 ReferenceTemporaryDtor = ClassDecl->getDestructor();
324 }
325
326 if (!ReferenceTemporaryDtor)
327 return;
328
329 // Call the destructor for the temporary.
330 switch (M->getStorageDuration()) {
331 case SD_Static:
332 case SD_Thread: {
333 llvm::Constant *CleanupFn;
334 llvm::Constant *CleanupArg;
335 if (E->getType()->isArrayType()) {
336 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
John McCall7f416cc2015-09-08 08:05:57 +0000337 ReferenceTemporary, E->getType(),
David Blaikieebe87e12013-08-27 23:57:18 +0000338 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
339 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
Richard Smith736a9472013-06-12 20:42:33 +0000340 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
341 } else {
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000342 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
343 StructorType::Complete);
John McCall7f416cc2015-09-08 08:05:57 +0000344 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
Richard Smith736a9472013-06-12 20:42:33 +0000345 }
346 CGF.CGM.getCXXABI().registerGlobalDtor(
347 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
348 break;
349 }
350
351 case SD_FullExpression:
352 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
353 CodeGenFunction::destroyCXXObject,
354 CGF.getLangOpts().Exceptions);
355 break;
356
357 case SD_Automatic:
358 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
359 ReferenceTemporary, E->getType(),
360 CodeGenFunction::destroyCXXObject,
361 CGF.getLangOpts().Exceptions);
362 break;
363
364 case SD_Dynamic:
365 llvm_unreachable("temporary cannot have dynamic storage duration");
366 }
367}
368
Yaxun Liucbf647c2017-07-08 13:24:52 +0000369static Address createReferenceTemporary(CodeGenFunction &CGF,
370 const MaterializeTemporaryExpr *M,
Yaxun Liua2a9cfa2018-05-17 11:16:35 +0000371 const Expr *Inner,
372 Address *Alloca = nullptr) {
Yaxun Liucbf647c2017-07-08 13:24:52 +0000373 auto &TCG = CGF.getTargetHooks();
Richard Smith736a9472013-06-12 20:42:33 +0000374 switch (M->getStorageDuration()) {
375 case SD_FullExpression:
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000376 case SD_Automatic: {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000377 // If we have a constant temporary array or record try to promote it into a
378 // constant global under the same rules a normal constant would've been
379 // promoted. This is easier on the optimizer and generally emits fewer
380 // instructions.
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000381 QualType Ty = Inner->getType();
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000382 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000383 (Ty->isArrayType() || Ty->isRecordType()) &&
384 CGF.CGM.isTypeConstant(Ty, true))
John McCallde0fe072017-08-15 21:42:52 +0000385 if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
Yaxun Liucbf647c2017-07-08 13:24:52 +0000386 if (auto AddrSpace = CGF.getTarget().getConstantAddressSpace()) {
387 auto AS = AddrSpace.getValue();
388 auto *GV = new llvm::GlobalVariable(
389 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
390 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
391 llvm::GlobalValue::NotThreadLocal,
392 CGF.getContext().getTargetAddressSpace(AS));
393 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
394 GV->setAlignment(alignment.getQuantity());
395 llvm::Constant *C = GV;
396 if (AS != LangAS::Default)
397 C = TCG.performAddrSpaceCast(
398 CGF.CGM, GV, AS, LangAS::Default,
399 GV->getValueType()->getPointerTo(
400 CGF.getContext().getTargetAddressSpace(LangAS::Default)));
401 // FIXME: Should we put the new global into a COMDAT?
402 return Address(C, alignment);
403 }
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000404 }
Yaxun Liua2a9cfa2018-05-17 11:16:35 +0000405 return CGF.CreateMemTemp(Ty, "ref.tmp", Alloca);
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000406 }
Richard Smith736a9472013-06-12 20:42:33 +0000407 case SD_Thread:
408 case SD_Static:
Hans Wennborgf9d865b2015-03-17 16:38:58 +0000409 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
Richard Smith736a9472013-06-12 20:42:33 +0000410
411 case SD_Dynamic:
412 llvm_unreachable("temporary can't have dynamic storage duration");
413 }
414 llvm_unreachable("unknown storage duration");
415}
416
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000417LValue CodeGenFunction::
418EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000419 const Expr *E = M->GetTemporaryExpr();
Richard Smith7c5d4dc2013-06-11 02:41:00 +0000420
Erik Pilkington1e368822019-01-04 18:33:06 +0000421 assert((!M->getExtendingDecl() || !isa<VarDecl>(M->getExtendingDecl()) ||
422 !cast<VarDecl>(M->getExtendingDecl())->isARCPseudoStrong()) &&
423 "Reference should never be pseudo-strong!");
424
425 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
426 // as that will cause the lifetime adjustment to be lost for ARC
John McCall460ce582015-10-22 18:38:17 +0000427 auto ownership = M->getType().getObjCLifetime();
428 if (ownership != Qualifiers::OCL_None &&
429 ownership != Qualifiers::OCL_ExplicitNone) {
John McCall7f416cc2015-09-08 08:05:57 +0000430 Address Object = createReferenceTemporary(*this, M, E);
431 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
432 Object = Address(llvm::ConstantExpr::getBitCast(Var,
433 ConvertTypeForMem(E->getType())
434 ->getPointerTo(Object.getAddressSpace())),
435 Object.getAlignment());
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000436
437 // createReferenceTemporary will promote the temporary to a global with a
438 // constant initializer if it can. It can only do this to a value of
439 // ARC-manageable type if the value is global and therefore "immune" to
440 // ref-counting operations. Therefore we have no need to emit either a
441 // dynamic initialization or a cleanup and we can just return the address
442 // of the temporary.
443 if (Var->hasInitializer())
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000444 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000445
Richard Smitha509f2f2013-06-14 03:07:01 +0000446 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
447 }
John McCall7f416cc2015-09-08 08:05:57 +0000448 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000449 AlignmentSource::Decl);
Richard Smitha509f2f2013-06-14 03:07:01 +0000450
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000451 switch (getEvaluationKind(E->getType())) {
452 default: llvm_unreachable("expected scalar or aggregate expression");
453 case TEK_Scalar:
454 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
455 break;
456 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000457 EmitAggExpr(E, AggValueSlot::forAddr(Object,
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000458 E->getType().getQualifiers(),
459 AggValueSlot::IsDestructed,
460 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +0000461 AggValueSlot::IsNotAliased,
462 AggValueSlot::DoesNotOverlap));
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000463 break;
464 }
465 }
Richard Smith736a9472013-06-12 20:42:33 +0000466
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000467 pushTemporaryCleanup(*this, M, E, Object);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000468 return RefTempDst;
Jordan Roseb1312a52013-04-11 00:58:58 +0000469 }
470
Richard Smithf3fabd22013-06-03 00:17:11 +0000471 SmallVector<const Expr *, 2> CommaLHSs;
Jordan Roseb1312a52013-04-11 00:58:58 +0000472 SmallVector<SubobjectAdjustment, 2> Adjustments;
Richard Smithf3fabd22013-06-03 00:17:11 +0000473 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
474
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000475 for (const auto &Ignored : CommaLHSs)
476 EmitIgnoredExpr(Ignored);
Richard Smithf3fabd22013-06-03 00:17:11 +0000477
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000478 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
Richard Smith736a9472013-06-12 20:42:33 +0000479 if (opaque->getType()->isRecordType()) {
480 assert(Adjustments.empty());
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000481 return EmitOpaqueValueLValue(opaque);
Jordan Roseb1312a52013-04-11 00:58:58 +0000482 }
483 }
484
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000485 // Create and initialize the reference temporary.
Yaxun Liua2a9cfa2018-05-17 11:16:35 +0000486 Address Alloca = Address::invalid();
487 Address Object = createReferenceTemporary(*this, M, E, &Alloca);
Yaxun Liucbf647c2017-07-08 13:24:52 +0000488 if (auto *Var = dyn_cast<llvm::GlobalVariable>(
489 Object.getPointer()->stripPointerCasts())) {
John McCall7f416cc2015-09-08 08:05:57 +0000490 Object = Address(llvm::ConstantExpr::getBitCast(
Yaxun Liucbf647c2017-07-08 13:24:52 +0000491 cast<llvm::Constant>(Object.getPointer()),
492 ConvertTypeForMem(E->getType())->getPointerTo()),
John McCall7f416cc2015-09-08 08:05:57 +0000493 Object.getAlignment());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000494 // If the temporary is a global and has a constant initializer or is a
495 // constant temporary that we promoted to a global, we may have already
496 // initialized it.
Richard Smitha509f2f2013-06-14 03:07:01 +0000497 if (!Var->hasInitializer()) {
498 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
499 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
500 }
501 } else {
Tim Shen421119f2016-07-01 21:08:47 +0000502 switch (M->getStorageDuration()) {
503 case SD_Automatic:
Tim Shen421119f2016-07-01 21:08:47 +0000504 if (auto *Size = EmitLifetimeStart(
Yaxun Liua2a9cfa2018-05-17 11:16:35 +0000505 CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
506 Alloca.getPointer())) {
Richard Smithaa140bf2018-08-04 01:25:06 +0000507 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
508 Alloca, Size);
Tim Shen421119f2016-07-01 21:08:47 +0000509 }
510 break;
Richard Smithaa140bf2018-08-04 01:25:06 +0000511
512 case SD_FullExpression: {
513 if (!ShouldEmitLifetimeMarkers)
514 break;
515
516 // Avoid creating a conditional cleanup just to hold an llvm.lifetime.end
517 // marker. Instead, start the lifetime of a conditional temporary earlier
518 // so that it's unconditional. Don't do this in ASan's use-after-scope
519 // mode so that it gets the more precise lifetime marks. If the type has
520 // a non-trivial destructor, we'll have a cleanup block for it anyway,
521 // so this typically doesn't help; skip it in that case.
522 ConditionalEvaluation *OldConditional = nullptr;
523 CGBuilderTy::InsertPoint OldIP;
524 if (isInConditionalBranch() && !E->getType().isDestructedType() &&
525 !CGM.getCodeGenOpts().SanitizeAddressUseAfterScope) {
526 OldConditional = OutermostConditional;
527 OutermostConditional = nullptr;
528
529 OldIP = Builder.saveIP();
530 llvm::BasicBlock *Block = OldConditional->getStartingBlock();
531 Builder.restoreIP(CGBuilderTy::InsertPoint(
532 Block, llvm::BasicBlock::iterator(Block->back())));
533 }
534
535 if (auto *Size = EmitLifetimeStart(
536 CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
537 Alloca.getPointer())) {
538 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Alloca,
539 Size);
540 }
541
542 if (OldConditional) {
543 OutermostConditional = OldConditional;
544 Builder.restoreIP(OldIP);
545 }
546 break;
547 }
548
Tim Shen421119f2016-07-01 21:08:47 +0000549 default:
550 break;
551 }
Richard Smitha509f2f2013-06-14 03:07:01 +0000552 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
553 }
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000554 pushTemporaryCleanup(*this, M, E, Object);
Jordan Roseb1312a52013-04-11 00:58:58 +0000555
Richard Smith736a9472013-06-12 20:42:33 +0000556 // Perform derived-to-base casts and/or field accesses, to get from the
557 // temporary object we created (and, potentially, for which we extended
558 // the lifetime) to the subobject we're binding the reference to.
559 for (unsigned I = Adjustments.size(); I != 0; --I) {
560 SubobjectAdjustment &Adjustment = Adjustments[I-1];
561 switch (Adjustment.Kind) {
562 case SubobjectAdjustment::DerivedToBaseAdjustment:
563 Object =
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000564 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
565 Adjustment.DerivedToBase.BasePath->path_begin(),
566 Adjustment.DerivedToBase.BasePath->path_end(),
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000567 /*NullCheckValue=*/ false, E->getExprLoc());
Richard Smith736a9472013-06-12 20:42:33 +0000568 break;
Richard Smithf3fabd22013-06-03 00:17:11 +0000569
Richard Smith736a9472013-06-12 20:42:33 +0000570 case SubobjectAdjustment::FieldAdjustment: {
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000571 LValue LV = MakeAddrLValue(Object, E->getType(), AlignmentSource::Decl);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000572 LV = EmitLValueForField(LV, Adjustment.Field);
Richard Smith736a9472013-06-12 20:42:33 +0000573 assert(LV.isSimple() &&
574 "materialized temporary field is not a simple lvalue");
575 Object = LV.getAddress();
576 break;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000577 }
578
Richard Smith736a9472013-06-12 20:42:33 +0000579 case SubobjectAdjustment::MemberPointerAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000580 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
John McCall7f416cc2015-09-08 08:05:57 +0000581 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
582 Adjustment.Ptr.MPT);
Richard Smith736a9472013-06-12 20:42:33 +0000583 break;
584 }
585 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000586 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000587
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000588 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000589}
590
591RValue
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000592CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
593 // Emit the expression as an lvalue.
594 LValue LV = EmitLValue(E);
595 assert(LV.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000596 llvm::Value *Value = LV.getPointer();
Richard Smith736a9472013-06-12 20:42:33 +0000597
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000598 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000599 // C++11 [dcl.ref]p5 (as amended by core issue 453):
600 // If a glvalue to which a reference is directly bound designates neither
601 // an existing object or function of an appropriate type nor a region of
602 // storage of suitable size and alignment to contain an object of the
603 // reference's type, the behavior is undefined.
604 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000605 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000606 }
John McCall8680f872010-07-21 06:29:51 +0000607
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000608 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000609}
610
611
Mike Stump4a3999f2009-09-09 13:00:44 +0000612/// getAccessedFieldNo - Given an encoded value and a result number, return the
613/// input field number being accessed.
614unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000615 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000616 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
617 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000618}
619
Richard Smith4d3110a2012-10-25 02:14:12 +0000620/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
621static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
622 llvm::Value *High) {
623 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
624 llvm::Value *K47 = Builder.getInt64(47);
625 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
626 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
627 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
628 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
629 return Builder.CreateMul(B1, KMul);
630}
631
Vedant Kumar24792e32017-10-03 01:27:25 +0000632bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) {
633 return TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
Stephan Bergmannd71ad172017-12-28 12:45:41 +0000634 TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation;
Vedant Kumar24792e32017-10-03 01:27:25 +0000635}
636
637bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) {
638 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
639 return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
640 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
641 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
Stephan Bergmannd71ad172017-12-28 12:45:41 +0000642 TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation);
Vedant Kumar24792e32017-10-03 01:27:25 +0000643}
644
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000645bool CodeGenFunction::sanitizePerformTypeCheck() const {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000646 return SanOpts.has(SanitizerKind::Null) |
647 SanOpts.has(SanitizerKind::Alignment) |
648 SanOpts.has(SanitizerKind::ObjectSize) |
649 SanOpts.has(SanitizerKind::Vptr);
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000650}
651
Richard Smithe30752c2012-10-09 19:52:38 +0000652void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +0000653 llvm::Value *Ptr, QualType Ty,
Vedant Kumar18348ea2017-02-17 23:22:55 +0000654 CharUnits Alignment,
655 SanitizerSet SkippedChecks) {
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000656 if (!sanitizePerformTypeCheck())
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000657 return;
658
Richard Smith2d8b2942012-11-01 07:22:08 +0000659 // Don't check pointers outside the default address space. The null check
660 // isn't correct, the object-size check isn't supported by LLVM, and we can't
661 // communicate the addresses to the runtime handler for the vptr check.
John McCall7f416cc2015-09-08 08:05:57 +0000662 if (Ptr->getType()->getPointerAddressSpace())
Richard Smith2d8b2942012-11-01 07:22:08 +0000663 return;
664
Vedant Kumarc420d142017-06-16 03:27:36 +0000665 // Don't check pointers to volatile data. The behavior here is implementation-
666 // defined.
667 if (Ty.isVolatileQualified())
668 return;
669
Alexey Samsonov24cad992014-07-17 18:46:27 +0000670 SanitizerScope SanScope(this);
671
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000672 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
Craig Topper8a13c412014-05-21 05:09:00 +0000673 llvm::BasicBlock *Done = nullptr;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000674
Vedant Kumare859ebb2017-04-26 02:17:21 +0000675 // Quickly determine whether we have a pointer to an alloca. It's possible
676 // to skip null checks, and some alignment checks, for these pointers. This
677 // can reduce compile-time significantly.
678 auto PtrToAlloca =
679 dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCastsNoFollowAliases());
680
Vedant Kumara8ff3b32017-10-03 01:27:26 +0000681 llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000682 llvm::Value *IsNonNull = nullptr;
683 bool IsGuaranteedNonNull =
684 SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
Vedant Kumar24792e32017-10-03 01:27:25 +0000685 bool AllowNullPointers = isNullPointerAllowed(TCK);
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000686 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000687 !IsGuaranteedNonNull) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000688 // The glvalue must not be an empty glvalue.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000689 IsNonNull = Builder.CreateIsNotNull(Ptr);
Richard Smith2c5868c2013-02-13 21:18:23 +0000690
Vedant Kumardbbdda42017-04-17 22:26:10 +0000691 // The IR builder can constant-fold the null check if the pointer points to
692 // a constant.
Vedant Kumara8ff3b32017-10-03 01:27:26 +0000693 IsGuaranteedNonNull = IsNonNull == True;
Vedant Kumardbbdda42017-04-17 22:26:10 +0000694
695 // Skip the null check if the pointer is known to be non-null.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000696 if (!IsGuaranteedNonNull) {
Vedant Kumardbbdda42017-04-17 22:26:10 +0000697 if (AllowNullPointers) {
698 // When performing pointer casts, it's OK if the value is null.
699 // Skip the remaining checks in that case.
700 Done = createBasicBlock("null");
701 llvm::BasicBlock *Rest = createBasicBlock("not.null");
702 Builder.CreateCondBr(IsNonNull, Rest, Done);
703 EmitBlock(Rest);
704 } else {
705 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
706 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000707 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000708 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000709
Vedant Kumar18348ea2017-02-17 23:22:55 +0000710 if (SanOpts.has(SanitizerKind::ObjectSize) &&
711 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
712 !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000713 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000714
Richard Smith69d0d262012-08-24 00:54:33 +0000715 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000716 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000717 // to check this.
Matt Arsenault2f152632013-10-07 19:00:18 +0000718 // FIXME: Get object address space
719 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
720 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smith69d0d262012-08-24 00:54:33 +0000721 llvm::Value *Min = Builder.getFalse();
George Burgess IVa63f9152017-03-21 20:09:35 +0000722 llvm::Value *NullIsUnknown = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +0000723 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
George Burgess IVa63f9152017-03-21 20:09:35 +0000724 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
725 Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}),
726 llvm::ConstantInt::get(IntPtrTy, Size));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000727 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
Richard Smithe30752c2012-10-09 19:52:38 +0000728 }
Richard Smith69d0d262012-08-24 00:54:33 +0000729
Richard Smithb1b0ab42012-11-05 22:21:05 +0000730 uint64_t AlignVal = 0;
Vedant Kumar8a715332017-10-03 01:27:24 +0000731 llvm::Value *PtrAsInt = nullptr;
Richard Smithb1b0ab42012-11-05 22:21:05 +0000732
Vedant Kumar18348ea2017-02-17 23:22:55 +0000733 if (SanOpts.has(SanitizerKind::Alignment) &&
734 !SkippedChecks.has(SanitizerKind::Alignment)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000735 AlignVal = Alignment.getQuantity();
736 if (!Ty->isIncompleteType() && !AlignVal)
737 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
738
Richard Smith69d0d262012-08-24 00:54:33 +0000739 // The glvalue must be suitably aligned.
Vedant Kumare859ebb2017-04-26 02:17:21 +0000740 if (AlignVal > 1 &&
741 (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
Vedant Kumar8a715332017-10-03 01:27:24 +0000742 PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
743 llvm::Value *Align = Builder.CreateAnd(
744 PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000745 llvm::Value *Aligned =
Vedant Kumar8a715332017-10-03 01:27:24 +0000746 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
Vedant Kumara8ff3b32017-10-03 01:27:26 +0000747 if (Aligned != True)
748 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000749 }
Richard Smith69d0d262012-08-24 00:54:33 +0000750 }
751
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000752 if (Checks.size() > 0) {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000753 // Make sure we're not losing information. Alignment needs to be a power of
754 // 2
755 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
Richard Smithe30752c2012-10-09 19:52:38 +0000756 llvm::Constant *StaticData[] = {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000757 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
758 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
759 llvm::ConstantInt::get(Int8Ty, TCK)};
Vedant Kumar8a715332017-10-03 01:27:24 +0000760 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData,
761 PtrAsInt ? PtrAsInt : Ptr);
Richard Smithe30752c2012-10-09 19:52:38 +0000762 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000763
Richard Smithb1b0ab42012-11-05 22:21:05 +0000764 // If possible, check that the vptr indicates that there is a subobject of
765 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000766 //
767 // C++11 [basic.life]p5,6:
768 // [For storage which does not refer to an object within its lifetime]
769 // The program has undefined behavior if:
770 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000771 // or call a non-static member function
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000772 if (SanOpts.has(SanitizerKind::Vptr) &&
Vedant Kumar24792e32017-10-03 01:27:25 +0000773 !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000774 // Ensure that the pointer is non-null before loading it. If there is no
Vedant Kumara0c36712017-08-02 18:10:31 +0000775 // compile-time guarantee, reuse the run-time null check or emit a new one.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000776 if (!IsGuaranteedNonNull) {
Vedant Kumara0c36712017-08-02 18:10:31 +0000777 if (!IsNonNull)
778 IsNonNull = Builder.CreateIsNotNull(Ptr);
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000779 if (!Done)
780 Done = createBasicBlock("vptr.null");
781 llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
782 Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
783 EmitBlock(VptrNotNull);
784 }
785
Richard Smith4d3110a2012-10-25 02:14:12 +0000786 // Compute a hash of the mangled name of the type.
787 //
788 // FIXME: This is not guaranteed to be deterministic! Move to a
789 // fingerprinting mechanism once LLVM provides one. For the time
790 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000791 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000792 llvm::raw_svector_ostream Out(MangledName);
793 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
794 Out);
Richard Smith4d3110a2012-10-25 02:14:12 +0000795
Alexey Samsonov84856012014-07-10 22:34:19 +0000796 // Blacklist based on the mangled type.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000797 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +0000798 SanitizerKind::Vptr, Out.str())) {
Alexey Samsonov84856012014-07-10 22:34:19 +0000799 llvm::hash_code TypeHash = hash_value(Out.str());
Richard Smith4d3110a2012-10-25 02:14:12 +0000800
Alexey Samsonov84856012014-07-10 22:34:19 +0000801 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
802 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
803 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
John McCall7f416cc2015-09-08 08:05:57 +0000804 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000805 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
806 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
Richard Smith4d3110a2012-10-25 02:14:12 +0000807
Alexey Samsonov84856012014-07-10 22:34:19 +0000808 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
809 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
Richard Smith4d3110a2012-10-25 02:14:12 +0000810
Alexey Samsonov84856012014-07-10 22:34:19 +0000811 // Look the hash up in our cache.
812 const int CacheSize = 128;
813 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
814 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
815 "__ubsan_vptr_type_cache");
816 llvm::Value *Slot = Builder.CreateAnd(Hash,
817 llvm::ConstantInt::get(IntPtrTy,
818 CacheSize-1));
819 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
820 llvm::Value *CacheVal =
John McCall7f416cc2015-09-08 08:05:57 +0000821 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
822 getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000823
824 // If the hash isn't in the cache, call a runtime handler to perform the
825 // hard work of checking whether the vptr is for an object of the right
826 // type. This will either fill in the cache and return, or produce a
827 // diagnostic.
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000828 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
Alexey Samsonov84856012014-07-10 22:34:19 +0000829 llvm::Constant *StaticData[] = {
830 EmitCheckSourceLocation(Loc),
831 EmitCheckTypeDescriptor(Ty),
832 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
833 llvm::ConstantInt::get(Int8Ty, TCK)
834 };
John McCall7f416cc2015-09-08 08:05:57 +0000835 llvm::Value *DynamicData[] = { Ptr, Hash };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000836 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000837 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
838 DynamicData);
Alexey Samsonov84856012014-07-10 22:34:19 +0000839 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000840 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000841
842 if (Done) {
843 Builder.CreateBr(Done);
844 EmitBlock(Done);
845 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000846}
Chris Lattner4647a212007-08-31 22:49:20 +0000847
Richard Smith539e4a72013-02-23 02:53:19 +0000848/// Determine whether this expression refers to a flexible array member in a
849/// struct. We disable array bounds checks for such members.
850static bool isFlexibleArrayMemberExpr(const Expr *E) {
851 // For compatibility with existing code, we treat arrays of length 0 or
852 // 1 as flexible array members.
853 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000854 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000855 if (CAT->getSize().ugt(1))
856 return false;
857 } else if (!isa<IncompleteArrayType>(AT))
858 return false;
859
860 E = E->IgnoreParens();
861
862 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000863 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000864 // FIXME: If the base type of the member expr is not FD->getParent(),
865 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000866 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith539e4a72013-02-23 02:53:19 +0000867 RecordDecl::field_iterator FI(
868 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
869 return ++FI == FD->getParent()->field_end();
870 }
Vedant Kumare356f1a2016-10-04 20:36:04 +0000871 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
872 return IRE->getDecl()->getNextIvar() == nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000873 }
874
875 return false;
876}
877
Vedant Kumar36347d92017-12-08 01:51:47 +0000878llvm::Value *CodeGenFunction::LoadPassedObjectSize(const Expr *E,
879 QualType EltTy) {
880 ASTContext &C = getContext();
881 uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity();
882 if (!EltSize)
883 return nullptr;
884
885 auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
886 if (!ArrayDeclRef)
887 return nullptr;
888
889 auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
890 if (!ParamDecl)
891 return nullptr;
892
Vedant Kumar36347d92017-12-08 01:51:47 +0000893 auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
894 if (!POSAttr)
895 return nullptr;
896
897 // Don't load the size if it's a lower bound.
898 int POSType = POSAttr->getType();
899 if (POSType != 0 && POSType != 1)
900 return nullptr;
901
902 // Find the implicit size parameter.
903 auto PassedSizeIt = SizeArguments.find(ParamDecl);
904 if (PassedSizeIt == SizeArguments.end())
905 return nullptr;
906
907 const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
908 assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
909 Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
910 llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false,
911 C.getSizeType(), E->getExprLoc());
912 llvm::Value *SizeOfElement =
913 llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
914 return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
915}
916
Richard Smith539e4a72013-02-23 02:53:19 +0000917/// If Base is known to point to the start of an array, return the length of
918/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000919static llvm::Value *getArrayIndexingBound(
920 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000921 // For the vector indexing extension, the bound is the number of elements.
922 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
923 IndexedType = Base->getType();
924 return CGF.Builder.getInt32(VT->getNumElements());
925 }
926
927 Base = Base->IgnoreParens();
928
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000929 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000930 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
931 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
932 IndexedType = CE->getSubExpr()->getType();
933 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000934 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000935 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000936 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Sander de Smalen891af03a2018-02-03 13:55:59 +0000937 return CGF.getVLASize(VAT).NumElts;
Vedant Kumar36347d92017-12-08 01:51:47 +0000938 // Ignore pass_object_size here. It's not applicable on decayed pointers.
Richard Smith539e4a72013-02-23 02:53:19 +0000939 }
940 }
941
Vedant Kumar36347d92017-12-08 01:51:47 +0000942 QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
943 if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) {
944 IndexedType = Base->getType();
945 return POS;
946 }
947
Craig Topper8a13c412014-05-21 05:09:00 +0000948 return nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000949}
950
951void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
952 llvm::Value *Index, QualType IndexType,
953 bool Accessed) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000954 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
Richard Smith6b53e222013-10-22 22:51:04 +0000955 "should not be called unless adding bounds checks");
Alexey Samsonov24cad992014-07-17 18:46:27 +0000956 SanitizerScope SanScope(this);
Richard Smith2847b222013-02-24 01:56:24 +0000957
Richard Smith539e4a72013-02-23 02:53:19 +0000958 QualType IndexedType;
959 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
960 if (!Bound)
961 return;
962
963 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
964 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
965 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
966
967 llvm::Constant *StaticData[] = {
968 EmitCheckSourceLocation(E->getExprLoc()),
969 EmitCheckTypeDescriptor(IndexedType),
970 EmitCheckTypeDescriptor(IndexType)
971 };
972 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
973 : Builder.CreateICmpULE(IndexVal, BoundVal);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000974 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
975 SanitizerHandler::OutOfBounds, StaticData, Index);
Richard Smith539e4a72013-02-23 02:53:19 +0000976}
977
Chris Lattner116ce8f2010-01-09 21:40:03 +0000978
Chris Lattner116ce8f2010-01-09 21:40:03 +0000979CodeGenFunction::ComplexPairTy CodeGenFunction::
980EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
981 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000982 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +0000983
Chris Lattner116ce8f2010-01-09 21:40:03 +0000984 llvm::Value *NextVal;
985 if (isa<llvm::IntegerType>(InVal.first->getType())) {
986 uint64_t AmountVal = isInc ? 1 : -1;
987 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +0000988
Chris Lattner116ce8f2010-01-09 21:40:03 +0000989 // Add the inc/dec to the real part.
990 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
991 } else {
992 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
993 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
994 if (!isInc)
995 FVal.changeSign();
996 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
Craig Topper99e79272013-07-26 05:59:26 +0000997
Chris Lattner116ce8f2010-01-09 21:40:03 +0000998 // Add the inc/dec to the real part.
999 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
1000 }
Craig Topper99e79272013-07-26 05:59:26 +00001001
Chris Lattner116ce8f2010-01-09 21:40:03 +00001002 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +00001003
Chris Lattner116ce8f2010-01-09 21:40:03 +00001004 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +00001005 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Craig Topper99e79272013-07-26 05:59:26 +00001006
Chris Lattner116ce8f2010-01-09 21:40:03 +00001007 // If this is a postinc, return the value read from memory, otherwise use the
1008 // updated value.
1009 return isPre ? IncVal : InVal;
1010}
1011
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00001012void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
1013 CodeGenFunction *CGF) {
1014 // Bind VLAs in the cast type.
1015 if (CGF && E->getType()->isVariablyModifiedType())
1016 CGF->EmitVariablyModifiedType(E->getType());
1017
1018 if (CGDebugInfo *DI = getModuleDebugInfo())
1019 DI->EmitExplicitCastType(E->getType());
1020}
1021
Chris Lattnera45c5af2007-06-02 19:47:04 +00001022//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +00001023// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +00001024//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +00001025
John McCall7f416cc2015-09-08 08:05:57 +00001026/// EmitPointerWithAlignment - Given an expression of pointer type, try to
1027/// derive a more accurate bound on the alignment of the pointer.
1028Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00001029 LValueBaseInfo *BaseInfo,
1030 TBAAAccessInfo *TBAAInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001031 // We allow this with ObjC object pointers because of fragile ABIs.
1032 assert(E->getType()->isPointerType() ||
1033 E->getType()->isObjCObjectPointerType());
1034 E = E->IgnoreParens();
1035
1036 // Casts:
1037 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00001038 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
1039 CGM.EmitExplicitCastExprType(ECE, this);
John McCall7f416cc2015-09-08 08:05:57 +00001040
1041 switch (CE->getCastKind()) {
1042 // Non-converting casts (but not C's implicit conversion from void*).
1043 case CK_BitCast:
1044 case CK_NoOp:
Anastasia Stulova0a72ed42017-09-27 14:37:00 +00001045 case CK_AddressSpaceConversion:
John McCall7f416cc2015-09-08 08:05:57 +00001046 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
1047 if (PtrTy->getPointeeType()->isVoidType())
1048 break;
1049
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00001050 LValueBaseInfo InnerBaseInfo;
1051 TBAAAccessInfo InnerTBAAInfo;
1052 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(),
1053 &InnerBaseInfo,
1054 &InnerTBAAInfo);
1055 if (BaseInfo) *BaseInfo = InnerBaseInfo;
1056 if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
John McCall7f416cc2015-09-08 08:05:57 +00001057
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00001058 if (isa<ExplicitCastExpr>(CE)) {
1059 LValueBaseInfo TargetTypeBaseInfo;
1060 TBAAAccessInfo TargetTypeTBAAInfo;
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001061 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(),
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00001062 &TargetTypeBaseInfo,
1063 &TargetTypeTBAAInfo);
1064 if (TBAAInfo)
1065 *TBAAInfo = CGM.mergeTBAAInfoForCast(*TBAAInfo,
1066 TargetTypeTBAAInfo);
1067 // If the source l-value is opaque, honor the alignment of the
1068 // casted-to type.
1069 if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
1070 if (BaseInfo)
1071 BaseInfo->mergeForCast(TargetTypeBaseInfo);
1072 Addr = Address(Addr.getPointer(), Align);
1073 }
John McCall7f416cc2015-09-08 08:05:57 +00001074 }
1075
Peter Collingbourne574975e2016-01-14 02:49:48 +00001076 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
1077 CE->getCastKind() == CK_BitCast) {
Peter Collingbourneee381ff2015-09-09 00:01:31 +00001078 if (auto PT = E->getType()->getAs<PointerType>())
1079 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
1080 /*MayBeNull=*/true,
1081 CodeGenFunction::CFITCK_UnrelatedCast,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001082 CE->getBeginLoc());
Peter Collingbourneee381ff2015-09-09 00:01:31 +00001083 }
Anastasia Stulova0a72ed42017-09-27 14:37:00 +00001084 return CE->getCastKind() != CK_AddressSpaceConversion
1085 ? Builder.CreateBitCast(Addr, ConvertType(E->getType()))
1086 : Builder.CreateAddrSpaceCast(Addr,
1087 ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00001088 }
1089 break;
1090
1091 // Array-to-pointer decay.
1092 case CK_ArrayToPointerDecay:
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00001093 return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
John McCall7f416cc2015-09-08 08:05:57 +00001094
1095 // Derived-to-base conversions.
1096 case CK_UncheckedDerivedToBase:
1097 case CK_DerivedToBase: {
Ivan A. Kosareved4f3302018-01-08 15:36:06 +00001098 // TODO: Support accesses to members of base classes in TBAA. For now, we
1099 // conservatively pretend that the complete object is of the base class
1100 // type.
1101 if (TBAAInfo)
1102 *TBAAInfo = CGM.getTBAAAccessInfo(E->getType());
1103 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +00001104 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
1105 return GetAddressOfBaseClass(Addr, Derived,
1106 CE->path_begin(), CE->path_end(),
1107 ShouldNullCheckClassCastValue(CE),
1108 CE->getExprLoc());
1109 }
1110
1111 // TODO: Is there any reason to treat base-to-derived conversions
1112 // specially?
1113 default:
1114 break;
1115 }
1116 }
1117
1118 // Unary &.
1119 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1120 if (UO->getOpcode() == UO_AddrOf) {
1121 LValue LV = EmitLValue(UO->getSubExpr());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001122 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00001123 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
John McCall7f416cc2015-09-08 08:05:57 +00001124 return LV.getAddress();
1125 }
1126 }
1127
1128 // TODO: conditional operators, comma.
1129
1130 // Otherwise, use the alignment of the type.
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00001131 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), BaseInfo,
1132 TBAAInfo);
John McCall7f416cc2015-09-08 08:05:57 +00001133 return Address(EmitScalarExpr(E), Align);
1134}
1135
Daniel Dunbarc79407f2009-02-05 07:09:07 +00001136RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001137 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001138 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +00001139
1140 switch (getEvaluationKind(Ty)) {
1141 case TEK_Complex: {
1142 llvm::Type *EltTy =
1143 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +00001144 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +00001145 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001146 }
Craig Topper99e79272013-07-26 05:59:26 +00001147
Chris Lattner65526f02010-08-23 05:26:13 +00001148 // If this is a use of an undefined aggregate type, the aggregate must have an
1149 // identifiable address. Just because the contents of the value are undefined
1150 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +00001151 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00001152 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +00001153 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +00001154 }
John McCall47fb9502013-03-07 21:37:08 +00001155
1156 case TEK_Scalar:
1157 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1158 }
1159 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +00001160}
1161
Daniel Dunbarc79407f2009-02-05 07:09:07 +00001162RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
1163 const char *Name) {
1164 ErrorUnsupported(E, Name);
1165 return GetUndefRValue(E->getType());
1166}
1167
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001168LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
1169 const char *Name) {
1170 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001171 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00001172 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
1173 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001174}
1175
Vedant Kumarffd7c882017-04-14 22:03:34 +00001176bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001177 const Expr *Base = Obj;
1178 while (!isa<CXXThisExpr>(Base)) {
1179 // The result of a dynamic_cast can be null.
1180 if (isa<CXXDynamicCastExpr>(Base))
1181 return false;
1182
1183 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1184 Base = CE->getSubExpr();
1185 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
1186 Base = PE->getSubExpr();
1187 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1188 if (UO->getOpcode() == UO_Extension)
1189 Base = UO->getSubExpr();
1190 else
1191 return false;
1192 } else {
1193 return false;
1194 }
1195 }
1196 return true;
1197}
1198
Richard Smith4d1458e2012-09-08 02:08:36 +00001199LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +00001200 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001201 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +00001202 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1203 else
1204 LV = EmitLValue(E);
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001205 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1206 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00001207 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1208 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1209 if (IsBaseCXXThis)
1210 SkippedChecks.set(SanitizerKind::Alignment, true);
1211 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001212 SkippedChecks.set(SanitizerKind::Null, true);
Vedant Kumarffd7c882017-04-14 22:03:34 +00001213 }
John McCall7f416cc2015-09-08 08:05:57 +00001214 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001215 E->getType(), LV.getAlignment(), SkippedChecks);
1216 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +00001217 return LV;
1218}
1219
Chris Lattner8394d792007-06-05 20:53:16 +00001220/// EmitLValue - Emit code to compute a designator that specifies the location
1221/// of the expression.
1222///
Mike Stump4a3999f2009-09-09 13:00:44 +00001223/// This can return one of two things: a simple address or a bitfield reference.
1224/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1225/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +00001226///
Mike Stump4a3999f2009-09-09 13:00:44 +00001227/// If this returns a bitfield reference, nothing about the pointee type of the
1228/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +00001229///
Mike Stump4a3999f2009-09-09 13:00:44 +00001230/// If this returns a normal address, and if the lvalue's C type is fixed size,
1231/// this method guarantees that the returned pointer type will point to an LLVM
1232/// type of the same size of the lvalue's type. If the lvalue has a variable
1233/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +00001234///
Chris Lattnerd7f58862007-06-02 05:24:33 +00001235LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +00001236 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +00001237 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001238 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +00001239
John McCallc109a252011-11-07 03:59:57 +00001240 case Expr::ObjCPropertyRefExprClass:
1241 llvm_unreachable("cannot emit a property reference directly");
1242
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00001243 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +00001244 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00001245 case Expr::ObjCIsaExprClass:
1246 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001247 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00001248 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001249 case Expr::CompoundAssignOperatorClass: {
1250 QualType Ty = E->getType();
1251 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1252 Ty = AT->getValueType();
1253 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +00001254 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1255 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001256 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001257 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +00001258 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001259 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001260 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001261 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00001262 case Expr::VAArgExprClass:
1263 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001264 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001265 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Bill Wendling8003edc2018-11-09 00:41:36 +00001266 case Expr::ConstantExprClass:
1267 return EmitLValue(cast<ConstantExpr>(E)->getSubExpr());
Eric Christopherd98e4242011-09-08 17:15:04 +00001268 case Expr::ParenExprClass:
1269 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +00001270 case Expr::GenericSelectionExprClass:
1271 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +00001272 case Expr::PredefinedExprClass:
1273 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +00001274 case Expr::StringLiteralClass:
1275 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001276 case Expr::ObjCEncodeExprClass:
1277 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +00001278 case Expr::PseudoObjectExprClass:
1279 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001280 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +00001281 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +00001282 case Expr::CXXTemporaryObjectExprClass:
1283 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001284 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1285 case Expr::CXXBindTemporaryExprClass:
1286 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +00001287 case Expr::CXXUuidofExprClass:
1288 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +00001289
1290 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001291 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +00001292 enterFullExpression(cleanups);
1293 RunCleanupsScope Scope(*this);
Reid Kleckner092d0652017-03-06 22:18:34 +00001294 LValue LV = EmitLValue(cleanups->getSubExpr());
1295 if (LV.isSimple()) {
1296 // Defend against branches out of gnu statement expressions surrounded by
1297 // cleanups.
1298 llvm::Value *V = LV.getPointer();
1299 Scope.ForceCleanup({&V});
1300 return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001301 getContext(), LV.getBaseInfo(), LV.getTBAAInfo());
Reid Kleckner092d0652017-03-06 22:18:34 +00001302 }
1303 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1304 // bitfield lvalue or some other non-simple lvalue?
1305 return LV;
John McCall08ef4662011-11-10 08:15:53 +00001306 }
1307
Anders Carlsson52ce3bb2009-11-14 01:51:50 +00001308 case Expr::CXXDefaultArgExprClass:
1309 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001310 case Expr::CXXDefaultInitExprClass: {
1311 CXXDefaultInitExprScope Scope(*this);
1312 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1313 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001314 case Expr::CXXTypeidExprClass:
1315 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001316
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001317 case Expr::ObjCMessageExprClass:
1318 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001319 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001320 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001321 case Expr::StmtExprClass:
1322 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001323 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001324 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001325 case Expr::ArraySubscriptExprClass:
1326 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001327 case Expr::OMPArraySectionExprClass:
1328 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001329 case Expr::ExtVectorElementExprClass:
1330 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001331 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001332 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001333 case Expr::CompoundLiteralExprClass:
1334 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001335 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001336 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001337 case Expr::BinaryConditionalOperatorClass:
1338 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001339 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001340 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001341 case Expr::OpaqueValueExprClass:
1342 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001343 case Expr::SubstNonTypeTemplateParmExprClass:
1344 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001345 case Expr::ImplicitCastExprClass:
1346 case Expr::CStyleCastExprClass:
1347 case Expr::CXXFunctionalCastExprClass:
1348 case Expr::CXXStaticCastExprClass:
1349 case Expr::CXXDynamicCastExprClass:
1350 case Expr::CXXReinterpretCastExprClass:
1351 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001352 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001353 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001354
Douglas Gregorfe314812011-06-21 17:03:29 +00001355 case Expr::MaterializeTemporaryExprClass:
1356 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Eric Fiseliercddaf872017-06-15 19:43:36 +00001357
1358 case Expr::CoawaitExprClass:
1359 return EmitCoawaitLValue(cast<CoawaitExpr>(E));
1360 case Expr::CoyieldExprClass:
1361 return EmitCoyieldLValue(cast<CoyieldExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001362 }
1363}
1364
John McCall71335052012-03-10 03:05:10 +00001365/// Given an object of the given canonical type, can we safely copy a
1366/// value out of it based on its initializer?
1367static bool isConstantEmittableObjectType(QualType type) {
1368 assert(type.isCanonical());
1369 assert(!type->isReferenceType());
1370
1371 // Must be const-qualified but non-volatile.
1372 Qualifiers qs = type.getLocalQualifiers();
1373 if (!qs.hasConst() || qs.hasVolatile()) return false;
1374
1375 // Otherwise, all object types satisfy this except C++ classes with
1376 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001377 if (const auto *RT = dyn_cast<RecordType>(type))
1378 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001379 if (RD->hasMutableFields() || !RD->isTrivial())
1380 return false;
1381
1382 return true;
1383}
1384
1385/// Can we constant-emit a load of a reference to a variable of the
1386/// given type? This is different from predicates like
1387/// Decl::isUsableInConstantExpressions because we do want it to apply
1388/// in situations that don't necessarily satisfy the language's rules
1389/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1390/// to do this with const float variables even if those variables
1391/// aren't marked 'constexpr'.
1392enum ConstantEmissionKind {
1393 CEK_None,
1394 CEK_AsReferenceOnly,
1395 CEK_AsValueOrReference,
1396 CEK_AsValueOnly
1397};
1398static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1399 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001400 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001401 if (isConstantEmittableObjectType(ref->getPointeeType()))
1402 return CEK_AsValueOrReference;
1403 return CEK_AsReferenceOnly;
1404 }
1405 if (isConstantEmittableObjectType(type))
1406 return CEK_AsValueOnly;
1407 return CEK_None;
1408}
1409
1410/// Try to emit a reference to the given value without producing it as
1411/// an l-value. This is actually more than an optimization: we can't
1412/// produce an l-value for variables that we never actually captured
1413/// in a block or lambda, which means const int variables or constexpr
1414/// literals or similar.
1415CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001416CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1417 ValueDecl *value = refExpr->getDecl();
1418
John McCall71335052012-03-10 03:05:10 +00001419 // The value needs to be an enum constant or a constant variable.
1420 ConstantEmissionKind CEK;
1421 if (isa<ParmVarDecl>(value)) {
1422 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001423 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001424 CEK = checkVarTypeForConstantEmission(var->getType());
1425 } else if (isa<EnumConstantDecl>(value)) {
1426 CEK = CEK_AsValueOnly;
1427 } else {
1428 CEK = CEK_None;
1429 }
1430 if (CEK == CEK_None) return ConstantEmission();
1431
John McCall71335052012-03-10 03:05:10 +00001432 Expr::EvalResult result;
1433 bool resultIsReference;
1434 QualType resultType;
1435
1436 // It's best to evaluate all the way as an r-value if that's permitted.
1437 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001438 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001439 resultIsReference = false;
1440 resultType = refExpr->getType();
1441
1442 // Otherwise, try to evaluate as an l-value.
1443 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001444 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001445 resultIsReference = true;
1446 resultType = value->getType();
1447
1448 // Failure.
1449 } else {
1450 return ConstantEmission();
1451 }
1452
1453 // In any case, if the initializer has side-effects, abandon ship.
1454 if (result.HasSideEffects)
1455 return ConstantEmission();
1456
1457 // Emit as a constant.
John McCallde0fe072017-08-15 21:42:52 +00001458 auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
1459 result.Val, resultType);
John McCall71335052012-03-10 03:05:10 +00001460
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001461 // Make sure we emit a debug reference to the global variable.
1462 // This should probably fire even for
1463 if (isa<VarDecl>(value)) {
1464 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001465 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001466 } else {
1467 assert(isa<EnumConstantDecl>(value));
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001468 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001469 }
John McCall71335052012-03-10 03:05:10 +00001470
1471 // If we emitted a reference constant, we need to dereference that.
1472 if (resultIsReference)
1473 return ConstantEmission::forReference(C);
1474
1475 return ConstantEmission::forValue(C);
1476}
1477
Alex Lorenz6cc83172017-08-25 10:07:00 +00001478static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
1479 const MemberExpr *ME) {
1480 if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
1481 // Try to emit static variable member expressions as DREs.
1482 return DeclRefExpr::Create(
1483 CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD,
1484 /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
1485 ME->getType(), ME->getValueKind());
1486 }
1487 return nullptr;
1488}
1489
1490CodeGenFunction::ConstantEmission
1491CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
1492 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
1493 return tryEmitAsConstant(DRE);
1494 return ConstantEmission();
1495}
1496
Volodymyr Sapsaief1899b2018-11-01 21:57:05 +00001497llvm::Value *CodeGenFunction::emitScalarConstant(
1498 const CodeGenFunction::ConstantEmission &Constant, Expr *E) {
1499 assert(Constant && "not a constant");
1500 if (Constant.isReference())
1501 return EmitLoadOfLValue(Constant.getReferenceLValue(*this, E),
1502 E->getExprLoc())
1503 .getScalarVal();
1504 return Constant.getValue();
1505}
1506
Nick Lewycky2d84e842013-10-02 02:29:49 +00001507llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1508 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +00001509 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001510 lvalue.getType(), Loc, lvalue.getBaseInfo(),
Ivan A. Kosareva511ed72017-10-03 10:52:39 +00001511 lvalue.getTBAAInfo(), lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001512}
1513
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001514static bool hasBooleanRepresentation(QualType Ty) {
1515 if (Ty->isBooleanType())
1516 return true;
1517
1518 if (const EnumType *ET = Ty->getAs<EnumType>())
1519 return ET->getDecl()->getIntegerType()->isBooleanType();
1520
Douglas Gregor298f43d2012-04-12 20:42:30 +00001521 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1522 return hasBooleanRepresentation(AT->getValueType());
1523
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001524 return false;
1525}
1526
Richard Smith1629da92012-12-13 07:11:50 +00001527static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1528 llvm::APInt &Min, llvm::APInt &End,
Vedant Kumar4593a462016-12-09 23:48:18 +00001529 bool StrictEnums, bool IsBool) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001530 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001531 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1532 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001533 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001534 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001535
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001536 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001537 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1538 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001539 } else {
1540 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001541 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001542 unsigned Bitwidth = LTy->getScalarSizeInBits();
1543 unsigned NumNegativeBits = ED->getNumNegativeBits();
1544 unsigned NumPositiveBits = ED->getNumPositiveBits();
1545
1546 if (NumNegativeBits) {
1547 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1548 assert(NumBits <= Bitwidth);
1549 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1550 Min = -End;
1551 } else {
1552 assert(NumPositiveBits <= Bitwidth);
1553 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1554 Min = llvm::APInt(Bitwidth, 0);
1555 }
1556 }
Richard Smith1629da92012-12-13 07:11:50 +00001557 return true;
1558}
1559
1560llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1561 llvm::APInt Min, End;
Vedant Kumar4593a462016-12-09 23:48:18 +00001562 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1563 hasBooleanRepresentation(Ty)))
Craig Topper8a13c412014-05-21 05:09:00 +00001564 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001565
Duncan Sandsc720e782012-04-15 18:04:54 +00001566 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001567 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001568}
1569
Vedant Kumar5a972652017-02-27 19:46:19 +00001570bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1571 SourceLocation Loc) {
1572 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1573 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1574 if (!HasBoolCheck && !HasEnumCheck)
1575 return false;
1576
1577 bool IsBool = hasBooleanRepresentation(Ty) ||
1578 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1579 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1580 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1581 if (!NeedsBoolCheck && !NeedsEnumCheck)
1582 return false;
1583
Vedant Kumar129edab2017-03-09 16:06:27 +00001584 // Single-bit booleans don't need to be checked. Special-case this to avoid
1585 // a bit width mismatch when handling bitfield values. This is handled by
1586 // EmitFromMemory for the non-bitfield case.
1587 if (IsBool &&
1588 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1589 return false;
1590
Vedant Kumar5a972652017-02-27 19:46:19 +00001591 llvm::APInt Min, End;
1592 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1593 return true;
1594
Vedant Kumar791f7012017-10-03 01:27:26 +00001595 auto &Ctx = getLLVMContext();
Vedant Kumar5a972652017-02-27 19:46:19 +00001596 SanitizerScope SanScope(this);
1597 llvm::Value *Check;
1598 --End;
1599 if (!Min) {
Vedant Kumar791f7012017-10-03 01:27:26 +00001600 Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
Vedant Kumar5a972652017-02-27 19:46:19 +00001601 } else {
Vedant Kumar791f7012017-10-03 01:27:26 +00001602 llvm::Value *Upper =
1603 Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
1604 llvm::Value *Lower =
1605 Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
Vedant Kumar5a972652017-02-27 19:46:19 +00001606 Check = Builder.CreateAnd(Upper, Lower);
1607 }
1608 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1609 EmitCheckTypeDescriptor(Ty)};
1610 SanitizerMask Kind =
1611 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1612 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1613 StaticArgs, EmitCheckValue(Value));
1614 return true;
1615}
1616
John McCall7f416cc2015-09-08 08:05:57 +00001617llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1618 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001619 SourceLocation Loc,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001620 LValueBaseInfo BaseInfo,
Ivan A. Kosareva511ed72017-10-03 10:52:39 +00001621 TBAAAccessInfo TBAAInfo,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001622 bool isNontemporal) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001623 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1624 // For better performance, handle vector loads differently.
1625 if (Ty->isVectorType()) {
1626 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001627
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001628 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001629
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001630 // Handle vectors of size 3 like size 4 for better performance.
1631 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001632
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001633 // Bitcast to vec4 type.
1634 llvm::VectorType *vec4Ty =
1635 llvm::VectorType::get(VTy->getElementType(), 4);
1636 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1637 // Now load value.
1638 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001639
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001640 // Shuffle vector to get vec3.
1641 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1642 {0, 1, 2}, "extractVec");
1643 return EmitFromMemory(V, Ty);
1644 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001645 }
1646 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001647
1648 // Atomic operations have to be done on integral types.
David Majnemera38c9f12016-05-24 16:09:25 +00001649 LValue AtomicLValue =
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001650 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
David Majnemera38c9f12016-05-24 16:09:25 +00001651 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1652 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001653 }
Craig Topper99e79272013-07-26 05:59:26 +00001654
John McCall7f416cc2015-09-08 08:05:57 +00001655 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001656 if (isNontemporal) {
1657 llvm::MDNode *Node = llvm::MDNode::get(
1658 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1659 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1660 }
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001661
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001662 CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
Daniel Dunbar1d425462009-02-10 00:57:50 +00001663
Vedant Kumar5a972652017-02-27 19:46:19 +00001664 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1665 // In order to prevent the optimizer from throwing away the check, don't
1666 // attach range metadata to the load.
Richard Smith1629da92012-12-13 07:11:50 +00001667 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001668 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1669 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001670
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001671 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001672}
1673
John McCall3a7f6922010-10-27 20:58:56 +00001674llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1675 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001676 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001677 // This should really always be an i1, but sometimes it's already
1678 // an i8, and it's awkward to track those cases down.
1679 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001680 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1681 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1682 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001683 }
1684
1685 return Value;
1686}
1687
1688llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1689 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001690 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001691 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1692 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001693 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1694 }
1695
1696 return Value;
1697}
1698
John McCall7f416cc2015-09-08 08:05:57 +00001699void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1700 bool Volatile, QualType Ty,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001701 LValueBaseInfo BaseInfo,
Ivan A. Kosareva511ed72017-10-03 10:52:39 +00001702 TBAAAccessInfo TBAAInfo,
1703 bool isInit, bool isNontemporal) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001704 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1705 // Handle vectors differently to get better performance.
1706 if (Ty->isVectorType()) {
1707 llvm::Type *SrcTy = Value->getType();
Simon Pilgrima5dbbc62017-06-01 20:13:34 +00001708 auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001709 // Handle vec3 special.
Simon Pilgrima5dbbc62017-06-01 20:13:34 +00001710 if (VecTy && VecTy->getNumElements() == 3) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001711 // Our source is a vec3, do a shuffle vector to make it a vec4.
1712 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1713 Builder.getInt32(2),
1714 llvm::UndefValue::get(Builder.getInt32Ty())};
1715 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1716 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
1717 MaskV, "extractVec");
1718 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1719 }
1720 if (Addr.getElementType() != SrcTy) {
1721 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1722 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001723 }
1724 }
Craig Topper99e79272013-07-26 05:59:26 +00001725
John McCall3a7f6922010-10-27 20:58:56 +00001726 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001727
David Majnemera38c9f12016-05-24 16:09:25 +00001728 LValue AtomicLValue =
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001729 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
David Majnemera5b195a2015-02-14 01:35:12 +00001730 if (Ty->isAtomicType() ||
David Majnemera38c9f12016-05-24 16:09:25 +00001731 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1732 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
John McCalla8ec7eb2013-03-07 21:37:17 +00001733 return;
1734 }
1735
Daniel Dunbar03816342010-08-21 02:24:36 +00001736 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001737 if (isNontemporal) {
1738 llvm::MDNode *Node =
1739 llvm::MDNode::get(Store->getContext(),
1740 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1741 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1742 }
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001743
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001744 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
Daniel Dunbar1d425462009-02-10 00:57:50 +00001745}
1746
David Chisnallfa35df62012-01-16 17:27:18 +00001747void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001748 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001749 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001750 lvalue.getType(), lvalue.getBaseInfo(),
Ivan A. Kosareva511ed72017-10-03 10:52:39 +00001751 lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001752}
1753
Mike Stump4a3999f2009-09-09 13:00:44 +00001754/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1755/// method emits the address of the lvalue, then loads the result as an rvalue,
1756/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001757RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001758 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001759 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001760 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001761 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1762 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001763 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001764 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001765 // In MRC mode, we do a load+autorelease.
1766 if (!getLangOpts().ObjCAutoRefCount) {
1767 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1768 }
1769
1770 // In ARC mode, we load retained and then consume the value.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001771 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1772 Object = EmitObjCConsumeObject(LV.getType(), Object);
1773 return RValue::get(Object);
1774 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001775
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001776 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001777 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001778
John McCalla1dee5302010-08-22 10:59:02 +00001779 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001780 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001781 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001782
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001783 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001784 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001785 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001786 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001787 "vecext"));
1788 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001789
1790 // If this is a reference to a subset of the elements of a vector, either
1791 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001792 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001793 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001794
Renato Golin230c5eb2014-05-19 18:15:42 +00001795 // Global Register variables always invoke intrinsics
1796 if (LV.isGlobalReg())
1797 return EmitLoadOfGlobalRegLValue(LV);
1798
John McCallc109a252011-11-07 03:59:57 +00001799 assert(LV.isBitField() && "Unknown LValue type!");
Vedant Kumar129edab2017-03-09 16:06:27 +00001800 return EmitLoadOfBitfieldLValue(LV, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +00001801}
1802
Vedant Kumar129edab2017-03-09 16:06:27 +00001803RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1804 SourceLocation Loc) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001805 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001806
Daniel Dunbar3447a022010-04-13 23:34:15 +00001807 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001808 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001809
John McCall7f416cc2015-09-08 08:05:57 +00001810 Address Ptr = LV.getBitFieldAddress();
1811 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001812
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001813 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001814 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001815 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1816 if (HighBits)
1817 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1818 if (Info.Offset + HighBits)
1819 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1820 } else {
1821 if (Info.Offset)
1822 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001823 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001824 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1825 Info.Size),
1826 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001827 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001828 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Vedant Kumar129edab2017-03-09 16:06:27 +00001829 EmitScalarRangeCheck(Val, LV.getType(), Loc);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001830 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001831}
1832
Nate Begemanb699c9b2009-01-18 06:42:49 +00001833// If this is a reference to a subset of the elements of a vector, create an
1834// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001835RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001836 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1837 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001838
Nate Begemanf322eab2008-05-09 06:41:27 +00001839 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001840
1841 // If the result of the expression is a non-vector type, we must be extracting
1842 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001843 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001844 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001845 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001846 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001847 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001848 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001849
1850 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001851 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001852
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001853 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001854 for (unsigned i = 0; i != NumResultElts; ++i)
1855 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001856
Chris Lattner91c08ad2011-02-15 00:14:06 +00001857 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1858 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001859 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001860 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001861}
1862
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001863/// Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001864Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1865 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001866 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1867 QualType EQT = ExprVT->getElementType();
1868 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fangrui Song6907ce22018-07-30 19:24:48 +00001869
John McCall7f416cc2015-09-08 08:05:57 +00001870 Address CastToPointerElement =
1871 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1872 "conv.ptr.element");
Fangrui Song6907ce22018-07-30 19:24:48 +00001873
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001874 const llvm::Constant *Elts = LV.getExtVectorElts();
1875 unsigned ix = getAccessedFieldNo(0, Elts);
Fangrui Song6907ce22018-07-30 19:24:48 +00001876
John McCall7f416cc2015-09-08 08:05:57 +00001877 Address VectorBasePtrPlusIx =
1878 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1879 getContext().getTypeSizeInChars(EQT),
1880 "vector.elt");
1881
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001882 return VectorBasePtrPlusIx;
1883}
1884
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001885/// Load of global gamed gegisters are always calls to intrinsics.
Renato Golin230c5eb2014-05-19 18:15:42 +00001886RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001887 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1888 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001889 llvm::MDNode *RegName = cast<llvm::MDNode>(
1890 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001891
1892 // We accept integer and pointer types only
1893 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1894 llvm::Type *Ty = OrigTy;
1895 if (OrigTy->isPointerTy())
1896 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1897 llvm::Type *Types[] = { Ty };
1898
Renato Golin230c5eb2014-05-19 18:15:42 +00001899 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001900 llvm::Value *Call = Builder.CreateCall(
1901 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001902 if (OrigTy->isPointerTy())
1903 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001904 return RValue::get(Call);
1905}
Chris Lattner40ff7012007-08-03 16:18:34 +00001906
Chris Lattner9369a562007-06-29 16:31:29 +00001907
Chris Lattner8394d792007-06-05 20:53:16 +00001908/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1909/// lvalue, where both are guaranteed to the have the same type, and that type
1910/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001911void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001912 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001913 if (!Dst.isSimple()) {
1914 if (Dst.isVectorElt()) {
1915 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001916 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1917 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001918 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001919 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001920 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1921 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001922 return;
1923 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001924
Nate Begemance4d7fc2008-04-18 23:10:10 +00001925 // If this is an update of extended vector elements, insert them as
1926 // appropriate.
1927 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001928 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001929
Renato Golin230c5eb2014-05-19 18:15:42 +00001930 if (Dst.isGlobalReg())
1931 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1932
John McCallc109a252011-11-07 03:59:57 +00001933 assert(Dst.isBitField() && "Unknown LValue type");
1934 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001935 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001936
John McCall31168b02011-06-15 23:02:42 +00001937 // There's special magic for assigning into an ARC-qualified l-value.
1938 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1939 switch (Lifetime) {
1940 case Qualifiers::OCL_None:
1941 llvm_unreachable("present but none");
1942
1943 case Qualifiers::OCL_ExplicitNone:
1944 // nothing special
1945 break;
1946
1947 case Qualifiers::OCL_Strong:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001948 if (isInit) {
1949 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1950 break;
1951 }
John McCall55e1fbc2011-06-25 02:11:03 +00001952 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001953 return;
1954
1955 case Qualifiers::OCL_Weak:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001956 if (isInit)
1957 // Initialize and then skip the primitive store.
1958 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1959 else
1960 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001961 return;
1962
1963 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001964 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1965 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001966 // fall into the normal path
1967 break;
1968 }
1969 }
1970
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001971 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001972 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001973 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001974 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001975 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001976 return;
1977 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001978
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001979 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001980 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001981 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001982 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001983 if (Dst.isObjCIvar()) {
1984 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001985 llvm::Type *ResultType = IntPtrTy;
1986 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1987 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001988 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001989 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001990 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1991 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001992 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001993 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001994 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001995 } else if (Dst.isGlobalObjCRef()) {
1996 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1997 Dst.isThreadLocalRef());
1998 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001999 else
2000 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00002001 return;
2002 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002003
Chris Lattner6278e6a2007-08-11 00:04:45 +00002004 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00002005 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00002006}
2007
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00002008void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00002009 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00002010 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00002011 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00002012 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00002013
Daniel Dunbar67aba792010-04-15 03:47:33 +00002014 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00002015 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00002016
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002017 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00002018 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002019 /*IsSigned=*/false);
2020 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00002021
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002022 // See if there are other bits in the bitfield's storage we'll need to load
2023 // and mask together with source before storing.
2024 if (Info.StorageSize != Info.Size) {
2025 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00002026 llvm::Value *Val =
2027 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002028
2029 // Mask the source value as needed.
2030 if (!hasBooleanRepresentation(Dst.getType()))
2031 SrcVal = Builder.CreateAnd(SrcVal,
2032 llvm::APInt::getLowBitsSet(Info.StorageSize,
2033 Info.Size),
2034 "bf.value");
2035 MaskedVal = SrcVal;
2036 if (Info.Offset)
2037 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
2038
2039 // Mask out the original value.
2040 Val = Builder.CreateAnd(Val,
2041 ~llvm::APInt::getBitsSet(Info.StorageSize,
2042 Info.Offset,
2043 Info.Offset + Info.Size),
2044 "bf.clear");
2045
2046 // Or together the unchanged values and the source value.
2047 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
2048 } else {
2049 assert(Info.Offset == 0);
2050 }
2051
2052 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00002053 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00002054
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00002055 // Return the new value of the bit-field, if requested.
2056 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002057 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00002058
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002059 // Sign extend the value if needed.
2060 if (Info.IsSigned) {
2061 assert(Info.Size <= Info.StorageSize);
2062 unsigned HighBits = Info.StorageSize - Info.Size;
2063 if (HighBits) {
2064 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
2065 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
2066 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00002067 }
2068
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002069 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
2070 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00002071 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00002072 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00002073}
2074
Nate Begemance4d7fc2008-04-18 23:10:10 +00002075void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00002076 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00002077 // This access turns into a read/modify/write of the vector. Load the input
2078 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00002079 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
2080 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00002081 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00002082
Chris Lattner4647a212007-08-31 22:49:20 +00002083 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00002084
John McCall55e1fbc2011-06-25 02:11:03 +00002085 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00002086 unsigned NumSrcElts = VTy->getNumElements();
Craig Topperf2f1a092016-07-08 02:17:35 +00002087 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00002088 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00002089 // Use shuffle vector is the src and destination are the same number of
2090 // elements and restore the vector mask since it is on the side it will be
2091 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002092 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002093 for (unsigned i = 0; i != NumSrcElts; ++i)
2094 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00002095
Chris Lattner91c08ad2011-02-15 00:14:06 +00002096 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00002097 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00002098 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002099 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00002100 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00002101 // Extended the source vector to the same length and then shuffle it
2102 // into the destination.
2103 // FIXME: since we're shuffling with undef, can we just use the indices
2104 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002105 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00002106 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002107 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00002108 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00002109 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00002110 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00002111 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00002112 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002113 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00002114 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002115 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002116 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002117 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002118
Joey Goulycf4143b2013-11-21 17:09:05 +00002119 // When the vector size is odd and .odd or .hi is used, the last element
2120 // of the Elts constant array will be one past the size of the vector.
2121 // Ignore the last element here, if it is greater than the mask size.
2122 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
2123 NumSrcElts--;
2124
Nate Begemanb699c9b2009-01-18 06:42:49 +00002125 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002126 for (unsigned i = 0; i != NumSrcElts; ++i)
2127 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00002128 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002129 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00002130 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00002131 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00002132 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00002133 }
2134 } else {
2135 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00002136 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00002137 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002138 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00002139 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002140
John McCall7f416cc2015-09-08 08:05:57 +00002141 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
2142 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00002143}
2144
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002145/// Store of global named registers are always calls to intrinsics.
Renato Golin230c5eb2014-05-19 18:15:42 +00002146void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00002147 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
2148 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002149 llvm::MDNode *RegName = cast<llvm::MDNode>(
2150 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00002151 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00002152
2153 // We accept integer and pointer types only
2154 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
2155 llvm::Type *Ty = OrigTy;
2156 if (OrigTy->isPointerTy())
2157 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2158 llvm::Type *Types[] = { Ty };
2159
Renato Golin230c5eb2014-05-19 18:15:42 +00002160 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
2161 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00002162 if (OrigTy->isPointerTy())
2163 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00002164 Builder.CreateCall(
2165 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00002166}
2167
Eric Christopherc9e2a682014-05-20 17:10:39 +00002168// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002169// generating write-barries API. It is currently a global, ivar,
2170// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002171static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002172 LValue &LV,
2173 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002174 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002175 return;
Craig Topper99e79272013-07-26 05:59:26 +00002176
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002177 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002178 QualType ExpTy = E->getType();
2179 if (IsMemberAccess && ExpTy->isPointerType()) {
2180 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00002181 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002182 // writer-barrier conservatively.
2183 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2184 if (ExpTy->isRecordType()) {
2185 LV.setObjCIvar(false);
2186 return;
2187 }
2188 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002189 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002190 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002191 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002192 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002193 return;
2194 }
Craig Topper99e79272013-07-26 05:59:26 +00002195
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002196 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
2197 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00002198 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002199 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00002200 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002201 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002202 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002203 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002204 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002205 }
Craig Topper99e79272013-07-26 05:59:26 +00002206
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002207 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002208 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002209 return;
2210 }
Craig Topper99e79272013-07-26 05:59:26 +00002211
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002212 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002213 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002214 if (LV.isObjCIvar()) {
2215 // If cast is to a structure pointer, follow gcc's behavior and make it
2216 // a non-ivar write-barrier.
2217 QualType ExpTy = E->getType();
2218 if (ExpTy->isPointerType())
2219 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2220 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00002221 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002222 }
2223 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002224 }
Peter Collingbourne91147592011-04-15 00:35:48 +00002225
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002226 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00002227 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2228 return;
2229 }
2230
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002231 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002232 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002233 return;
2234 }
Craig Topper99e79272013-07-26 05:59:26 +00002235
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002236 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002237 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002238 return;
2239 }
John McCall31168b02011-06-15 23:02:42 +00002240
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002241 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002242 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00002243 return;
2244 }
2245
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002246 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002247 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00002248 if (LV.isObjCIvar() && !LV.isObjCArray())
2249 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002250 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00002251 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002252 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00002253 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002254 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002255 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002256 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002257 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002258
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002259 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002260 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002261 // We don't know if member is an 'ivar', but this flag is looked at
2262 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002263 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002264 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002265 }
2266}
2267
Chris Lattner3f32d692011-07-12 06:52:18 +00002268static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00002269EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00002270 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002271 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00002272 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00002273 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00002274}
2275
Alexey Bataev97720002014-11-11 04:05:39 +00002276static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00002277 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2278 llvm::Type *RealVarTy, SourceLocation Loc) {
2279 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2280 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002281 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
John McCall7f416cc2015-09-08 08:05:57 +00002282}
2283
Alexey Bataev92327c52018-03-26 16:40:55 +00002284static Address emitDeclTargetLinkVarDeclLValue(CodeGenFunction &CGF,
2285 const VarDecl *VD, QualType T) {
Alexey Bataevd01b7492018-08-15 19:45:12 +00002286 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2287 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2288 if (!Res || *Res == OMPDeclareTargetDeclAttr::MT_To)
2289 return Address::invalid();
2290 assert(*Res == OMPDeclareTargetDeclAttr::MT_Link && "Expected link clause");
2291 QualType PtrTy = CGF.getContext().getPointerType(VD->getType());
2292 Address Addr = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetLink(VD);
2293 return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>());
Alexey Bataev92327c52018-03-26 16:40:55 +00002294}
2295
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002296Address
2297CodeGenFunction::EmitLoadOfReference(LValue RefLVal,
2298 LValueBaseInfo *PointeeBaseInfo,
2299 TBAAAccessInfo *PointeeTBAAInfo) {
2300 llvm::LoadInst *Load = Builder.CreateLoad(RefLVal.getAddress(),
2301 RefLVal.isVolatile());
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00002302 CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002303
2304 CharUnits Align = getNaturalTypeAlignment(RefLVal.getType()->getPointeeType(),
2305 PointeeBaseInfo, PointeeTBAAInfo,
2306 /* forPointeeType= */ true);
2307 return Address(Load, Align);
John McCall7f416cc2015-09-08 08:05:57 +00002308}
2309
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002310LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) {
2311 LValueBaseInfo PointeeBaseInfo;
2312 TBAAAccessInfo PointeeTBAAInfo;
2313 Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
2314 &PointeeTBAAInfo);
2315 return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
2316 PointeeBaseInfo, PointeeTBAAInfo);
Alexey Bataev97720002014-11-11 04:05:39 +00002317}
2318
Alexey Bataev31300ed2016-02-04 11:27:03 +00002319Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2320 const PointerType *PtrTy,
Ivan A. Kosarev90295642017-10-13 16:47:22 +00002321 LValueBaseInfo *BaseInfo,
2322 TBAAAccessInfo *TBAAInfo) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00002323 llvm::Value *Addr = Builder.CreateLoad(Ptr);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002324 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(),
Ivan A. Kosarev78f486d2017-10-13 16:58:30 +00002325 BaseInfo, TBAAInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00002326 /*forPointeeType=*/true));
2327}
2328
2329LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2330 const PointerType *PtrTy) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002331 LValueBaseInfo BaseInfo;
Ivan A. Kosarev90295642017-10-13 16:47:22 +00002332 TBAAAccessInfo TBAAInfo;
2333 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
2334 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00002335}
2336
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002337static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2338 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00002339 QualType T = E->getType();
2340
2341 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00002342 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2343 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00002344 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
Alexey Bataev92327c52018-03-26 16:40:55 +00002345 // Check if the variable is marked as declare target with link clause in
2346 // device codegen.
2347 if (CGF.getLangOpts().OpenMPIsDevice) {
2348 Address Addr = emitDeclTargetLinkVarDeclLValue(CGF, VD, T);
2349 if (Addr.isValid())
2350 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2351 }
Richard Smith0f383742014-03-26 22:48:22 +00002352
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002353 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002354 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2355 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00002356 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00002357 Address Addr(V, Alignment);
Alexey Bataev97720002014-11-11 04:05:39 +00002358 // Emit reference to the private copy of the variable if it is an OpenMP
2359 // threadprivate variable.
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00002360 if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
2361 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
John McCall7f416cc2015-09-08 08:05:57 +00002362 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002363 E->getExprLoc());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00002364 }
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002365 LValue LV = VD->getType()->isReferenceType() ?
2366 CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
2367 AlignmentSource::Decl) :
2368 CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002369 setObjCGCLValueClass(CGF.getContext(), E, LV);
2370 return LV;
2371}
2372
John McCallb92ab1a2016-10-26 23:46:34 +00002373static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2374 const FunctionDecl *FD) {
2375 if (FD->hasAttr<WeakRefAttr>()) {
2376 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2377 return aliasee.getPointer();
2378 }
2379
2380 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002381 if (!FD->hasPrototype()) {
2382 if (const FunctionProtoType *Proto =
2383 FD->getType()->getAs<FunctionProtoType>()) {
2384 // Ugly case: for a K&R-style definition, the type of the definition
2385 // isn't the same as the type of a use. Correct for this with a
2386 // bitcast.
2387 QualType NoProtoType =
John McCallb92ab1a2016-10-26 23:46:34 +00002388 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2389 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2390 V = llvm::ConstantExpr::getBitCast(V,
2391 CGM.getTypes().ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002392 }
2393 }
John McCallb92ab1a2016-10-26 23:46:34 +00002394 return V;
2395}
2396
2397static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2398 const Expr *E, const FunctionDecl *FD) {
2399 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
Eli Friedmana0544d62011-12-03 04:14:32 +00002400 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002401 return CGF.MakeAddrLValue(V, E->getType(), Alignment,
2402 AlignmentSource::Decl);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002403}
2404
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00002405static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2406 llvm::Value *ThisValue) {
2407 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2408 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2409 return CGF.EmitLValueForField(LV, FD);
2410}
2411
Renato Golin230c5eb2014-05-19 18:15:42 +00002412/// Named Registers are named metadata pointing to the register name
2413/// which will be read from/written to as an argument to the intrinsic
2414/// @llvm.read/write_register.
2415/// So far, only the name is being passed down, but other options such as
2416/// register type, allocation type or even optimization options could be
2417/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002418static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002419 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002420 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002421 assert(Asm->getLabel().size() < 64-Name.size() &&
2422 "Register name too big");
2423 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002424 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002425 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002426 if (M->getNumOperands() == 0) {
2427 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2428 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002429 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002430 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2431 }
John McCall7f416cc2015-09-08 08:05:57 +00002432
2433 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2434
2435 llvm::Value *Ptr =
2436 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2437 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002438}
2439
Chris Lattnerd7f58862007-06-02 05:24:33 +00002440LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002441 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002442 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002443
Renato Goline7b3d5d2014-05-27 16:46:27 +00002444 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2445 // Global Named registers access via intrinsics only
2446 if (VD->getStorageClass() == SC_Register &&
2447 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002448 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002449
Renato Goline7b3d5d2014-05-27 16:46:27 +00002450 // A DeclRefExpr for a reference initialized by a constant expression can
2451 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002452 const Expr *Init = VD->getAnyInitializer(VD);
Alexey Bataev7b1a7bd2018-08-20 16:00:22 +00002453 const auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl);
Richard Smith5a1104b2012-10-20 01:38:33 +00002454 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2455 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002456 VD->checkInitIsICE() &&
2457 // Do not emit if it is private OpenMP variable.
Alexey Bataevcab496d2017-10-06 16:17:25 +00002458 !(E->refersToEnclosingVariableOrCapture() &&
2459 ((CapturedStmtInfo &&
2460 (LocalDeclMap.count(VD->getCanonicalDecl()) ||
2461 CapturedStmtInfo->lookup(VD->getCanonicalDecl()))) ||
2462 LambdaCaptureFields.lookup(VD->getCanonicalDecl()) ||
Alexey Bataev7b1a7bd2018-08-20 16:00:22 +00002463 (BD && BD->capturesVariable(VD))))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002464 llvm::Constant *Val =
John McCallde0fe072017-08-15 21:42:52 +00002465 ConstantEmitter(*this).emitAbstract(E->getLocation(),
2466 *VD->evaluateValue(),
2467 VD->getType());
Richard Smith5a1104b2012-10-20 01:38:33 +00002468 assert(Val && "failed to emit reference constant expression");
2469 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002470
2471 // Should we be using the alignment of the constant pointer we emitted?
Ivan A. Kosarev78f486d2017-10-13 16:58:30 +00002472 CharUnits Alignment = getNaturalTypeAlignment(E->getType(),
2473 /* BaseInfo= */ nullptr,
2474 /* TBAAInfo= */ nullptr,
2475 /* forPointeeType= */ true);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002476 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
Richard Smith5a1104b2012-10-20 01:38:33 +00002477 }
David Majnemer602cfe72015-01-01 09:49:44 +00002478
2479 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002480 if (E->refersToEnclosingVariableOrCapture()) {
Alexey Bataev6a71f362017-08-22 17:54:52 +00002481 VD = VD->getCanonicalDecl();
David Majnemer602cfe72015-01-01 09:49:44 +00002482 if (auto *FD = LambdaCaptureFields.lookup(VD))
2483 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2484 else if (CapturedStmtInfo) {
Alexey Bataevac5eabb2016-11-07 11:16:04 +00002485 auto I = LocalDeclMap.find(VD);
2486 if (I != LocalDeclMap.end()) {
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002487 if (VD->getType()->isReferenceType())
2488 return EmitLoadOfReferenceLValue(I->second, VD->getType(),
2489 AlignmentSource::Decl);
Alexey Bataevac5eabb2016-11-07 11:16:04 +00002490 return MakeAddrLValue(I->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002491 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002492 LValue CapLVal =
2493 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2494 CapturedStmtInfo->getContextValue());
2495 return MakeAddrLValue(
2496 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00002497 CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl),
2498 CapLVal.getTBAAInfo());
David Majnemer602cfe72015-01-01 09:49:44 +00002499 }
John McCall7f416cc2015-09-08 08:05:57 +00002500
David Majnemer602cfe72015-01-01 09:49:44 +00002501 assert(isa<BlockDecl>(CurCodeDecl));
Akira Hatanaka8e57b072018-10-01 21:51:28 +00002502 Address addr = GetAddrOfBlockDecl(VD);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002503 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002504 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002505 }
2506
Eli Friedman5720e342012-01-21 04:52:58 +00002507 // FIXME: We should be able to assert this for FunctionDecls as well!
2508 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2509 // those with a valid source location.
2510 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2511 !E->getLocation().isValid()) &&
2512 "Should not use decl without marking it used!");
2513
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002514 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002515 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002516 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002517 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002518 }
2519
Renato Goline7b3d5d2014-05-27 16:46:27 +00002520 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002521 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002522 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002523 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002524
John McCall7f416cc2015-09-08 08:05:57 +00002525 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002526
John McCall7f416cc2015-09-08 08:05:57 +00002527 // The variable should generally be present in the local decl map.
2528 auto iter = LocalDeclMap.find(VD);
2529 if (iter != LocalDeclMap.end()) {
2530 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002531
John McCall7f416cc2015-09-08 08:05:57 +00002532 // Otherwise, it might be static local we haven't emitted yet for
2533 // some reason; most likely, because it's in an outer function.
2534 } else if (VD->isStaticLocal()) {
2535 addr = Address(CGM.getOrCreateStaticVarDecl(
2536 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2537 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002538
John McCall7f416cc2015-09-08 08:05:57 +00002539 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002540 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002541 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2542 }
2543
2544
2545 // Check for OpenMP threadprivate variables.
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00002546 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
2547 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
John McCall7f416cc2015-09-08 08:05:57 +00002548 return EmitThreadPrivateVarDeclLValue(
2549 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2550 E->getExprLoc());
2551 }
2552
2553 // Drill into block byref variables.
Akira Hatanaka8e57b072018-10-01 21:51:28 +00002554 bool isBlockByref = VD->isEscapingByref();
John McCall7f416cc2015-09-08 08:05:57 +00002555 if (isBlockByref) {
2556 addr = emitBlockByrefAddress(addr, VD);
2557 }
2558
2559 // Drill into reference types.
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002560 LValue LV = VD->getType()->isReferenceType() ?
2561 EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) :
2562 MakeAddrLValue(addr, T, AlignmentSource::Decl);
Chris Lattner3f32d692011-07-12 06:52:18 +00002563
John McCallcdda29c2013-03-13 03:10:54 +00002564 bool isLocalStorage = VD->hasLocalStorage();
2565
2566 bool NonGCable = isLocalStorage &&
2567 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002568 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002569 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002570 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002571 LV.setNonGC(true);
2572 }
John McCallcdda29c2013-03-13 03:10:54 +00002573
2574 bool isImpreciseLifetime =
2575 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2576 if (isImpreciseLifetime)
2577 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002578 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002579 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002580 }
John McCallf3a88602011-02-03 08:15:49 +00002581
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002582 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002583 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002584
Richard Smithda383632016-08-15 01:33:41 +00002585 // FIXME: While we're emitting a binding from an enclosing scope, all other
2586 // DeclRefExprs we see should be implicitly treated as if they also refer to
2587 // an enclosing scope.
2588 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2589 return EmitLValue(BD->getBinding());
2590
David Blaikie83d382b2011-09-23 05:06:16 +00002591 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002592}
Chris Lattnere47e4402007-06-01 18:02:12 +00002593
Chris Lattner8394d792007-06-05 20:53:16 +00002594LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2595 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002596 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002597 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002598
Chris Lattner0f398c42008-07-26 22:37:01 +00002599 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002600 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002601 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002602 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002603 QualType T = E->getSubExpr()->getType()->getPointeeType();
2604 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002605
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002606 LValueBaseInfo BaseInfo;
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00002607 TBAAAccessInfo TBAAInfo;
2608 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo,
2609 &TBAAInfo);
2610 LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002611 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002612
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002613 // We should not generate __weak write barrier on indirect reference
2614 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2615 // But, we continue to generate __strong write barrier on indirect write
2616 // into a pointer to object.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002617 if (getLangOpts().ObjC &&
Richard Smith9c6890a2012-11-01 22:30:59 +00002618 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002619 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002620 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002621 return LV;
2622 }
John McCalle3027922010-08-25 11:45:40 +00002623 case UO_Real:
2624 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002625 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002626 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002627
Richard Smith0b6b8e42012-02-18 20:53:32 +00002628 // __real is valid on scalars. This is a faster way of testing that.
2629 // __imag can only produce an rvalue on scalars.
2630 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002631 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002632 assert(E->getSubExpr()->getType()->isArithmeticType());
2633 return LV;
2634 }
2635
Alexey Bataev611b0a12016-11-07 18:15:02 +00002636 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
John McCalla2342eb2010-12-05 02:00:02 +00002637
John McCall7f416cc2015-09-08 08:05:57 +00002638 Address Component =
2639 (E->getOpcode() == UO_Real
2640 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2641 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00002642 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00002643 CGM.getTBAAInfoForSubobject(LV, T));
Alexey Bataev611b0a12016-11-07 18:15:02 +00002644 ElemLV.getQuals().addQualifiers(LV.getQuals());
2645 return ElemLV;
Chris Lattner595db862007-10-30 22:53:42 +00002646 }
John McCalle3027922010-08-25 11:45:40 +00002647 case UO_PreInc:
2648 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002649 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002650 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002651
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002652 if (E->getType()->isAnyComplexType())
2653 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2654 else
2655 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2656 return LV;
2657 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002658 }
Chris Lattner8394d792007-06-05 20:53:16 +00002659}
2660
Chris Lattner4347e3692007-06-06 04:54:52 +00002661LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002662 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002663 E->getType(), AlignmentSource::Decl);
Chris Lattner4347e3692007-06-06 04:54:52 +00002664}
2665
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002666LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002667 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002668 E->getType(), AlignmentSource::Decl);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002669}
2670
Mike Stump4a3999f2009-09-09 13:00:44 +00002671LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002672 auto SL = E->getFunctionName();
2673 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2674 StringRef FnName = CurFn->getName();
2675 if (FnName.startswith("\01"))
2676 FnName = FnName.substr(1);
2677 StringRef NameItems[] = {
Bruno Ricci17ff0262018-10-27 19:21:19 +00002678 PredefinedExpr::getIdentKindName(E->getIdentKind()), FnName};
Alexey Bataevec474782014-10-09 08:45:04 +00002679 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Shoaib Meenai34aa1312018-04-11 18:17:35 +00002680 if (auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl)) {
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002681 std::string Name = SL->getString();
2682 if (!Name.empty()) {
2683 unsigned Discriminator =
2684 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2685 if (Discriminator)
2686 Name += "_" + Twine(Discriminator + 1).str();
2687 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002688 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002689 } else {
2690 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002691 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002692 }
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002693 }
Alexey Bataevec474782014-10-09 08:45:04 +00002694 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002695 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002696}
2697
Richard Smithe30752c2012-10-09 19:52:38 +00002698/// Emit a type description suitable for use by a runtime sanitizer library. The
2699/// format of a type descriptor is
2700///
2701/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002702/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002703/// \endcode
2704///
Richard Smith683398a2012-10-09 23:55:19 +00002705/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2706/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002707llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002708 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002709 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002710 return C;
2711
Richard Smithe30752c2012-10-09 19:52:38 +00002712 uint16_t TypeKind = -1;
2713 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002714
Richard Smithe30752c2012-10-09 19:52:38 +00002715 if (T->isIntegerType()) {
2716 TypeKind = 0;
2717 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002718 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002719 } else if (T->isFloatingType()) {
2720 TypeKind = 1;
2721 TypeInfo = getContext().getTypeSize(T);
2722 }
2723
2724 // Format the type name as if for a diagnostic, including quotes and
2725 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002726 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002727 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2728 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002729 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002730 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002731
2732 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002733 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2734 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002735 };
2736 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2737
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002738 auto *GV = new llvm::GlobalVariable(
2739 CGM.getModule(), Descriptor->getType(),
2740 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002741 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002742 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002743
2744 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002745 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002746
Richard Smithe30752c2012-10-09 19:52:38 +00002747 return GV;
2748}
2749
2750llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2751 llvm::Type *TargetTy = IntPtrTy;
2752
Vedant Kumar8a715332017-10-03 01:27:24 +00002753 if (V->getType() == TargetTy)
2754 return V;
2755
Richard Smith48366f72013-03-22 00:47:07 +00002756 // Floating-point types which fit into intptr_t are bitcast to integers
2757 // and then passed directly (after zero-extension, if necessary).
2758 if (V->getType()->isFloatingPointTy()) {
2759 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2760 if (Bits <= TargetTy->getIntegerBitWidth())
2761 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2762 Bits));
2763 }
2764
Richard Smithe30752c2012-10-09 19:52:38 +00002765 // Integers which fit in intptr_t are zero-extended and passed directly.
2766 if (V->getType()->isIntegerTy() &&
2767 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2768 return Builder.CreateZExt(V, TargetTy);
2769
2770 // Pointers are passed directly, everything else is passed by address.
2771 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002772 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002773 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002774 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002775 }
2776 return Builder.CreatePtrToInt(V, TargetTy);
2777}
2778
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002779/// Emit a representation of a SourceLocation for passing to a handler
Richard Smithe30752c2012-10-09 19:52:38 +00002780/// in a sanitizer runtime library. The format for this data is:
2781/// \code
2782/// struct SourceLocation {
2783/// const char *Filename;
2784/// int32_t Line, Column;
2785/// };
2786/// \endcode
2787/// For an invalid SourceLocation, the Filename pointer is null.
2788llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002789 llvm::Constant *Filename;
2790 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002791
Alexey Samsonov6c124142014-07-18 17:50:06 +00002792 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2793 if (PLoc.isValid()) {
Filipe Cabecinhasab731f72016-05-12 16:51:36 +00002794 StringRef FilenameString = PLoc.getFilename();
2795
2796 int PathComponentsToStrip =
2797 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2798 if (PathComponentsToStrip < 0) {
2799 assert(PathComponentsToStrip != INT_MIN);
2800 int PathComponentsToKeep = -PathComponentsToStrip;
2801 auto I = llvm::sys::path::rbegin(FilenameString);
2802 auto E = llvm::sys::path::rend(FilenameString);
2803 while (I != E && --PathComponentsToKeep)
2804 ++I;
2805
2806 FilenameString = FilenameString.substr(I - E);
2807 } else if (PathComponentsToStrip > 0) {
2808 auto I = llvm::sys::path::begin(FilenameString);
2809 auto E = llvm::sys::path::end(FilenameString);
2810 while (I != E && PathComponentsToStrip--)
2811 ++I;
2812
2813 if (I != E)
2814 FilenameString =
2815 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2816 else
2817 FilenameString = llvm::sys::path::filename(FilenameString);
2818 }
2819
2820 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002821 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2822 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2823 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002824 Line = PLoc.getLine();
2825 Column = PLoc.getColumn();
2826 } else {
2827 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2828 Line = Column = 0;
2829 }
2830
2831 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2832 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002833
2834 return llvm::ConstantStruct::getAnon(Data);
2835}
2836
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002837namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002838/// Specify under what conditions this check can be recovered
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002839enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002840 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002841 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002842 /// Check supports recovering, runtime has both fatal (noreturn) and
2843 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002844 Recoverable,
2845 /// Runtime conditionally aborts, always need to support recovery.
2846 AlwaysRecoverable
2847};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002848}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002849
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002850static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2851 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002852 switch (Kind) {
2853 case SanitizerKind::Vptr:
2854 return CheckRecoverableKind::AlwaysRecoverable;
2855 case SanitizerKind::Return:
2856 case SanitizerKind::Unreachable:
2857 return CheckRecoverableKind::Unrecoverable;
2858 default:
2859 return CheckRecoverableKind::Recoverable;
2860 }
2861}
2862
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002863namespace {
2864struct SanitizerHandlerInfo {
2865 char const *const Name;
2866 unsigned Version;
2867};
Saleem Abdulrasoolca6e2b42016-12-13 03:27:35 +00002868}
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002869
2870const SanitizerHandlerInfo SanitizerHandlers[] = {
2871#define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2872 LIST_SANITIZER_CHECKS
2873#undef SANITIZER_CHECK
2874};
2875
Alexey Samsonov88459522015-01-12 22:39:12 +00002876static void emitCheckHandlerCall(CodeGenFunction &CGF,
2877 llvm::FunctionType *FnType,
2878 ArrayRef<llvm::Value *> FnArgs,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002879 SanitizerHandler CheckHandler,
Alexey Samsonov88459522015-01-12 22:39:12 +00002880 CheckRecoverableKind RecoverKind, bool IsFatal,
2881 llvm::BasicBlock *ContBB) {
2882 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
Adrian Prantlc9f24732018-11-28 21:44:06 +00002883 Optional<ApplyDebugLocation> DL;
2884 if (!CGF.Builder.getCurrentDebugLocation()) {
2885 // Ensure that the call has at least an artificial debug location.
2886 DL.emplace(CGF, SourceLocation());
2887 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002888 bool NeedsAbortSuffix =
2889 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002890 bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002891 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2892 const StringRef CheckName = CheckInfo.Name;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002893 std::string FnName = "__ubsan_handle_" + CheckName.str();
2894 if (CheckInfo.Version && !MinimalRuntime)
2895 FnName += "_v" + llvm::utostr(CheckInfo.Version);
2896 if (MinimalRuntime)
2897 FnName += "_minimal";
2898 if (NeedsAbortSuffix)
2899 FnName += "_abort";
Alexey Samsonov88459522015-01-12 22:39:12 +00002900 bool MayReturn =
2901 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2902
2903 llvm::AttrBuilder B;
2904 if (!MayReturn) {
2905 B.addAttribute(llvm::Attribute::NoReturn)
2906 .addAttribute(llvm::Attribute::NoUnwind);
2907 }
2908 B.addAttribute(llvm::Attribute::UWTable);
2909
2910 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2911 FnType, FnName,
Reid Klecknerde864822017-03-21 16:57:30 +00002912 llvm::AttributeList::get(CGF.getLLVMContext(),
2913 llvm::AttributeList::FunctionIndex, B),
Saleem Abdulrasool05b8fde2016-12-15 16:30:20 +00002914 /*Local=*/true);
Alexey Samsonov88459522015-01-12 22:39:12 +00002915 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2916 if (!MayReturn) {
2917 HandlerCall->setDoesNotReturn();
2918 CGF.Builder.CreateUnreachable();
2919 } else {
2920 CGF.Builder.CreateBr(ContBB);
2921 }
2922}
2923
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002924void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002925 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002926 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002927 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002928 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002929 assert(Checked.size() > 0);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002930 assert(CheckHandler >= 0 &&
Zachary Turner260fe3e2017-12-14 22:07:03 +00002931 size_t(CheckHandler) < llvm::array_lengthof(SanitizerHandlers));
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002932 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
Alexey Samsonov88459522015-01-12 22:39:12 +00002933
2934 llvm::Value *FatalCond = nullptr;
2935 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002936 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002937 for (int i = 0, n = Checked.size(); i < n; ++i) {
2938 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002939 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002940 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002941 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2942 ? TrapCond
2943 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2944 ? RecoverableCond
2945 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002946 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2947 }
2948
Peter Collingbourne9881b782015-06-18 23:59:22 +00002949 if (TrapCond)
2950 EmitTrapCheck(TrapCond);
2951 if (!FatalCond && !RecoverableCond)
2952 return;
2953
Alexey Samsonov88459522015-01-12 22:39:12 +00002954 llvm::Value *JointCond;
2955 if (FatalCond && RecoverableCond)
2956 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2957 else
2958 JointCond = FatalCond ? FatalCond : RecoverableCond;
2959 assert(JointCond);
2960
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002961 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002962 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002963#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002964 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002965 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002966 "All recoverable kinds in a single check must be same!");
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002967 assert(SanOpts.has(Checked[i].second));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002968 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002969#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002970
Richard Smith4d1458e2012-09-08 02:08:36 +00002971 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002972 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2973 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002974 // Give hint that we very much don't expect to execute the handler
2975 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2976 llvm::MDBuilder MDHelper(getLLVMContext());
2977 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2978 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002979 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002980
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002981 // Handler functions take an i8* pointing to the (handler-specific) static
2982 // information block, followed by a sequence of intptr_t arguments
2983 // representing operand values.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002984 SmallVector<llvm::Value *, 4> Args;
2985 SmallVector<llvm::Type *, 4> ArgTypes;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002986 if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
2987 Args.reserve(DynamicArgs.size() + 1);
2988 ArgTypes.reserve(DynamicArgs.size() + 1);
Richard Smithe30752c2012-10-09 19:52:38 +00002989
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002990 // Emit handler arguments and create handler function type.
2991 if (!StaticArgs.empty()) {
2992 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2993 auto *InfoPtr =
2994 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2995 llvm::GlobalVariable::PrivateLinkage, Info);
2996 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2997 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2998 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2999 ArgTypes.push_back(Int8PtrTy);
3000 }
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003001
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00003002 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
3003 Args.push_back(EmitCheckValue(DynamicArgs[i]));
3004 ArgTypes.push_back(IntPtrTy);
3005 }
Richard Smithe30752c2012-10-09 19:52:38 +00003006 }
3007
3008 llvm::FunctionType *FnType =
3009 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00003010
Alexey Samsonov88459522015-01-12 22:39:12 +00003011 if (!FatalCond || !RecoverableCond) {
3012 // Simple case: we need to generate a single handler call, either
3013 // fatal, or non-fatal.
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00003014 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
Alexey Samsonov88459522015-01-12 22:39:12 +00003015 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00003016 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00003017 // Emit two handler calls: first one for set of unrecoverable checks,
3018 // another one for recoverable.
3019 llvm::BasicBlock *NonFatalHandlerBB =
3020 createBasicBlock("non_fatal." + CheckName);
3021 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
3022 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
3023 EmitBlock(FatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00003024 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
Alexey Samsonov88459522015-01-12 22:39:12 +00003025 NonFatalHandlerBB);
3026 EmitBlock(NonFatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00003027 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
Alexey Samsonov88459522015-01-12 22:39:12 +00003028 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00003029 }
Richard Smithe30752c2012-10-09 19:52:38 +00003030
Richard Smith4d1458e2012-09-08 02:08:36 +00003031 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00003032}
3033
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003034void CodeGenFunction::EmitCfiSlowPathCheck(
3035 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
3036 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00003037 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
3038
3039 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
3040 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
3041
3042 llvm::MDBuilder MDHelper(getLLVMContext());
3043 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
3044 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
3045
3046 EmitBlock(CheckBB);
3047
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003048 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
3049
3050 llvm::CallInst *CheckCall;
Rafael Espindolab2c47fb2018-03-29 22:08:01 +00003051 llvm::Constant *SlowPathFn;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003052 if (WithDiag) {
3053 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
3054 auto *InfoPtr =
3055 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
3056 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003057 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003058 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
3059
Rafael Espindolab2c47fb2018-03-29 22:08:01 +00003060 SlowPathFn = CGM.getModule().getOrInsertFunction(
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003061 "__cfi_slowpath_diag",
3062 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
3063 false));
3064 CheckCall = Builder.CreateCall(
Rafael Espindolab2c47fb2018-03-29 22:08:01 +00003065 SlowPathFn, {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003066 } else {
Rafael Espindolab2c47fb2018-03-29 22:08:01 +00003067 SlowPathFn = CGM.getModule().getOrInsertFunction(
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003068 "__cfi_slowpath",
3069 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
3070 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
3071 }
3072
Rafael Espindolab2c47fb2018-03-29 22:08:01 +00003073 CGM.setDSOLocal(cast<llvm::GlobalValue>(SlowPathFn->stripPointerCasts()));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00003074 CheckCall->setDoesNotThrow();
3075
3076 EmitBlock(Cont);
3077}
3078
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +00003079// Emit a stub for __cfi_check function so that the linker knows about this
3080// symbol in LTO mode.
3081void CodeGenFunction::EmitCfiCheckStub() {
3082 llvm::Module *M = &CGM.getModule();
3083 auto &Ctx = M->getContext();
3084 llvm::Function *F = llvm::Function::Create(
3085 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
3086 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
Rafael Espindola54d44bf2018-03-29 20:51:30 +00003087 CGM.setDSOLocal(F);
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +00003088 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
3089 // FIXME: consider emitting an intrinsic call like
3090 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
3091 // which can be lowered in CrossDSOCFI pass to the actual contents of
3092 // __cfi_check. This would allow inlining of __cfi_check calls.
3093 llvm::CallInst::Create(
3094 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
3095 llvm::ReturnInst::Create(Ctx, nullptr, BB);
3096}
3097
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003098// This function is basically a switch over the CFI failure kind, which is
3099// extracted from CFICheckFailData (1st function argument). Each case is either
3100// llvm.trap or a call to one of the two runtime handlers, based on
3101// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
3102// failure kind) traps, but this should really never happen. CFICheckFailData
3103// can be nullptr if the calling module has -fsanitize-trap behavior for this
3104// check kind; in this case __cfi_check_fail traps as well.
3105void CodeGenFunction::EmitCfiCheckFail() {
3106 SanitizerScope SanScope(this);
3107 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003108 ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
3109 ImplicitParamDecl::Other);
3110 ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
3111 ImplicitParamDecl::Other);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003112 Args.push_back(&ArgData);
3113 Args.push_back(&ArgAddr);
3114
John McCallc56a8b32016-03-11 04:30:31 +00003115 const CGFunctionInfo &FI =
3116 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003117
3118 llvm::Function *F = llvm::Function::Create(
3119 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
3120 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
3121 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
3122
3123 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
3124 SourceLocation());
3125
Evgeniy Stepanovfb762b22018-06-21 23:22:37 +00003126 // This function should not be affected by blacklist. This function does
3127 // not have a source location, but "src:*" would still apply. Revert any
3128 // changes to SanOpts made in StartFunction.
3129 SanOpts = CGM.getLangOpts().Sanitize;
3130
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003131 llvm::Value *Data =
3132 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
3133 CGM.getContext().VoidPtrTy, ArgData.getLocation());
3134 llvm::Value *Addr =
3135 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
3136 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
3137
3138 // Data == nullptr means the calling module has trap behaviour for this check.
3139 llvm::Value *DataIsNotNullPtr =
3140 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
3141 EmitTrapCheck(DataIsNotNullPtr);
3142
3143 llvm::StructType *SourceLocationTy =
Serge Guelton1d993272017-05-09 19:31:30 +00003144 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003145 llvm::StructType *CfiCheckFailDataTy =
Serge Guelton1d993272017-05-09 19:31:30 +00003146 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003147
3148 llvm::Value *V = Builder.CreateConstGEP2_32(
3149 CfiCheckFailDataTy,
3150 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
3151 0);
3152 Address CheckKindAddr(V, getIntAlign());
3153 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
3154
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00003155 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
3156 CGM.getLLVMContext(),
3157 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
3158 llvm::Value *ValidVtable = Builder.CreateZExt(
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00003159 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00003160 {Addr, AllVtables}),
3161 IntPtrTy);
3162
Evgeniy Stepanov4d3b0872016-01-25 23:45:37 +00003163 const std::pair<int, SanitizerMask> CheckKinds[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003164 {CFITCK_VCall, SanitizerKind::CFIVCall},
3165 {CFITCK_NVCall, SanitizerKind::CFINVCall},
3166 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
3167 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
3168 {CFITCK_ICall, SanitizerKind::CFIICall}};
3169
3170 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
3171 for (auto CheckKindMaskPair : CheckKinds) {
3172 int Kind = CheckKindMaskPair.first;
3173 SanitizerMask Mask = CheckKindMaskPair.second;
3174 llvm::Value *Cond =
3175 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00003176 if (CGM.getLangOpts().Sanitize.has(Mask))
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00003177 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00003178 {Data, Addr, ValidVtable});
3179 else
3180 EmitTrapCheck(Cond);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003181 }
3182
3183 FinishFunction();
3184 // The only reference to this function will be created during LTO link.
3185 // Make sure it survives until then.
3186 CGM.addUsedGlobal(F);
3187}
3188
Vedant Kumar09b5bfd2017-12-21 00:10:25 +00003189void CodeGenFunction::EmitUnreachable(SourceLocation Loc) {
3190 if (SanOpts.has(SanitizerKind::Unreachable)) {
3191 SanitizerScope SanScope(this);
3192 EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()),
3193 SanitizerKind::Unreachable),
3194 SanitizerHandler::BuiltinUnreachable,
3195 EmitCheckSourceLocation(Loc), None);
3196 }
3197 Builder.CreateUnreachable();
3198}
3199
Chad Rosierae229d52013-01-29 23:31:22 +00003200void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00003201 llvm::BasicBlock *Cont = createBasicBlock("cont");
3202
3203 // If we're optimizing, collapse all calls to trap down to just one per
3204 // function to save on code size.
3205 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
3206 TrapBB = createBasicBlock("trap");
3207 Builder.CreateCondBr(Checked, Cont, TrapBB);
3208 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003209 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00003210 TrapCall->setDoesNotReturn();
3211 TrapCall->setDoesNotThrow();
3212 Builder.CreateUnreachable();
3213 } else {
3214 Builder.CreateCondBr(Checked, Cont, TrapBB);
3215 }
3216
3217 EmitBlock(Cont);
3218}
3219
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003220llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00003221 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003222
Amaury Sechet21f51b32016-09-09 04:42:49 +00003223 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3224 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3225 CGM.getCodeGenOpts().TrapFuncName);
Reid Klecknerde864822017-03-21 16:57:30 +00003226 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
Amaury Sechet21f51b32016-09-09 04:42:49 +00003227 }
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003228
3229 return TrapCall;
3230}
3231
John McCall7f416cc2015-09-08 08:05:57 +00003232Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003233 LValueBaseInfo *BaseInfo,
3234 TBAAAccessInfo *TBAAInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00003235 assert(E->getType()->isArrayType() &&
3236 "Array to pointer decay must have array source type!");
3237
3238 // Expressions of array type can't be bitfields or vector elements.
3239 LValue LV = EmitLValue(E);
3240 Address Addr = LV.getAddress();
John McCall7f416cc2015-09-08 08:05:57 +00003241
3242 // If the array type was an incomplete type, we need to make sure
3243 // the decay ends up being the right type.
3244 llvm::Type *NewTy = ConvertType(E->getType());
3245 Addr = Builder.CreateElementBitCast(Addr, NewTy);
3246
3247 // Note that VLA pointers are always decayed, so we don't need to do
3248 // anything here.
3249 if (!E->getType()->isVariableArrayType()) {
3250 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3251 "Expected pointer to array");
3252 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
3253 }
3254
Ivan A. Kosarevf761d0e2017-10-20 12:35:17 +00003255 // The result of this decay conversion points to an array element within the
3256 // base lvalue. However, since TBAA currently does not support representing
3257 // accesses to elements of member arrays, we conservatively represent accesses
3258 // to the pointee object as if it had no any base lvalue specified.
3259 // TODO: Support TBAA for member arrays.
John McCall7f416cc2015-09-08 08:05:57 +00003260 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
Ivan A. Kosarevf761d0e2017-10-20 12:35:17 +00003261 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
3262 if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
3263
John McCall7f416cc2015-09-08 08:05:57 +00003264 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
3265}
3266
Chris Lattner6c5abe82010-06-26 23:03:20 +00003267/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
3268/// array to pointer, return the array subexpression.
3269static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
3270 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003271 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00003272 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00003273 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00003274
Chris Lattner6c5abe82010-06-26 23:03:20 +00003275 // If this is a decay from variable width array, bail out.
3276 const Expr *SubExpr = CE->getSubExpr();
3277 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00003278 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00003279
Chris Lattner6c5abe82010-06-26 23:03:20 +00003280 return SubExpr;
3281}
3282
John McCall7f416cc2015-09-08 08:05:57 +00003283static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3284 llvm::Value *ptr,
3285 ArrayRef<llvm::Value*> indices,
3286 bool inbounds,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003287 bool signedIndices,
Vedant Kumara125eb52017-06-01 19:22:18 +00003288 SourceLocation loc,
John McCall7f416cc2015-09-08 08:05:57 +00003289 const llvm::Twine &name = "arrayidx") {
3290 if (inbounds) {
Vedant Kumar175b6d12017-07-13 20:55:26 +00003291 return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices,
3292 CodeGenFunction::NotSubtraction, loc,
3293 name);
John McCall7f416cc2015-09-08 08:05:57 +00003294 } else {
3295 return CGF.Builder.CreateGEP(ptr, indices, name);
3296 }
3297}
3298
3299static CharUnits getArrayElementAlign(CharUnits arrayAlign,
3300 llvm::Value *idx,
3301 CharUnits eltSize) {
3302 // If we have a constant index, we can use the exact offset of the
3303 // element we're accessing.
3304 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3305 CharUnits offset = constantIdx->getZExtValue() * eltSize;
3306 return arrayAlign.alignmentAtOffset(offset);
3307
3308 // Otherwise, use the worst-case alignment for any element.
3309 } else {
3310 return arrayAlign.alignmentOfArrayElement(eltSize);
3311 }
3312}
3313
3314static QualType getFixedSizeElementType(const ASTContext &ctx,
3315 const VariableArrayType *vla) {
3316 QualType eltType;
3317 do {
3318 eltType = vla->getElementType();
3319 } while ((vla = ctx.getAsVariableArrayType(eltType)));
3320 return eltType;
3321}
3322
3323static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
Vedant Kumara125eb52017-06-01 19:22:18 +00003324 ArrayRef<llvm::Value *> indices,
John McCall7f416cc2015-09-08 08:05:57 +00003325 QualType eltType, bool inbounds,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003326 bool signedIndices, SourceLocation loc,
John McCall7f416cc2015-09-08 08:05:57 +00003327 const llvm::Twine &name = "arrayidx") {
3328 // All the indices except that last must be zero.
3329#ifndef NDEBUG
3330 for (auto idx : indices.drop_back())
3331 assert(isa<llvm::ConstantInt>(idx) &&
3332 cast<llvm::ConstantInt>(idx)->isZero());
Fangrui Song6907ce22018-07-30 19:24:48 +00003333#endif
John McCall7f416cc2015-09-08 08:05:57 +00003334
3335 // Determine the element size of the statically-sized base. This is
3336 // the thing that the indices are expressed in terms of.
3337 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3338 eltType = getFixedSizeElementType(CGF.getContext(), vla);
3339 }
3340
3341 // We can use that to compute the best alignment of the element.
3342 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3343 CharUnits eltAlign =
3344 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3345
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003346 llvm::Value *eltPtr = emitArraySubscriptGEP(
3347 CGF, addr.getPointer(), indices, inbounds, signedIndices, loc, name);
John McCall7f416cc2015-09-08 08:05:57 +00003348 return Address(eltPtr, eltAlign);
3349}
3350
Richard Smith539e4a72013-02-23 02:53:19 +00003351LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3352 bool Accessed) {
Richard Smith9e67b992016-09-26 23:49:47 +00003353 // The index must always be an integer, which is not an aggregate. Emit it
3354 // in lexical order (this complexity is, sadly, required by C++17).
3355 llvm::Value *IdxPre =
3356 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003357 bool SignedIndices = false;
Richard Smith40885712016-09-27 00:53:24 +00003358 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
Richard Smith9e67b992016-09-26 23:49:47 +00003359 auto *Idx = IdxPre;
3360 if (E->getLHS() != E->getIdx()) {
3361 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3362 Idx = EmitScalarExpr(E->getIdx());
3363 }
Eli Friedman07bbeca2009-06-06 19:09:26 +00003364
Richard Smith9e67b992016-09-26 23:49:47 +00003365 QualType IdxTy = E->getIdx()->getType();
3366 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003367 SignedIndices |= IdxSigned;
Richard Smith9e67b992016-09-26 23:49:47 +00003368
3369 if (SanOpts.has(SanitizerKind::ArrayBounds))
3370 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3371
3372 // Extend or truncate the index type to 32 or 64-bits.
3373 if (Promote && Idx->getType() != IntPtrTy)
3374 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3375
3376 return Idx;
3377 };
3378 IdxPre = nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +00003379
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003380 // If the base is a vector type, then we are forming a vector element lvalue
3381 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003382 if (E->getBase()->getType()->isVectorType() &&
3383 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003384 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00003385 LValue LHS = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003386 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
Ted Kremenekc81614d2007-08-20 16:18:38 +00003387 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00003388 return LValue::MakeVectorElt(LHS.getAddress(), Idx, E->getBase()->getType(),
3389 LHS.getBaseInfo(), TBAAAccessInfo());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003390 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003391
John McCall7f416cc2015-09-08 08:05:57 +00003392 // All the other cases basically behave like simple offsetting.
3393
John McCall7f416cc2015-09-08 08:05:57 +00003394 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003395 if (isa<ExtVectorElementExpr>(E->getBase())) {
3396 LValue LV = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003397 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003398 Address Addr = EmitExtVectorElementLValue(LV);
3399
3400 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
Vedant Kumara125eb52017-06-01 19:22:18 +00003401 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003402 SignedIndices, E->getExprLoc());
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00003403 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003404 CGM.getTBAAInfoForSubobject(LV, EltType));
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003405 }
John McCall7f416cc2015-09-08 08:05:57 +00003406
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003407 LValueBaseInfo EltBaseInfo;
3408 TBAAAccessInfo EltTBAAInfo;
John McCall7f416cc2015-09-08 08:05:57 +00003409 Address Addr = Address::invalid();
3410 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003411 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00003412 // The base must be a pointer, which is not an aggregate. Emit
3413 // it. It needs to be emitted first in case it's what captures
3414 // the VLA bounds.
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003415 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003416 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Mike Stump4a3999f2009-09-09 13:00:44 +00003417
John McCall23c29fe2011-06-24 21:55:10 +00003418 // The element count here is the total number of non-VLA elements.
Sander de Smalen891af03a2018-02-03 13:55:59 +00003419 llvm::Value *numElements = getVLASize(vla).NumElts;
Mike Stump4a3999f2009-09-09 13:00:44 +00003420
John McCall77527a82011-06-25 01:32:37 +00003421 // Effectively, the multiply by the VLA size is part of the GEP.
3422 // GEP indexes are signed, and scaling an index isn't permitted to
3423 // signed-overflow, so we use the same semantics for our explicit
3424 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003425 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00003426 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003427 } else {
3428 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003429 }
John McCall7f416cc2015-09-08 08:05:57 +00003430
3431 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003432 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003433 SignedIndices, E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00003434
Chris Lattner6c5abe82010-06-26 23:03:20 +00003435 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3436 // Indexing over an interface, as in "NSString *P; P[4];"
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003437
John McCall7f416cc2015-09-08 08:05:57 +00003438 // Emit the base pointer.
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003439 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003440 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3441
3442 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3443 llvm::Value *InterfaceSizeVal =
3444 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3445
3446 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
John McCall7f416cc2015-09-08 08:05:57 +00003447
3448 // We don't necessarily build correct LLVM struct types for ObjC
3449 // interfaces, so we can't rely on GEP to do this scaling
3450 // correctly, so we need to cast to i8*. FIXME: is this actually
3451 // true? A lot of other things in the fragile ABI would break...
3452 llvm::Type *OrigBaseTy = Addr.getType();
3453 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3454
3455 // Do the GEP.
3456 CharUnits EltAlign =
3457 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003458 llvm::Value *EltPtr =
3459 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false,
3460 SignedIndices, E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00003461 Addr = Address(EltPtr, EltAlign);
3462
3463 // Cast back.
3464 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00003465 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3466 // If this is A[i] where A is an array, the frontend will have decayed the
3467 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3468 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3469 // "gep x, i" here. Emit one "gep A, 0, i".
3470 assert(Array->getType()->isArrayType() &&
3471 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00003472 LValue ArrayLV;
3473 // For simple multidimensional array indexing, set the 'accessed' flag for
3474 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003475 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00003476 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3477 else
3478 ArrayLV = EmitLValue(Array);
Richard Smith9e67b992016-09-26 23:49:47 +00003479 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Craig Topper99e79272013-07-26 05:59:26 +00003480
Daniel Dunbar82634272011-04-01 00:49:43 +00003481 // Propagate the alignment from the array itself to the result.
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003482 Addr = emitArraySubscriptGEP(
3483 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3484 E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3485 E->getExprLoc());
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003486 EltBaseInfo = ArrayLV.getBaseInfo();
3487 EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003488 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003489 // The base must be a pointer; emit it with an estimate of its alignment.
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003490 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003491 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003492 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003493 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003494 SignedIndices, E->getExprLoc());
Anders Carlsson3d312f82008-12-21 00:11:23 +00003495 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003496
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003497 LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
John McCall8ccfcb52009-09-24 19:53:00 +00003498
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003499 if (getLangOpts().ObjC &&
Richard Smith9c6890a2012-11-01 22:30:59 +00003500 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00003501 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00003502 setObjCGCLValueClass(getContext(), E, LV);
3503 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00003504 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00003505}
3506
Alexey Bataev31300ed2016-02-04 11:27:03 +00003507static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003508 LValueBaseInfo &BaseInfo,
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003509 TBAAAccessInfo &TBAAInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003510 QualType BaseTy, QualType ElTy,
3511 bool IsLowerBound) {
3512 LValue BaseLVal;
3513 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3514 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3515 if (BaseTy->isArrayType()) {
3516 Address Addr = BaseLVal.getAddress();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003517 BaseInfo = BaseLVal.getBaseInfo();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003518
3519 // If the array type was an incomplete type, we need to make sure
3520 // the decay ends up being the right type.
3521 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3522 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3523
3524 // Note that VLA pointers are always decayed, so we don't need to do
3525 // anything here.
3526 if (!BaseTy->isVariableArrayType()) {
3527 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3528 "Expected pointer to array");
3529 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3530 "arraydecay");
3531 }
3532
3533 return CGF.Builder.CreateElementBitCast(Addr,
3534 CGF.ConvertTypeForMem(ElTy));
3535 }
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003536 LValueBaseInfo TypeBaseInfo;
3537 TBAAAccessInfo TypeTBAAInfo;
3538 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &TypeBaseInfo,
3539 &TypeTBAAInfo);
3540 BaseInfo.mergeForCast(TypeBaseInfo);
3541 TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003542 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3543 }
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003544 return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003545}
3546
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003547LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3548 bool IsLowerBound) {
Alexey Bataev7b0f1f02017-10-12 15:18:41 +00003549 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(E->getBase());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003550 QualType ResultExprTy;
3551 if (auto *AT = getContext().getAsArrayType(BaseTy))
3552 ResultExprTy = AT->getElementType();
3553 else
3554 ResultExprTy = BaseTy->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003555 llvm::Value *Idx = nullptr;
Benjamin Kramer5ff67472016-04-11 08:26:13 +00003556 if (IsLowerBound || E->getColonLoc().isInvalid()) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003557 // Requesting lower bound or upper bound, but without provided length and
3558 // without ':' symbol for the default length -> length = 1.
3559 // Idx = LowerBound ?: 0;
3560 if (auto *LowerBound = E->getLowerBound()) {
3561 Idx = Builder.CreateIntCast(
3562 EmitScalarExpr(LowerBound), IntPtrTy,
3563 LowerBound->getType()->hasSignedIntegerRepresentation());
3564 } else
3565 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3566 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003567 // Try to emit length or lower bound as constant. If this is possible, 1
3568 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3569 // IR (LB + Len) - 1.
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003570 auto &C = CGM.getContext();
3571 auto *Length = E->getLength();
3572 llvm::APSInt ConstLength;
3573 if (Length) {
3574 // Idx = LowerBound + Length - 1;
3575 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3576 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3577 Length = nullptr;
3578 }
3579 auto *LowerBound = E->getLowerBound();
3580 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3581 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3582 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3583 LowerBound = nullptr;
3584 }
3585 if (!Length)
3586 --ConstLength;
3587 else if (!LowerBound)
3588 --ConstLowerBound;
3589
3590 if (Length || LowerBound) {
3591 auto *LowerBoundVal =
3592 LowerBound
3593 ? Builder.CreateIntCast(
3594 EmitScalarExpr(LowerBound), IntPtrTy,
3595 LowerBound->getType()->hasSignedIntegerRepresentation())
3596 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3597 auto *LengthVal =
3598 Length
3599 ? Builder.CreateIntCast(
3600 EmitScalarExpr(Length), IntPtrTy,
3601 Length->getType()->hasSignedIntegerRepresentation())
3602 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3603 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3604 /*HasNUW=*/false,
3605 !getLangOpts().isSignedOverflowDefined());
3606 if (Length && LowerBound) {
3607 Idx = Builder.CreateSub(
3608 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3609 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3610 }
3611 } else
3612 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3613 } else {
3614 // Idx = ArraySize - 1;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003615 QualType ArrayTy = BaseTy->isPointerType()
3616 ? E->getBase()->IgnoreParenImpCasts()->getType()
3617 : BaseTy;
3618 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003619 Length = VAT->getSizeExpr();
3620 if (Length->isIntegerConstantExpr(ConstLength, C))
3621 Length = nullptr;
3622 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003623 auto *CAT = C.getAsConstantArrayType(ArrayTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003624 ConstLength = CAT->getSize();
3625 }
3626 if (Length) {
3627 auto *LengthVal = Builder.CreateIntCast(
3628 EmitScalarExpr(Length), IntPtrTy,
3629 Length->getType()->hasSignedIntegerRepresentation());
3630 Idx = Builder.CreateSub(
3631 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3632 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3633 } else {
3634 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3635 --ConstLength;
3636 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3637 }
3638 }
3639 }
3640 assert(Idx);
3641
Alexey Bataev31300ed2016-02-04 11:27:03 +00003642 Address EltPtr = Address::invalid();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003643 LValueBaseInfo BaseInfo;
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003644 TBAAAccessInfo TBAAInfo;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003645 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003646 // The base must be a pointer, which is not an aggregate. Emit
3647 // it. It needs to be emitted first in case it's what captures
3648 // the VLA bounds.
3649 Address Base =
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003650 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
3651 BaseTy, VLA->getElementType(), IsLowerBound);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003652 // The element count here is the total number of non-VLA elements.
Sander de Smalen891af03a2018-02-03 13:55:59 +00003653 llvm::Value *NumElements = getVLASize(VLA).NumElts;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003654
3655 // Effectively, the multiply by the VLA size is part of the GEP.
3656 // GEP indexes are signed, and scaling an index isn't permitted to
3657 // signed-overflow, so we use the same semantics for our explicit
3658 // multiply. We suppress this if overflow is not undefined behavior.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003659 if (getLangOpts().isSignedOverflowDefined())
3660 Idx = Builder.CreateMul(Idx, NumElements);
3661 else
3662 Idx = Builder.CreateNSWMul(Idx, NumElements);
3663 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003664 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003665 /*SignedIndices=*/false, E->getExprLoc());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003666 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3667 // If this is A[i] where A is an array, the frontend will have decayed the
3668 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3669 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3670 // "gep x, i" here. Emit one "gep A, 0, i".
3671 assert(Array->getType()->isArrayType() &&
3672 "Array to pointer decay must have array source type!");
3673 LValue ArrayLV;
3674 // For simple multidimensional array indexing, set the 'accessed' flag for
3675 // better bounds-checking of the base expression.
3676 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3677 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3678 else
3679 ArrayLV = EmitLValue(Array);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003680
Alexey Bataev31300ed2016-02-04 11:27:03 +00003681 // Propagate the alignment from the array itself to the result.
3682 EltPtr = emitArraySubscriptGEP(
3683 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
Vedant Kumara125eb52017-06-01 19:22:18 +00003684 ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003685 /*SignedIndices=*/false, E->getExprLoc());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003686 BaseInfo = ArrayLV.getBaseInfo();
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003687 TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003688 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003689 Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003690 TBAAInfo, BaseTy, ResultExprTy,
3691 IsLowerBound);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003692 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
Vedant Kumara125eb52017-06-01 19:22:18 +00003693 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003694 /*SignedIndices=*/false, E->getExprLoc());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003695 }
3696
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003697 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003698}
3699
Chris Lattner9e751ca2007-08-02 23:37:31 +00003700LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00003701EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00003702 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003703 LValue Base;
3704
3705 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00003706 if (E->isArrow()) {
3707 // If it is a pointer to a vector, emit the address and form an lvalue with
3708 // it.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003709 LValueBaseInfo BaseInfo;
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003710 TBAAAccessInfo TBAAInfo;
3711 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003712 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003713 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
Daniel Dunbarf166a522010-08-21 03:44:13 +00003714 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00003715 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00003716 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3717 // emit the base as an lvalue.
3718 assert(E->getBase()->getType()->isVectorType());
3719 Base = EmitLValue(E->getBase());
3720 } else {
3721 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00003722 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00003723 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00003724 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00003725
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00003726 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00003727 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00003728 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00003729 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00003730 AlignmentSource::Decl);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003731 }
John McCall1553b192011-06-16 04:16:24 +00003732
3733 QualType type =
3734 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00003735
Nate Begemand3862152008-05-13 21:03:02 +00003736 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00003737 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00003738 E->getEncodedElementAccess(Indices);
3739
3740 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00003741 llvm::Constant *CV =
3742 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00003743 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00003744 Base.getBaseInfo(), TBAAAccessInfo());
Nate Begemand3862152008-05-13 21:03:02 +00003745 }
3746 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3747
3748 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003749 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00003750
Chris Lattner595ba3a2012-01-30 06:20:36 +00003751 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3752 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00003753 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00003754 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00003755 Base.getBaseInfo(), TBAAAccessInfo());
Chris Lattner9e751ca2007-08-02 23:37:31 +00003756}
3757
Devang Patel30efa2e2007-10-23 20:28:39 +00003758LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Alex Lorenz6cc83172017-08-25 10:07:00 +00003759 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
3760 EmitIgnoredExpr(E->getBase());
3761 return EmitDeclRefLValue(DRE);
3762 }
3763
Devang Pateld68df202007-10-24 22:26:28 +00003764 Expr *BaseExpr = E->getBase();
Chris Lattner4e4186b2007-12-02 18:52:07 +00003765 // 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 +00003766 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00003767 if (E->isArrow()) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003768 LValueBaseInfo BaseInfo;
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003769 TBAAAccessInfo TBAAInfo;
3770 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
Richard Smith69d0d262012-08-24 00:54:33 +00003771 QualType PtrTy = BaseExpr->getType()->getPointeeType();
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003772 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00003773 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
3774 if (IsBaseCXXThis)
3775 SkippedChecks.set(SanitizerKind::Alignment, true);
3776 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003777 SkippedChecks.set(SanitizerKind::Null, true);
3778 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
3779 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003780 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
Richard Smith69d0d262012-08-24 00:54:33 +00003781 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003782 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003783
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003784 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003785 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003786 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003787 setObjCGCLValueClass(getContext(), E, LV);
3788 return LV;
3789 }
Craig Topper99e79272013-07-26 05:59:26 +00003790
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003791 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003792 return EmitFunctionDeclLValue(*this, E, FD);
3793
David Blaikie83d382b2011-09-23 05:06:16 +00003794 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003795}
Devang Patel30efa2e2007-10-23 20:28:39 +00003796
John McCalldec348f72013-05-03 07:33:41 +00003797/// Given that we are currently emitting a lambda, emit an l-value for
3798/// one of its members.
3799LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3800 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3801 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3802 QualType LambdaTagType =
3803 getContext().getTagDeclType(Field->getParent());
3804 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3805 return EmitLValueForField(LambdaLV, Field);
3806}
3807
John McCall7f416cc2015-09-08 08:05:57 +00003808/// Drill down to the storage of a field without walking into
3809/// reference types.
3810///
3811/// The resulting address doesn't necessarily have the right type.
3812static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3813 const FieldDecl *field) {
3814 const RecordDecl *rec = field->getParent();
Fangrui Song6907ce22018-07-30 19:24:48 +00003815
John McCall7f416cc2015-09-08 08:05:57 +00003816 unsigned idx =
3817 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3818
3819 CharUnits offset;
3820 // Adjust the alignment down to the given offset.
3821 // As a special case, if the LLVM field index is 0, we know that this
3822 // is zero.
3823 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3824 .getFieldOffset(field->getFieldIndex()) == 0) &&
3825 "LLVM field at index zero had non-zero offset?");
3826 if (idx != 0) {
3827 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3828 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3829 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3830 }
3831
3832 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3833}
3834
Piotr Padlewskic1d26062017-06-01 18:39:34 +00003835static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
3836 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
3837 if (!RD)
3838 return false;
3839
3840 if (RD->isDynamicClass())
3841 return true;
3842
3843 for (const auto &Base : RD->bases())
3844 if (hasAnyVptr(Base.getType(), Context))
3845 return true;
3846
3847 for (const FieldDecl *Field : RD->fields())
3848 if (hasAnyVptr(Field->getType(), Context))
3849 return true;
3850
3851 return false;
3852}
3853
Eli Friedman7f1ff602012-04-16 03:54:45 +00003854LValue CodeGenFunction::EmitLValueForField(LValue base,
3855 const FieldDecl *field) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003856 LValueBaseInfo BaseInfo = base.getBaseInfo();
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00003857
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003858 if (field->isBitField()) {
3859 const CGRecordLayout &RL =
3860 CGM.getTypes().getCGRecordLayout(field->getParent());
3861 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003862 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003863 unsigned Idx = RL.getLLVMFieldNo(field);
3864 if (Idx != 0)
3865 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003866 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3867 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003868 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003869 llvm::Type *FieldIntTy =
3870 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3871 if (Addr.getElementType() != FieldIntTy)
3872 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003873
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003874 QualType fieldType =
3875 field->getType().withCVRQualifiers(base.getVRQualifiers());
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003876 // TODO: Support TBAA for bit fields.
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003877 LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00003878 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
3879 TBAAAccessInfo());
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003880 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003881
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003882 // Fields of may-alias structures are may-alias themselves.
3883 // FIXME: this should get propagated down through anonymous structs
3884 // and unions.
3885 QualType FieldType = field->getType();
3886 const RecordDecl *rec = field->getParent();
3887 AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003888 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003889 TBAAAccessInfo FieldTBAAInfo;
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003890 if (base.getTBAAInfo().isMayAlias() ||
3891 rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
3892 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
Hal Finkela5986b92017-12-03 03:10:13 +00003893 } else if (rec->isUnion()) {
3894 // TODO: Support TBAA for unions.
3895 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003896 } else {
3897 // If no base type been assigned for the base access, then try to generate
3898 // one for this base lvalue.
3899 FieldTBAAInfo = base.getTBAAInfo();
3900 if (!FieldTBAAInfo.BaseType) {
3901 FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
3902 assert(!FieldTBAAInfo.Offset &&
3903 "Nonzero offset for an access with no base type!");
3904 }
3905
Hal Finkela5986b92017-12-03 03:10:13 +00003906 // Adjust offset to be relative to the base type.
3907 const ASTRecordLayout &Layout =
3908 getContext().getASTRecordLayout(field->getParent());
3909 unsigned CharWidth = getContext().getCharWidth();
3910 if (FieldTBAAInfo.BaseType)
3911 FieldTBAAInfo.Offset +=
3912 Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003913
Ivan A. Kosarev617c3b72017-12-21 08:14:16 +00003914 // Update the final access type and size.
Hal Finkela5986b92017-12-03 03:10:13 +00003915 FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
Ivan A. Kosarev617c3b72017-12-21 08:14:16 +00003916 FieldTBAAInfo.Size =
3917 getContext().getTypeSizeInChars(FieldType).getQuantity();
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003918 }
3919
John McCall7f416cc2015-09-08 08:05:57 +00003920 Address addr = base.getAddress();
Piotr Padlewski07058292018-07-02 19:21:36 +00003921 if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) {
3922 if (CGM.getCodeGenOpts().StrictVTablePointers &&
3923 ClassDef->isDynamicClass()) {
3924 // Getting to any field of dynamic object requires stripping dynamic
3925 // information provided by invariant.group. This is because accessing
3926 // fields may leak the real address of dynamic object, which could result
3927 // in miscompilation when leaked pointer would be compared.
3928 auto *stripped = Builder.CreateStripInvariantGroup(addr.getPointer());
3929 addr = Address(stripped, addr.getAlignment());
3930 }
3931 }
3932
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00003933 unsigned RecordCVR = base.getVRQualifiers();
John McCall53fcbd22011-02-26 08:07:02 +00003934 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003935 // For unions, there is no pointer adjustment.
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003936 assert(!FieldType->isReferenceType() && "union has reference member");
Piotr Padlewskic1d26062017-06-01 18:39:34 +00003937 if (CGM.getCodeGenOpts().StrictVTablePointers &&
3938 hasAnyVptr(FieldType, getContext()))
3939 // Because unions can easily skip invariant.barriers, we need to add
3940 // a barrier every time CXXRecord field with vptr is referenced.
Piotr Padlewski5dde8092018-05-03 11:03:01 +00003941 addr = Address(Builder.CreateLaunderInvariantGroup(addr.getPointer()),
Piotr Padlewskic1d26062017-06-01 18:39:34 +00003942 addr.getAlignment());
John McCall53fcbd22011-02-26 08:07:02 +00003943 } else {
3944 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003945 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003946
3947 // If this is a reference field, load the reference right now.
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00003948 if (FieldType->isReferenceType()) {
3949 LValue RefLVal = MakeAddrLValue(addr, FieldType, FieldBaseInfo,
3950 FieldTBAAInfo);
3951 if (RecordCVR & Qualifiers::Volatile)
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00003952 RefLVal.getQuals().addVolatile();
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00003953 addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
John McCall53fcbd22011-02-26 08:07:02 +00003954
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00003955 // Qualifiers on the struct don't apply to the referencee.
3956 RecordCVR = 0;
3957 FieldType = FieldType->getPointeeType();
John McCall53fcbd22011-02-26 08:07:02 +00003958 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003959 }
Craig Topper99e79272013-07-26 05:59:26 +00003960
Chris Lattner13ee4f42011-07-10 05:34:54 +00003961 // Make sure that the address is pointing to the right type. This is critical
3962 // for both unions and structs. A union needs a bitcast, a struct element
3963 // will need a bitcast if the LLVM type laid out doesn't match the desired
3964 // type.
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003965 addr = Builder.CreateElementBitCast(
3966 addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003967
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003968 if (field->hasAttr<AnnotateAttr>())
3969 addr = EmitFieldAnnotations(field, addr);
3970
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00003971 LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00003972 LV.getQuals().addCVRQualifiers(RecordCVR);
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00003973
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003974 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003975 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3976 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003977
Daniel Dunbarf166a522010-08-21 03:44:13 +00003978 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003979}
3980
Craig Topper99e79272013-07-26 05:59:26 +00003981LValue
3982CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003983 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003984 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003985
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003986 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003987 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003988
John McCall7f416cc2015-09-08 08:05:57 +00003989 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003990
John McCall7f416cc2015-09-08 08:05:57 +00003991 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003992 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003993 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003994
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003995 // TODO: Generate TBAA information that describes this access as a structure
3996 // member access and not just an access to an object of the field's type. This
3997 // should be similar to what we do in EmitLValueForField().
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003998 LValueBaseInfo BaseInfo = Base.getBaseInfo();
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003999 AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
4000 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004001 return MakeAddrLValue(V, FieldType, FieldBaseInfo,
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004002 CGM.getTBAAInfoForSubobject(Base, FieldType));
Anders Carlssondb78f0a2010-01-29 05:24:29 +00004003}
4004
Chris Lattnerf53c0962010-09-06 00:11:41 +00004005LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00004006 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00004007 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004008 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
Richard Smith2d988f02011-11-22 22:48:32 +00004009 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00004010 if (E->getType()->isVariablyModifiedType())
4011 // make sure to emit the VLA size.
4012 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00004013
John McCall7f416cc2015-09-08 08:05:57 +00004014 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00004015 const Expr *InitExpr = E->getInitializer();
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004016 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
Eli Friedman9fd8b682008-05-13 23:18:27 +00004017
Chad Rosier615ed1a2012-03-29 17:37:10 +00004018 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
4019 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00004020
4021 return Result;
4022}
4023
Richard Smithbb653bd2012-05-14 21:57:21 +00004024LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
4025 if (!E->isGLValue())
4026 // Initializing an aggregate temporary in C++11: T{...}.
4027 return EmitAggExprToLValue(E);
4028
4029 // An lvalue initializer list must be initializing a reference.
Richard Smith122f88d2016-12-06 23:52:28 +00004030 assert(E->isTransparent() && "non-transparent glvalue init list");
Richard Smithbb653bd2012-05-14 21:57:21 +00004031 return EmitLValue(E->getInit(0));
4032}
4033
Richard Smithf3076ff2014-06-20 18:43:47 +00004034/// Emit the operand of a glvalue conditional operator. This is either a glvalue
4035/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
4036/// LValue is returned and the current block has been terminated.
4037static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
4038 const Expr *Operand) {
4039 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
4040 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
4041 return None;
4042 }
4043
4044 return CGF.EmitLValue(Operand);
4045}
4046
John McCallc07a0c72011-02-17 10:25:35 +00004047LValue CodeGenFunction::
4048EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
4049 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00004050 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00004051 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00004052 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00004053 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00004054 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00004055
Eli Friedman59954892012-01-25 05:04:17 +00004056 OpaqueValueMapping binding(*this, expr);
4057
John McCallc07a0c72011-02-17 10:25:35 +00004058 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00004059 bool CondExprBool;
4060 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00004061 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00004062 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00004063
Justin Bogneref512b92014-01-06 22:27:43 +00004064 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00004065 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00004066 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00004067 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00004068 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00004069 }
John McCall0a6bf2e2011-01-26 19:21:13 +00004070 }
4071
John McCallc07a0c72011-02-17 10:25:35 +00004072 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
4073 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
4074 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00004075
4076 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00004077 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00004078
John McCall0a6bf2e2011-01-26 19:21:13 +00004079 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00004080 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00004081 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00004082 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00004083 Optional<LValue> lhs =
4084 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00004085 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00004086
Richard Smithf3076ff2014-06-20 18:43:47 +00004087 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00004088 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00004089
John McCallc07a0c72011-02-17 10:25:35 +00004090 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00004091 if (lhs)
4092 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00004093
John McCall0a6bf2e2011-01-26 19:21:13 +00004094 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00004095 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00004096 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00004097 Optional<LValue> rhs =
4098 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00004099 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00004100 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00004101 return EmitUnsupportedLValue(expr, "conditional operator");
4102 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00004103
John McCallc07a0c72011-02-17 10:25:35 +00004104 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00004105
Richard Smithf3076ff2014-06-20 18:43:47 +00004106 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00004107 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00004108 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00004109 phi->addIncoming(lhs->getPointer(), lhsBlock);
4110 phi->addIncoming(rhs->getPointer(), rhsBlock);
4111 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
4112 AlignmentSource alignSource =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004113 std::max(lhs->getBaseInfo().getAlignmentSource(),
4114 rhs->getBaseInfo().getAlignmentSource());
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004115 TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
4116 lhs->getTBAAInfo(), rhs->getTBAAInfo());
4117 return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
4118 TBAAInfo);
Richard Smithf3076ff2014-06-20 18:43:47 +00004119 } else {
4120 assert((lhs || rhs) &&
4121 "both operands of glvalue conditional are throw-expressions?");
4122 return lhs ? *lhs : *rhs;
4123 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00004124}
4125
Richard Smithbb653bd2012-05-14 21:57:21 +00004126/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
4127/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00004128/// otherwise if a cast is needed by the code generator in an lvalue context,
4129/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00004130/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00004131/// are permitted with aggregate result, including noop aggregate casts, and
4132/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00004133LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00004134 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00004135 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00004136 case CK_BitCast:
4137 case CK_ArrayToPointerDecay:
4138 case CK_FunctionToPointerDecay:
4139 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00004140 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00004141 case CK_IntegralToPointer:
4142 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00004143 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00004144 case CK_VectorSplat:
4145 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00004146 case CK_BooleanToSignedIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00004147 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00004148 case CK_IntegralToFloating:
4149 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00004150 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00004151 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00004152 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00004153 case CK_FloatingComplexToReal:
4154 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00004155 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00004156 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00004157 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00004158 case CK_IntegralComplexToReal:
4159 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00004160 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00004161 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00004162 case CK_DerivedToBaseMemberPointer:
4163 case CK_BaseToDerivedMemberPointer:
4164 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00004165 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00004166 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00004167 case CK_ARCProduceObject:
4168 case CK_ARCConsumeObject:
4169 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00004170 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00004171 case CK_CopyAndAutoreleaseBlockObject:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00004172 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +00004173 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +00004174 case CK_FixedPointToBoolean:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00004175 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
4176
4177 case CK_Dependent:
4178 llvm_unreachable("dependent cast kind in IR gen!");
4179
4180 case CK_BuiltinFnToFnPtr:
4181 llvm_unreachable("builtin functions are handled elsewhere");
4182
Eli Friedmanbe4504d2013-07-11 01:32:21 +00004183 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00004184 case CK_NonAtomicToAtomic:
4185 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00004186 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00004187
Anders Carlsson8a01a752011-04-11 02:03:26 +00004188 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00004189 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004190 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004191 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00004192 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00004193 }
4194
John McCalle3027922010-08-25 11:45:40 +00004195 case CK_ConstructorConversion:
4196 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00004197 case CK_CPointerToObjCPointerCast:
4198 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00004199 case CK_NoOp:
4200 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00004201 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00004202
John McCalle3027922010-08-25 11:45:40 +00004203 case CK_UncheckedDerivedToBase:
4204 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00004205 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00004206 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004207 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00004208
Anders Carlssond95f9602009-09-12 16:16:49 +00004209 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004210 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00004211
Anders Carlssond95f9602009-09-12 16:16:49 +00004212 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00004213 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00004214 This, DerivedClassDecl, E->path_begin(), E->path_end(),
4215 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00004216
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004217 // TODO: Support accesses to members of base classes in TBAA. For now, we
4218 // conservatively pretend that the complete object is of the base class
4219 // type.
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004220 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004221 CGM.getTBAAInfoForSubobject(LV, E->getType()));
Anders Carlssond95f9602009-09-12 16:16:49 +00004222 }
John McCalle3027922010-08-25 11:45:40 +00004223 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00004224 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00004225 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00004226 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004227 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00004228
Anders Carlsson8c793172009-11-23 17:57:54 +00004229 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00004230
Anders Carlsson8c793172009-11-23 17:57:54 +00004231 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00004232 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00004233 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00004234 E->path_begin(), E->path_end(),
4235 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00004236
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004237 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
4238 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00004239 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004240 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00004241 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004242
Peter Collingbourned2926c92015-03-14 02:42:25 +00004243 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00004244 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004245 /*MayBeNull=*/false, CFITCK_DerivedCast,
4246 E->getBeginLoc());
Peter Collingbourned2926c92015-03-14 02:42:25 +00004247
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004248 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004249 CGM.getTBAAInfoForSubobject(LV, E->getType()));
Eli Friedman8c98dff2009-11-16 05:48:01 +00004250 }
John McCalle3027922010-08-25 11:45:40 +00004251 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00004252 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004253 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00004254
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00004255 CGM.EmitExplicitCastExprType(CE, this);
Anders Carlsson50cb3212009-11-14 21:21:42 +00004256 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004257 Address V = Builder.CreateBitCast(LV.getAddress(),
4258 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00004259
4260 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00004261 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004262 /*MayBeNull=*/false, CFITCK_UnrelatedCast,
4263 E->getBeginLoc());
Peter Collingbourned2926c92015-03-14 02:42:25 +00004264
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004265 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004266 CGM.getTBAAInfoForSubobject(LV, E->getType()));
Anders Carlsson50cb3212009-11-14 21:21:42 +00004267 }
Anastasia Stulova04307942018-11-16 16:22:56 +00004268 case CK_AddressSpaceConversion: {
4269 LValue LV = EmitLValue(E->getSubExpr());
4270 QualType DestTy = getContext().getPointerType(E->getType());
4271 llvm::Value *V = getTargetHooks().performAddrSpaceCast(
4272 *this, LV.getPointer(), E->getSubExpr()->getType().getAddressSpace(),
Andrew Savonichev87a7e432018-12-12 09:51:23 +00004273 E->getType().getAddressSpace(), ConvertType(DestTy));
4274 return MakeAddrLValue(Address(V, LV.getAddress().getAlignment()),
4275 E->getType(), LV.getBaseInfo(), LV.getTBAAInfo());
Anastasia Stulova04307942018-11-16 16:22:56 +00004276 }
John McCalle3027922010-08-25 11:45:40 +00004277 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004278 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004279 Address V = Builder.CreateElementBitCast(LV.getAddress(),
4280 ConvertType(E->getType()));
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004281 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004282 CGM.getTBAAInfoForSubobject(LV, E->getType()));
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004283 }
Andrew Savonichevb555b762018-10-23 15:19:20 +00004284 case CK_ZeroToOCLOpaqueType:
4285 llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00004286 }
Craig Topper99e79272013-07-26 05:59:26 +00004287
Douglas Gregorcdb466e2010-07-15 18:58:16 +00004288 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00004289}
4290
John McCall1bf58462011-02-16 08:02:54 +00004291LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00004292 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
Akira Hatanaka797afe32018-03-20 01:47:58 +00004293 return getOrCreateOpaqueLValueMapping(e);
4294}
4295
4296LValue
4297CodeGenFunction::getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e) {
4298 assert(OpaqueValueMapping::shouldBindAsLValue(e));
4299
4300 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
4301 it = OpaqueLValues.find(e);
4302
4303 if (it != OpaqueLValues.end())
4304 return it->second;
4305
4306 assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
4307 return EmitLValue(e->getSourceExpr());
4308}
4309
4310RValue
4311CodeGenFunction::getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e) {
4312 assert(!OpaqueValueMapping::shouldBindAsLValue(e));
4313
4314 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
4315 it = OpaqueRValues.find(e);
4316
4317 if (it != OpaqueRValues.end())
4318 return it->second;
4319
4320 assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
4321 return EmitAnyExpr(e->getSourceExpr());
John McCall1bf58462011-02-16 08:02:54 +00004322}
4323
Eli Friedman7f1ff602012-04-16 03:54:45 +00004324RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004325 const FieldDecl *FD,
4326 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004327 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00004328 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00004329 switch (getEvaluationKind(FT)) {
4330 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004331 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00004332 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00004333 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00004334 case TEK_Scalar:
Reid Kleckner9d031092016-05-02 22:42:34 +00004335 // This routine is used to load fields one-by-one to perform a copy, so
4336 // don't load reference fields.
4337 if (FD->getType()->isReferenceType())
4338 return RValue::get(FieldLV.getPointer());
Nick Lewycky2d84e842013-10-02 02:29:49 +00004339 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00004340 }
4341 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004342}
Douglas Gregorfe314812011-06-21 17:03:29 +00004343
Chris Lattnere47e4402007-06-01 18:02:12 +00004344//===--------------------------------------------------------------------===//
4345// Expression Emission
4346//===--------------------------------------------------------------------===//
4347
Craig Topper99e79272013-07-26 05:59:26 +00004348RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00004349 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00004350 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00004351 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00004352 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00004353
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004354 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00004355 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00004356
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004357 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00004358 return EmitCUDAKernelCallExpr(CE, ReturnValue);
4359
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004360 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
John McCallb92ab1a2016-10-26 23:46:34 +00004361 if (const CXXMethodDecl *MD =
4362 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
Anders Carlssonbfb36712009-12-24 21:13:40 +00004363 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00004364
John McCallb92ab1a2016-10-26 23:46:34 +00004365 CGCallee callee = EmitCallee(E->getCallee());
Craig Topper99e79272013-07-26 05:59:26 +00004366
John McCallb92ab1a2016-10-26 23:46:34 +00004367 if (callee.isBuiltin()) {
4368 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
4369 E, ReturnValue);
Douglas Gregorad8a3362009-09-04 17:36:40 +00004370 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004371
John McCallb92ab1a2016-10-26 23:46:34 +00004372 if (callee.isPseudoDestructor()) {
4373 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
4374 }
4375
4376 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
4377}
4378
4379/// Emit a CallExpr without considering whether it might be a subclass.
4380RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
4381 ReturnValueSlot ReturnValue) {
4382 CGCallee Callee = EmitCallee(E->getCallee());
4383 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
4384}
4385
4386static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
4387 if (auto builtinID = FD->getBuiltinID()) {
4388 return CGCallee::forBuiltin(builtinID, FD);
4389 }
4390
4391 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
Erich Keanede6480a32018-11-13 15:48:08 +00004392 return CGCallee::forDirect(calleePtr, GlobalDecl(FD));
John McCallb92ab1a2016-10-26 23:46:34 +00004393}
4394
4395CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
4396 E = E->IgnoreParens();
4397
4398 // Look through function-to-pointer decay.
4399 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
4400 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
4401 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
4402 return EmitCallee(ICE->getSubExpr());
4403 }
4404
4405 // Resolve direct calls.
4406 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
4407 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
4408 return EmitDirectCallee(*this, FD);
4409 }
4410 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
4411 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
4412 EmitIgnoredExpr(ME->getBase());
4413 return EmitDirectCallee(*this, FD);
4414 }
4415
4416 // Look through template substitutions.
4417 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4418 return EmitCallee(NTTP->getReplacement());
4419
4420 // Treat pseudo-destructor calls differently.
4421 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4422 return CGCallee::forPseudoDestructor(PDE);
4423 }
4424
4425 // Otherwise, we have an indirect reference.
4426 llvm::Value *calleePtr;
4427 QualType functionType;
4428 if (auto ptrType = E->getType()->getAs<PointerType>()) {
4429 calleePtr = EmitScalarExpr(E);
4430 functionType = ptrType->getPointeeType();
4431 } else {
4432 functionType = E->getType();
4433 calleePtr = EmitLValue(E).getPointer();
4434 }
4435 assert(functionType->isFunctionType());
Erich Keanede6480a32018-11-13 15:48:08 +00004436
4437 GlobalDecl GD;
4438 if (const auto *VD =
4439 dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee()))
4440 GD = GlobalDecl(VD);
4441
4442 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD);
John McCallb92ab1a2016-10-26 23:46:34 +00004443 CGCallee callee(calleeInfo, calleePtr);
4444 return callee;
Chris Lattner9e47ead2007-08-31 04:44:06 +00004445}
4446
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004447LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00004448 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00004449 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00004450 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00004451 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00004452 return EmitLValue(E->getRHS());
4453 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004454
John McCalle3027922010-08-25 11:45:40 +00004455 if (E->getOpcode() == BO_PtrMemD ||
4456 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004457 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004458
John McCalla2342eb2010-12-05 02:00:02 +00004459 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00004460
4461 // Note that in all of these cases, __block variables need the RHS
4462 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00004463
4464 switch (getEvaluationKind(E->getType())) {
4465 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00004466 switch (E->getLHS()->getType().getObjCLifetime()) {
4467 case Qualifiers::OCL_Strong:
4468 return EmitARCStoreStrong(E, /*ignored*/ false).first;
4469
4470 case Qualifiers::OCL_Autoreleasing:
4471 return EmitARCStoreAutoreleasing(E).first;
4472
4473 // No reason to do any of these differently.
4474 case Qualifiers::OCL_None:
4475 case Qualifiers::OCL_ExplicitNone:
4476 case Qualifiers::OCL_Weak:
4477 break;
4478 }
4479
John McCalld0a30012010-12-06 06:10:02 +00004480 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00004481 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
Vedant Kumar6b22dda2017-04-26 21:55:17 +00004482 if (RV.isScalar())
4483 EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
John McCall55e1fbc2011-06-25 02:11:03 +00004484 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00004485 return LV;
4486 }
John McCall4f29b492010-11-16 23:07:28 +00004487
John McCall47fb9502013-03-07 21:37:08 +00004488 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00004489 return EmitComplexAssignmentLValue(E);
4490
John McCall47fb9502013-03-07 21:37:08 +00004491 case TEK_Aggregate:
4492 return EmitAggExprToLValue(E);
4493 }
4494 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004495}
4496
Christopher Lambd91c3d42007-12-29 05:02:41 +00004497LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00004498 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00004499
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004500 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004501 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004502 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00004503
David Majnemerced8bdf2015-02-25 17:36:15 +00004504 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004505 "Can't have a scalar return unless the return type is a "
4506 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00004507
John McCall7f416cc2015-09-08 08:05:57 +00004508 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00004509}
4510
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004511LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4512 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00004513 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004514}
4515
Anders Carlsson3be22e22009-05-30 23:23:33 +00004516LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004517 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
4518 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004519 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00004520 EmitCXXConstructExpr(E, Slot);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004521 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
Anders Carlsson3be22e22009-05-30 23:23:33 +00004522}
4523
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004524LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00004525CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004526 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00004527}
4528
John McCall7f416cc2015-09-08 08:05:57 +00004529Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
4530 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4531 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00004532}
4533
4534LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004535 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004536 AlignmentSource::Decl);
Nico Webercf4ff5862012-10-11 10:13:44 +00004537}
4538
Mike Stumpc9b231c2009-11-15 08:09:41 +00004539LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004540CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004541 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00004542 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00004543 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004544 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004545 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004546}
4547
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004548LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004549 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00004550
Anders Carlsson280e61f12010-06-21 20:59:55 +00004551 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004552 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004553 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00004554
Alp Toker314cc812014-01-25 16:55:45 +00004555 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00004556 "Can't have a scalar return unless the return type is a "
4557 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00004558
John McCall7f416cc2015-09-08 08:05:57 +00004559 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004560}
4561
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004562LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004563 Address V =
4564 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004565 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004566}
4567
Daniel Dunbar722f4242009-04-22 05:08:15 +00004568llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004569 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004570 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004571}
4572
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004573LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4574 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004575 const ObjCIvarDecl *Ivar,
4576 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00004577 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00004578 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004579}
4580
4581LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004582 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00004583 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004584 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00004585 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004586 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004587 if (E->isArrow()) {
4588 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004589 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00004590 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004591 } else {
4592 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00004593 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004594 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00004595 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004596 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004597
Craig Topper99e79272013-07-26 05:59:26 +00004598 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00004599 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4600 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00004601 setObjCGCLValueClass(getContext(), E, LV);
4602 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00004603}
4604
Chris Lattnera4185c52009-04-25 19:35:26 +00004605LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00004606 // Can only get l-value for message expression returning aggregate type
4607 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00004608 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004609 AlignmentSource::Decl);
Chris Lattnera4185c52009-04-25 19:35:26 +00004610}
4611
John McCallb92ab1a2016-10-26 23:46:34 +00004612RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004613 const CallExpr *E, ReturnValueSlot ReturnValue,
John McCallb92ab1a2016-10-26 23:46:34 +00004614 llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00004615 // Get the actual function type. The callee type will always be a pointer to
4616 // function type or a block pointer type.
4617 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00004618 "Call must have function pointer type!");
4619
Erich Keanede6480a32018-11-13 15:48:08 +00004620 const Decl *TargetDecl =
4621 OrigCallee.getAbstractInfo().getCalleeDecl().getDecl();
Samuel Antao798f11c2015-11-23 22:04:44 +00004622
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004623 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
Eric Christopher39db7262015-11-14 01:56:04 +00004624 // We can only guarantee that a function is called from the correct
4625 // context/function based on the appropriate target attributes,
4626 // so only check in the case where we have both always_inline and target
4627 // since otherwise we could be making a conditional call after a check for
4628 // the proper cpu features (and it won't cause code generation issues due to
4629 // function based code generation).
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004630 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4631 TargetDecl->hasAttr<TargetAttr>())
4632 checkTargetFeatures(E, FD);
4633
John McCall6fd4c232009-10-23 08:22:42 +00004634 CalleeType = getContext().getCanonicalType(CalleeType);
4635
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00004636 auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType();
Daniel Dunbarc722b852008-08-30 03:02:31 +00004637
John McCallb92ab1a2016-10-26 23:46:34 +00004638 CGCallee Callee = OrigCallee;
4639
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004640 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004641 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4642 if (llvm::Constant *PrefixSig =
4643 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00004644 SanitizerScope SanScope(this);
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00004645 // Remove any (C++17) exception specifications, to allow calling e.g. a
4646 // noexcept function through a non-noexcept pointer.
4647 auto ProtoTy =
4648 getContext().getFunctionTypeWithExceptionSpec(PointeeType, EST_None);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004649 llvm::Constant *FTRTTIConst =
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00004650 CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
Vedant Kumarbb5d4852017-09-13 00:04:35 +00004651 llvm::Type *PrefixStructTyElems[] = {PrefixSig->getType(), Int32Ty};
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004652 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4653 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4654
John McCallb92ab1a2016-10-26 23:46:34 +00004655 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4656
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004657 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
John McCallb92ab1a2016-10-26 23:46:34 +00004658 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004659 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004660 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00004661 llvm::Value *CalleeSig =
4662 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004663 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4664
4665 llvm::BasicBlock *Cont = createBasicBlock("cont");
4666 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4667 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4668
4669 EmitBlock(TypeCheck);
4670 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004671 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
Vedant Kumarbb5d4852017-09-13 00:04:35 +00004672 llvm::Value *CalleeRTTIEncoded =
John McCall7f416cc2015-09-08 08:05:57 +00004673 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Vedant Kumarbb5d4852017-09-13 00:04:35 +00004674 llvm::Value *CalleeRTTI =
4675 DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004676 llvm::Value *CalleeRTTIMatch =
4677 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004678 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()),
4679 EmitCheckTypeDescriptor(CalleeType)};
Alexey Samsonove396bfc2014-11-11 22:03:54 +00004680 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
Stephan Bergmann0c352eb2017-12-18 13:51:48 +00004681 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004682
4683 Builder.CreateBr(Cont);
4684 EmitBlock(Cont);
4685 }
4686 }
4687
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00004688 const auto *FnType = cast<FunctionType>(PointeeType);
4689
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004690 // If we are checking indirect calls and this call is indirect, check that the
4691 // function pointer is a member of the bit set for the function type.
4692 if (SanOpts.has(SanitizerKind::CFIICall) &&
4693 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4694 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00004695 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004696
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00004697 llvm::Metadata *MD;
4698 if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
4699 MD = CGM.CreateMetadataIdentifierGeneralized(QualType(FnType, 0));
4700 else
4701 MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
4702
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004703 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004704
John McCallb92ab1a2016-10-26 23:46:34 +00004705 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4706 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004707 llvm::Value *TypeTest = Builder.CreateCall(
4708 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004709
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004710 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004711 llvm::Constant *StaticData[] = {
4712 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004713 EmitCheckSourceLocation(E->getBeginLoc()),
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004714 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4715 };
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004716 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4717 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004718 CastedCallee, StaticData);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004719 } else {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004720 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004721 SanitizerHandler::CFICheckFail, StaticData,
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004722 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004723 }
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004724 }
4725
Daniel Dunbarc722b852008-08-30 03:02:31 +00004726 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00004727 if (Chain)
4728 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4729 CGM.getContext().VoidPtrTy);
Richard Smith762672a2016-09-28 19:09:10 +00004730
4731 // C++17 requires that we evaluate arguments to a call using assignment syntax
Richard Smitha560ccf2016-09-29 21:30:12 +00004732 // right-to-left, and that we evaluate arguments to certain other operators
4733 // left-to-right. Note that we allow this to override the order dictated by
4734 // the calling convention on the MS ABI, which means that parameter
4735 // destruction order is not necessarily reverse construction order.
4736 // FIXME: Revisit this based on C++ committee response to unimplementability.
4737 EvaluationOrder Order = EvaluationOrder::Default;
4738 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4739 if (OCE->isAssignmentOp())
4740 Order = EvaluationOrder::ForceRightToLeft;
4741 else {
4742 switch (OCE->getOperator()) {
4743 case OO_LessLess:
4744 case OO_GreaterGreater:
4745 case OO_AmpAmp:
4746 case OO_PipePipe:
4747 case OO_Comma:
4748 case OO_ArrowStar:
4749 Order = EvaluationOrder::ForceLeftToRight;
4750 break;
4751 default:
4752 break;
4753 }
4754 }
4755 }
Richard Smith762672a2016-09-28 19:09:10 +00004756
David Blaikief05779e2015-07-21 18:37:18 +00004757 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
Richard Smitha560ccf2016-09-29 21:30:12 +00004758 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
Daniel Dunbarc722b852008-08-30 03:02:31 +00004759
Peter Collingbournef7706832014-12-12 23:41:25 +00004760 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4761 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00004762
4763 // C99 6.5.2.2p6:
4764 // If the expression that denotes the called function has a type
4765 // that does not include a prototype, [the default argument
4766 // promotions are performed]. If the number of arguments does not
4767 // equal the number of parameters, the behavior is undefined. If
4768 // the function is defined with a type that includes a prototype,
4769 // and either the prototype ends with an ellipsis (, ...) or the
4770 // types of the arguments after promotion are not compatible with
4771 // the types of the parameters, the behavior is undefined. If the
4772 // function is defined with a type that does not include a
4773 // prototype, and the types of the arguments after promotion are
4774 // not compatible with those of the parameters after promotion,
4775 // the behavior is undefined [except in some trivial cases].
4776 // That is, in the general case, we should assume that a call
4777 // through an unprototyped function type works like a *non-variadic*
4778 // call. The way we make this work is to cast to the exact type
4779 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00004780 //
4781 // Chain calls use this same code path to add the invisible chain parameter
4782 // to the function type.
4783 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00004784 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00004785 CalleeTy = CalleeTy->getPointerTo();
John McCallb92ab1a2016-10-26 23:46:34 +00004786
4787 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4788 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4789 Callee.setFunctionPointer(CalleePtr);
John McCallcbc038a2011-09-21 08:08:30 +00004790 }
4791
Vedant Kumar09b5bfd2017-12-21 00:10:25 +00004792 return EmitCall(FnInfo, Callee, ReturnValue, Args, nullptr, E->getExprLoc());
Daniel Dunbar97db84c2008-08-23 03:46:30 +00004793}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004794
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004795LValue CodeGenFunction::
4796EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004797 Address BaseAddr = Address::invalid();
4798 if (E->getOpcode() == BO_PtrMemI) {
4799 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4800 } else {
4801 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4802 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004803
John McCallc134eb52010-08-31 21:07:20 +00004804 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4805
4806 const MemberPointerType *MPT
4807 = E->getRHS()->getType()->getAs<MemberPointerType>();
4808
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004809 LValueBaseInfo BaseInfo;
Ivan A. Kosarev229a6d82017-10-13 16:38:32 +00004810 TBAAAccessInfo TBAAInfo;
John McCall7f416cc2015-09-08 08:05:57 +00004811 Address MemberAddr =
Ivan A. Kosarev229a6d82017-10-13 16:38:32 +00004812 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo,
4813 &TBAAInfo);
John McCallc134eb52010-08-31 21:07:20 +00004814
Ivan A. Kosarev229a6d82017-10-13 16:38:32 +00004815 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004816}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004817
John McCall47fb9502013-03-07 21:37:08 +00004818/// Given the address of a temporary variable, produce an r-value of
4819/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00004820RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004821 QualType type,
4822 SourceLocation loc) {
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004823 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
John McCall47fb9502013-03-07 21:37:08 +00004824 switch (getEvaluationKind(type)) {
4825 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004826 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004827 case TEK_Aggregate:
4828 return lvalue.asAggregateRValue();
4829 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004830 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004831 }
4832 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004833}
4834
Duncan Sandse81111c2012-04-10 08:23:07 +00004835void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004836 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00004837 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004838 return;
4839
Duncan Sands65229ed2012-04-16 16:29:47 +00004840 llvm::MDBuilder MDHelper(getLLVMContext());
4841 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004842
Duncan Sands6fc46192012-04-14 12:37:26 +00004843 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004844}
John McCallfe96e0b2011-11-06 09:01:30 +00004845
4846namespace {
4847 struct LValueOrRValue {
4848 LValue LV;
4849 RValue RV;
4850 };
4851}
4852
4853static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4854 const PseudoObjectExpr *E,
4855 bool forLValue,
4856 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004857 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00004858
4859 // Find the result expression, if any.
4860 const Expr *resultExpr = E->getResultExpr();
4861 LValueOrRValue result;
4862
4863 for (PseudoObjectExpr::const_semantics_iterator
4864 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4865 const Expr *semantic = *i;
4866
4867 // If this semantic expression is an opaque value, bind it
4868 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004869 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
Akira Hatanaka797afe32018-03-20 01:47:58 +00004870 // Skip unique OVEs.
4871 if (ov->isUnique()) {
4872 assert(ov != resultExpr &&
4873 "A unique OVE cannot be used as the result expression");
4874 continue;
4875 }
John McCallfe96e0b2011-11-06 09:01:30 +00004876
4877 // If this is the result expression, we may need to evaluate
4878 // directly into the slot.
4879 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4880 OVMA opaqueData;
4881 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00004882 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00004883 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
John McCall7f416cc2015-09-08 08:05:57 +00004884 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004885 AlignmentSource::Decl);
John McCallfe96e0b2011-11-06 09:01:30 +00004886 opaqueData = OVMA::bind(CGF, ov, LV);
4887 result.RV = slot.asRValue();
4888
4889 // Otherwise, emit as normal.
4890 } else {
4891 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4892
4893 // If this is the result, also evaluate the result now.
4894 if (ov == resultExpr) {
4895 if (forLValue)
4896 result.LV = CGF.EmitLValue(ov);
4897 else
4898 result.RV = CGF.EmitAnyExpr(ov, slot);
4899 }
4900 }
4901
4902 opaques.push_back(opaqueData);
4903
4904 // Otherwise, if the expression is the result, evaluate it
4905 // and remember the result.
4906 } else if (semantic == resultExpr) {
4907 if (forLValue)
4908 result.LV = CGF.EmitLValue(semantic);
4909 else
4910 result.RV = CGF.EmitAnyExpr(semantic, slot);
4911
4912 // Otherwise, evaluate the expression in an ignored context.
4913 } else {
4914 CGF.EmitIgnoredExpr(semantic);
4915 }
4916 }
4917
4918 // Unbind all the opaques now.
4919 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4920 opaques[i].unbind(CGF);
4921
4922 return result;
4923}
4924
4925RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4926 AggValueSlot slot) {
4927 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4928}
4929
4930LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4931 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4932}