blob: b53b77a819b49284e3bc05ac2c8911e6ef884468 [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"
Yonghong Song048493f2019-07-09 04:21:50 +000028#include "clang/Basic/Builtins.h"
Richard Trieu63688182018-12-11 03:18:39 +000029#include "clang/Basic/CodeGenOptions.h"
Reid Kleckner86565c12020-02-27 11:01:58 -080030#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "llvm/ADT/Hashing.h"
Alexey Bataevec474782014-10-09 08:45:04 +000032#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/LLVMContext.h"
36#include "llvm/IR/MDBuilder.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000037#include "llvm/Support/ConvertUTF.h"
Peter Collingbourne3eea6772015-05-11 21:39:14 +000038#include "llvm/Support/MathExtras.h"
Filipe Cabecinhasab731f72016-05-12 16:51:36 +000039#include "llvm/Support/Path.h"
Peter Collingbournedc134532016-01-16 00:31:22 +000040#include "llvm/Transforms/Utils/SanitizerStats.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000041
Filipe Cabecinhas84171bd2016-12-12 16:43:40 +000042#include <string>
43
Chris Lattnere47e4402007-06-01 18:02:12 +000044using namespace clang;
45using namespace CodeGen;
46
Chris Lattnerd7f58862007-06-02 05:24:33 +000047//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000048// Miscellaneous Helper Methods
49//===--------------------------------------------------------------------===//
50
John McCallad7c5c12011-02-08 08:22:06 +000051llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
52 unsigned addressSpace =
Yaxun Liu39195062017-08-04 18:16:31 +000053 cast<llvm::PointerType>(value->getType())->getAddressSpace();
John McCallad7c5c12011-02-08 08:22:06 +000054
Chris Lattner2192fe52011-07-18 04:24:23 +000055 llvm::PointerType *destType = Int8PtrTy;
John McCallad7c5c12011-02-08 08:22:06 +000056 if (addressSpace)
57 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
58
59 if (value->getType() == destType) return value;
60 return Builder.CreateBitCast(value, destType);
61}
62
Chris Lattnere9a64532007-06-22 21:44:33 +000063/// CreateTempAlloca - This creates a alloca and inserts it into the entry
64/// block.
Yaxun Liuaefdb8e2018-06-15 15:33:22 +000065Address CodeGenFunction::CreateTempAllocaWithoutCast(llvm::Type *Ty,
66 CharUnits Align,
67 const Twine &Name,
68 llvm::Value *ArraySize) {
69 auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
Guillaume Chateletc79099e2019-10-03 13:00:29 +000070 Alloca->setAlignment(Align.getAsAlign());
Yaxun Liuaefdb8e2018-06-15 15:33:22 +000071 return Address(Alloca, Align);
72}
73
74/// CreateTempAlloca - This creates a alloca and inserts it into the entry
75/// block. The alloca is casted to default address space if necessary.
John McCall7f416cc2015-09-08 08:05:57 +000076Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
Yaxun Liu84744c12017-06-19 17:03:41 +000077 const Twine &Name,
78 llvm::Value *ArraySize,
Yaxun Liuaefdb8e2018-06-15 15:33:22 +000079 Address *AllocaAddr) {
80 auto Alloca = CreateTempAllocaWithoutCast(Ty, Align, Name, ArraySize);
Yaxun Liua2a9cfa2018-05-17 11:16:35 +000081 if (AllocaAddr)
Yaxun Liuaefdb8e2018-06-15 15:33:22 +000082 *AllocaAddr = Alloca;
83 llvm::Value *V = Alloca.getPointer();
Yaxun Liu84744c12017-06-19 17:03:41 +000084 // Alloca always returns a pointer in alloca address space, which may
85 // be different from the type defined by the language. For example,
86 // in C++ the auto variables are in the default address space. Therefore
87 // cast alloca to the default address space when necessary.
Yaxun Liuaefdb8e2018-06-15 15:33:22 +000088 if (getASTAllocaAddressSpace() != LangAS::Default) {
Yaxun Liu84744c12017-06-19 17:03:41 +000089 auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
Yaxun Liue45b3d52017-10-24 19:14:43 +000090 llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
Yaxun Liu561ac062017-10-30 14:38:30 +000091 // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
92 // otherwise alloca is inserted at the current insertion point of the
93 // builder.
94 if (!ArraySize)
95 Builder.SetInsertPoint(AllocaInsertPt);
Yaxun Liu84744c12017-06-19 17:03:41 +000096 V = getTargetHooks().performAddrSpaceCast(
97 *this, V, getASTAllocaAddressSpace(), LangAS::Default,
98 Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
99 }
100
101 return Address(V, Align);
John McCall7f416cc2015-09-08 08:05:57 +0000102}
103
Yaxun Liu84744c12017-06-19 17:03:41 +0000104/// CreateTempAlloca - This creates an alloca and inserts it into the entry
105/// block if \p ArraySize is nullptr, otherwise inserts it at the current
106/// insertion point of the builder.
Chris Lattner2192fe52011-07-18 04:24:23 +0000107llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Yaxun Liu84744c12017-06-19 17:03:41 +0000108 const Twine &Name,
109 llvm::Value *ArraySize) {
110 if (ArraySize)
111 return Builder.CreateAlloca(Ty, ArraySize, Name);
Matt Arsenault502ad602017-04-10 22:28:02 +0000112 return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
Yaxun Liu84744c12017-06-19 17:03:41 +0000113 ArraySize, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +0000114}
Chris Lattner8394d792007-06-05 20:53:16 +0000115
John McCall7f416cc2015-09-08 08:05:57 +0000116/// CreateDefaultAlignTempAlloca - This creates an alloca with the
117/// default alignment of the corresponding LLVM type, which is *not*
118/// guaranteed to be related in any way to the expected alignment of
119/// an AST type that might have been lowered to Ty.
120Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
121 const Twine &Name) {
122 CharUnits Align =
123 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
124 return CreateTempAlloca(Ty, Align, Name);
125}
126
127void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
128 assert(isa<llvm::AllocaInst>(Var.getPointer()));
129 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
Guillaume Chateletc79099e2019-10-03 13:00:29 +0000130 Store->setAlignment(Var.getAlignment().getAsAlign());
John McCall2e6567a2010-04-22 01:10:34 +0000131 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000132 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
John McCall2e6567a2010-04-22 01:10:34 +0000133}
134
John McCall7f416cc2015-09-08 08:05:57 +0000135Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +0000136 CharUnits Align = getContext().getTypeAlignInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +0000137 return CreateTempAlloca(ConvertType(Ty), Align, Name);
Daniel Dunbard0049182010-02-16 19:44:13 +0000138}
139
Yaxun Liu84744c12017-06-19 17:03:41 +0000140Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
Yaxun Liuaefdb8e2018-06-15 15:33:22 +0000141 Address *Alloca) {
Daniel Dunbara7566f12010-02-09 02:48:28 +0000142 // FIXME: Should we prefer the preferred type alignment here?
Yaxun Liuaefdb8e2018-06-15 15:33:22 +0000143 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name, Alloca);
John McCall7f416cc2015-09-08 08:05:57 +0000144}
145
146Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
Yaxun Liuaefdb8e2018-06-15 15:33:22 +0000147 const Twine &Name, Address *Alloca) {
Yaxun Liua2a9cfa2018-05-17 11:16:35 +0000148 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name,
Yaxun Liuaefdb8e2018-06-15 15:33:22 +0000149 /*ArraySize=*/nullptr, Alloca);
150}
151
152Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty, CharUnits Align,
153 const Twine &Name) {
154 return CreateTempAllocaWithoutCast(ConvertTypeForMem(Ty), Align, Name);
155}
156
157Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty,
158 const Twine &Name) {
159 return CreateMemTempWithoutCast(Ty, getContext().getTypeAlignInChars(Ty),
160 Name);
Daniel Dunbara7566f12010-02-09 02:48:28 +0000161}
162
Chris Lattner8394d792007-06-05 20:53:16 +0000163/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
164/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000165llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000166 PGO.setCurrentStmt(E);
John McCall7a9aac22010-08-23 01:21:21 +0000167 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +0000168 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +0000169 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +0000170 }
John McCall7a9aac22010-08-23 01:21:21 +0000171
172 QualType BoolTy = getContext().BoolTy;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000173 SourceLocation Loc = E->getExprLoc();
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000174 if (!E->getType()->isAnyComplexType())
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000175 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +0000176
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000177 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
178 Loc);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000179}
180
John McCalla2342eb2010-12-05 02:00:02 +0000181/// EmitIgnoredExpr - Emit code to compute the specified expression,
182/// ignoring the result.
183void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
184 if (E->isRValue())
185 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
186
187 // Just emit it as an l-value and drop the result.
188 EmitLValue(E);
189}
190
John McCall7a626f62010-09-15 10:14:12 +0000191/// EmitAnyExpr - Emit code to compute the specified expression which
192/// can have any type. The result is returned as an RValue struct.
193/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000194/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000195RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
196 AggValueSlot aggSlot,
197 bool ignoreResult) {
John McCall47fb9502013-03-07 21:37:08 +0000198 switch (getEvaluationKind(E->getType())) {
199 case TEK_Scalar:
John McCall4e8ca4f2012-07-02 23:58:38 +0000200 return RValue::get(EmitScalarExpr(E, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000201 case TEK_Complex:
John McCall4e8ca4f2012-07-02 23:58:38 +0000202 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000203 case TEK_Aggregate:
204 if (!ignoreResult && aggSlot.isIgnored())
205 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
206 EmitAggExpr(E, aggSlot);
207 return aggSlot.asRValue();
208 }
209 llvm_unreachable("bad evaluation kind");
Chris Lattner4647a212007-08-31 22:49:20 +0000210}
211
George Burgess IVab1e5a12018-03-08 00:22:04 +0000212/// EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will
Mike Stump4a3999f2009-09-09 13:00:44 +0000213/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000214RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
215 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000216
John McCall47fb9502013-03-07 21:37:08 +0000217 if (hasAggregateEvaluationKind(E->getType()))
John McCall7a626f62010-09-15 10:14:12 +0000218 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
219 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000220}
221
John McCall21886962010-04-21 10:05:39 +0000222/// EmitAnyExprToMem - Evaluate an expression into a given memory
223/// location.
224void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000225 Address Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000226 Qualifiers Quals,
227 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000228 // FIXME: This function should take an LValue as an argument.
John McCall47fb9502013-03-07 21:37:08 +0000229 switch (getEvaluationKind(E->getType())) {
230 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000231 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
John McCall47fb9502013-03-07 21:37:08 +0000232 /*isInit*/ false);
233 return;
234
235 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000236 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000237 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000238 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +0000239 AggValueSlot::IsAliased_t(!IsInit),
240 AggValueSlot::MayOverlap));
John McCall47fb9502013-03-07 21:37:08 +0000241 return;
242 }
243
244 case TEK_Scalar: {
John McCall21886962010-04-21 10:05:39 +0000245 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000246 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000247 EmitStoreThroughLValue(RV, LV);
John McCall47fb9502013-03-07 21:37:08 +0000248 return;
John McCall21886962010-04-21 10:05:39 +0000249 }
John McCall47fb9502013-03-07 21:37:08 +0000250 }
251 llvm_unreachable("bad evaluation kind");
John McCall21886962010-04-21 10:05:39 +0000252}
253
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000254static void
255pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
John McCall7f416cc2015-09-08 08:05:57 +0000256 const Expr *E, Address ReferenceTemporary) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000257 // Objective-C++ ARC:
258 // If we are binding a reference to a temporary that has ownership, we
259 // need to perform retain/release operations on the temporary.
Richard Smith736a9472013-06-12 20:42:33 +0000260 //
261 // FIXME: This should be looking at E, not M.
John McCall460ce582015-10-22 18:38:17 +0000262 if (auto Lifetime = M->getType().getObjCLifetime()) {
263 switch (Lifetime) {
Richard Smith736a9472013-06-12 20:42:33 +0000264 case Qualifiers::OCL_None:
265 case Qualifiers::OCL_ExplicitNone:
266 // Carry on to normal cleanup handling.
267 break;
Sebastian Redl29526f02011-11-27 16:50:07 +0000268
Richard Smith736a9472013-06-12 20:42:33 +0000269 case Qualifiers::OCL_Autoreleasing:
270 // Nothing to do; cleaned up by an autorelease pool.
271 return;
272
273 case Qualifiers::OCL_Strong:
274 case Qualifiers::OCL_Weak:
275 switch (StorageDuration Duration = M->getStorageDuration()) {
276 case SD_Static:
277 // Note: we intentionally do not register a cleanup to release
278 // the object on program termination.
279 return;
280
281 case SD_Thread:
282 // FIXME: We should probably register a cleanup in this case.
283 return;
284
285 case SD_Automatic:
286 case SD_FullExpression:
Richard Smith736a9472013-06-12 20:42:33 +0000287 CodeGenFunction::Destroyer *Destroy;
288 CleanupKind CleanupKind;
289 if (Lifetime == Qualifiers::OCL_Strong) {
290 const ValueDecl *VD = M->getExtendingDecl();
291 bool Precise =
292 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
293 CleanupKind = CGF.getARCCleanupKind();
294 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
295 : &CodeGenFunction::destroyARCStrongImprecise;
296 } else {
297 // __weak objects always get EH cleanups; otherwise, exceptions
298 // could cause really nasty crashes instead of mere leaks.
299 CleanupKind = NormalAndEHCleanup;
300 Destroy = &CodeGenFunction::destroyARCWeak;
301 }
302 if (Duration == SD_FullExpression)
303 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000304 M->getType(), *Destroy,
Richard Smith736a9472013-06-12 20:42:33 +0000305 CleanupKind & EHCleanup);
306 else
307 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000308 M->getType(),
Richard Smith736a9472013-06-12 20:42:33 +0000309 *Destroy, CleanupKind & EHCleanup);
310 return;
311
312 case SD_Dynamic:
313 llvm_unreachable("temporary cannot have dynamic storage duration");
314 }
315 llvm_unreachable("unknown storage duration");
316 }
317 }
318
Craig Topper8a13c412014-05-21 05:09:00 +0000319 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
Richard Smith736a9472013-06-12 20:42:33 +0000320 if (const RecordType *RT =
321 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
322 // Get the destructor for the reference temporary.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000323 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith736a9472013-06-12 20:42:33 +0000324 if (!ClassDecl->hasTrivialDestructor())
325 ReferenceTemporaryDtor = ClassDecl->getDestructor();
326 }
327
328 if (!ReferenceTemporaryDtor)
329 return;
330
331 // Call the destructor for the temporary.
332 switch (M->getStorageDuration()) {
333 case SD_Static:
334 case SD_Thread: {
James Y Knightf7321542019-02-07 01:14:17 +0000335 llvm::FunctionCallee CleanupFn;
Richard Smith736a9472013-06-12 20:42:33 +0000336 llvm::Constant *CleanupArg;
337 if (E->getType()->isArrayType()) {
338 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
John McCall7f416cc2015-09-08 08:05:57 +0000339 ReferenceTemporary, E->getType(),
David Blaikieebe87e12013-08-27 23:57:18 +0000340 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
341 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
Richard Smith736a9472013-06-12 20:42:33 +0000342 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
343 } else {
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000344 CleanupFn = CGF.CGM.getAddrAndTypeOfCXXStructor(
345 GlobalDecl(ReferenceTemporaryDtor, Dtor_Complete));
John McCall7f416cc2015-09-08 08:05:57 +0000346 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
Richard Smith736a9472013-06-12 20:42:33 +0000347 }
348 CGF.CGM.getCXXABI().registerGlobalDtor(
349 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
350 break;
351 }
352
353 case SD_FullExpression:
354 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
355 CodeGenFunction::destroyCXXObject,
356 CGF.getLangOpts().Exceptions);
357 break;
358
359 case SD_Automatic:
360 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
361 ReferenceTemporary, E->getType(),
362 CodeGenFunction::destroyCXXObject,
363 CGF.getLangOpts().Exceptions);
364 break;
365
366 case SD_Dynamic:
367 llvm_unreachable("temporary cannot have dynamic storage duration");
368 }
369}
370
Yaxun Liucbf647c2017-07-08 13:24:52 +0000371static Address createReferenceTemporary(CodeGenFunction &CGF,
372 const MaterializeTemporaryExpr *M,
Yaxun Liua2a9cfa2018-05-17 11:16:35 +0000373 const Expr *Inner,
374 Address *Alloca = nullptr) {
Yaxun Liucbf647c2017-07-08 13:24:52 +0000375 auto &TCG = CGF.getTargetHooks();
Richard Smith736a9472013-06-12 20:42:33 +0000376 switch (M->getStorageDuration()) {
377 case SD_FullExpression:
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000378 case SD_Automatic: {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000379 // If we have a constant temporary array or record try to promote it into a
380 // constant global under the same rules a normal constant would've been
381 // promoted. This is easier on the optimizer and generally emits fewer
382 // instructions.
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000383 QualType Ty = Inner->getType();
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000384 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000385 (Ty->isArrayType() || Ty->isRecordType()) &&
386 CGF.CGM.isTypeConstant(Ty, true))
John McCallde0fe072017-08-15 21:42:52 +0000387 if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
Yaxun Liucbf647c2017-07-08 13:24:52 +0000388 if (auto AddrSpace = CGF.getTarget().getConstantAddressSpace()) {
389 auto AS = AddrSpace.getValue();
390 auto *GV = new llvm::GlobalVariable(
391 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
392 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
393 llvm::GlobalValue::NotThreadLocal,
394 CGF.getContext().getTargetAddressSpace(AS));
395 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
Guillaume Chateletc79099e2019-10-03 13:00:29 +0000396 GV->setAlignment(alignment.getAsAlign());
Yaxun Liucbf647c2017-07-08 13:24:52 +0000397 llvm::Constant *C = GV;
398 if (AS != LangAS::Default)
399 C = TCG.performAddrSpaceCast(
400 CGF.CGM, GV, AS, LangAS::Default,
401 GV->getValueType()->getPointerTo(
402 CGF.getContext().getTargetAddressSpace(LangAS::Default)));
403 // FIXME: Should we put the new global into a COMDAT?
404 return Address(C, alignment);
405 }
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000406 }
Yaxun Liua2a9cfa2018-05-17 11:16:35 +0000407 return CGF.CreateMemTemp(Ty, "ref.tmp", Alloca);
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000408 }
Richard Smith736a9472013-06-12 20:42:33 +0000409 case SD_Thread:
410 case SD_Static:
Hans Wennborgf9d865b2015-03-17 16:38:58 +0000411 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
Richard Smith736a9472013-06-12 20:42:33 +0000412
413 case SD_Dynamic:
414 llvm_unreachable("temporary can't have dynamic storage duration");
415 }
416 llvm_unreachable("unknown storage duration");
417}
418
Diogo Sampaio9d869182020-02-07 10:03:59 +0000419/// Helper method to check if the underlying ABI is AAPCS
420static bool isAAPCS(const TargetInfo &TargetInfo) {
421 return TargetInfo.getABI().startswith("aapcs");
422}
423
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000424LValue CodeGenFunction::
425EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
Tykerb0561b32019-11-17 11:41:55 +0100426 const Expr *E = M->getSubExpr();
Richard Smith7c5d4dc2013-06-11 02:41:00 +0000427
Erik Pilkington1e368822019-01-04 18:33:06 +0000428 assert((!M->getExtendingDecl() || !isa<VarDecl>(M->getExtendingDecl()) ||
429 !cast<VarDecl>(M->getExtendingDecl())->isARCPseudoStrong()) &&
430 "Reference should never be pseudo-strong!");
431
432 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
433 // as that will cause the lifetime adjustment to be lost for ARC
John McCall460ce582015-10-22 18:38:17 +0000434 auto ownership = M->getType().getObjCLifetime();
435 if (ownership != Qualifiers::OCL_None &&
436 ownership != Qualifiers::OCL_ExplicitNone) {
John McCall7f416cc2015-09-08 08:05:57 +0000437 Address Object = createReferenceTemporary(*this, M, E);
438 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
439 Object = Address(llvm::ConstantExpr::getBitCast(Var,
440 ConvertTypeForMem(E->getType())
441 ->getPointerTo(Object.getAddressSpace())),
442 Object.getAlignment());
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000443
444 // createReferenceTemporary will promote the temporary to a global with a
445 // constant initializer if it can. It can only do this to a value of
446 // ARC-manageable type if the value is global and therefore "immune" to
447 // ref-counting operations. Therefore we have no need to emit either a
448 // dynamic initialization or a cleanup and we can just return the address
449 // of the temporary.
450 if (Var->hasInitializer())
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000451 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000452
Richard Smitha509f2f2013-06-14 03:07:01 +0000453 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
454 }
John McCall7f416cc2015-09-08 08:05:57 +0000455 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000456 AlignmentSource::Decl);
Richard Smitha509f2f2013-06-14 03:07:01 +0000457
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000458 switch (getEvaluationKind(E->getType())) {
459 default: llvm_unreachable("expected scalar or aggregate expression");
460 case TEK_Scalar:
461 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
462 break;
463 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000464 EmitAggExpr(E, AggValueSlot::forAddr(Object,
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000465 E->getType().getQualifiers(),
466 AggValueSlot::IsDestructed,
467 AggValueSlot::DoesNotNeedGCBarriers,
Richard Smithe78fac52018-04-05 20:52:58 +0000468 AggValueSlot::IsNotAliased,
469 AggValueSlot::DoesNotOverlap));
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000470 break;
471 }
472 }
Richard Smith736a9472013-06-12 20:42:33 +0000473
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000474 pushTemporaryCleanup(*this, M, E, Object);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000475 return RefTempDst;
Jordan Roseb1312a52013-04-11 00:58:58 +0000476 }
477
Richard Smithf3fabd22013-06-03 00:17:11 +0000478 SmallVector<const Expr *, 2> CommaLHSs;
Jordan Roseb1312a52013-04-11 00:58:58 +0000479 SmallVector<SubobjectAdjustment, 2> Adjustments;
Richard Smithf3fabd22013-06-03 00:17:11 +0000480 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
481
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000482 for (const auto &Ignored : CommaLHSs)
483 EmitIgnoredExpr(Ignored);
Richard Smithf3fabd22013-06-03 00:17:11 +0000484
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000485 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
Richard Smith736a9472013-06-12 20:42:33 +0000486 if (opaque->getType()->isRecordType()) {
487 assert(Adjustments.empty());
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000488 return EmitOpaqueValueLValue(opaque);
Jordan Roseb1312a52013-04-11 00:58:58 +0000489 }
490 }
491
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000492 // Create and initialize the reference temporary.
Yaxun Liua2a9cfa2018-05-17 11:16:35 +0000493 Address Alloca = Address::invalid();
494 Address Object = createReferenceTemporary(*this, M, E, &Alloca);
Yaxun Liucbf647c2017-07-08 13:24:52 +0000495 if (auto *Var = dyn_cast<llvm::GlobalVariable>(
496 Object.getPointer()->stripPointerCasts())) {
John McCall7f416cc2015-09-08 08:05:57 +0000497 Object = Address(llvm::ConstantExpr::getBitCast(
Yaxun Liucbf647c2017-07-08 13:24:52 +0000498 cast<llvm::Constant>(Object.getPointer()),
499 ConvertTypeForMem(E->getType())->getPointerTo()),
John McCall7f416cc2015-09-08 08:05:57 +0000500 Object.getAlignment());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000501 // If the temporary is a global and has a constant initializer or is a
502 // constant temporary that we promoted to a global, we may have already
503 // initialized it.
Richard Smitha509f2f2013-06-14 03:07:01 +0000504 if (!Var->hasInitializer()) {
505 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
506 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
507 }
508 } else {
Tim Shen421119f2016-07-01 21:08:47 +0000509 switch (M->getStorageDuration()) {
510 case SD_Automatic:
Tim Shen421119f2016-07-01 21:08:47 +0000511 if (auto *Size = EmitLifetimeStart(
Yaxun Liua2a9cfa2018-05-17 11:16:35 +0000512 CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
513 Alloca.getPointer())) {
Richard Smithaa140bf2018-08-04 01:25:06 +0000514 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
515 Alloca, Size);
Tim Shen421119f2016-07-01 21:08:47 +0000516 }
517 break;
Richard Smithaa140bf2018-08-04 01:25:06 +0000518
519 case SD_FullExpression: {
520 if (!ShouldEmitLifetimeMarkers)
521 break;
522
523 // Avoid creating a conditional cleanup just to hold an llvm.lifetime.end
524 // marker. Instead, start the lifetime of a conditional temporary earlier
Vitaly Bukaaeca5692019-08-26 22:15:50 +0000525 // so that it's unconditional. Don't do this with sanitizers which need
526 // more precise lifetime marks.
Richard Smithaa140bf2018-08-04 01:25:06 +0000527 ConditionalEvaluation *OldConditional = nullptr;
528 CGBuilderTy::InsertPoint OldIP;
529 if (isInConditionalBranch() && !E->getType().isDestructedType() &&
Vitaly Buka669d1112019-08-26 22:16:05 +0000530 !SanOpts.has(SanitizerKind::HWAddress) &&
Vitaly Bukaaeca5692019-08-26 22:15:50 +0000531 !SanOpts.has(SanitizerKind::Memory) &&
Richard Smithaa140bf2018-08-04 01:25:06 +0000532 !CGM.getCodeGenOpts().SanitizeAddressUseAfterScope) {
533 OldConditional = OutermostConditional;
534 OutermostConditional = nullptr;
535
536 OldIP = Builder.saveIP();
537 llvm::BasicBlock *Block = OldConditional->getStartingBlock();
538 Builder.restoreIP(CGBuilderTy::InsertPoint(
539 Block, llvm::BasicBlock::iterator(Block->back())));
540 }
541
542 if (auto *Size = EmitLifetimeStart(
543 CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
544 Alloca.getPointer())) {
545 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Alloca,
546 Size);
547 }
548
549 if (OldConditional) {
550 OutermostConditional = OldConditional;
551 Builder.restoreIP(OldIP);
552 }
553 break;
554 }
555
Tim Shen421119f2016-07-01 21:08:47 +0000556 default:
557 break;
558 }
Richard Smitha509f2f2013-06-14 03:07:01 +0000559 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
560 }
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000561 pushTemporaryCleanup(*this, M, E, Object);
Jordan Roseb1312a52013-04-11 00:58:58 +0000562
Richard Smith736a9472013-06-12 20:42:33 +0000563 // Perform derived-to-base casts and/or field accesses, to get from the
564 // temporary object we created (and, potentially, for which we extended
565 // the lifetime) to the subobject we're binding the reference to.
566 for (unsigned I = Adjustments.size(); I != 0; --I) {
567 SubobjectAdjustment &Adjustment = Adjustments[I-1];
568 switch (Adjustment.Kind) {
569 case SubobjectAdjustment::DerivedToBaseAdjustment:
570 Object =
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000571 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
572 Adjustment.DerivedToBase.BasePath->path_begin(),
573 Adjustment.DerivedToBase.BasePath->path_end(),
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000574 /*NullCheckValue=*/ false, E->getExprLoc());
Richard Smith736a9472013-06-12 20:42:33 +0000575 break;
Richard Smithf3fabd22013-06-03 00:17:11 +0000576
Richard Smith736a9472013-06-12 20:42:33 +0000577 case SubobjectAdjustment::FieldAdjustment: {
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000578 LValue LV = MakeAddrLValue(Object, E->getType(), AlignmentSource::Decl);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000579 LV = EmitLValueForField(LV, Adjustment.Field);
Richard Smith736a9472013-06-12 20:42:33 +0000580 assert(LV.isSimple() &&
581 "materialized temporary field is not a simple lvalue");
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800582 Object = LV.getAddress(*this);
Richard Smith736a9472013-06-12 20:42:33 +0000583 break;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000584 }
585
Richard Smith736a9472013-06-12 20:42:33 +0000586 case SubobjectAdjustment::MemberPointerAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000587 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
John McCall7f416cc2015-09-08 08:05:57 +0000588 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
589 Adjustment.Ptr.MPT);
Richard Smith736a9472013-06-12 20:42:33 +0000590 break;
591 }
592 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000593 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000594
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +0000595 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000596}
597
598RValue
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000599CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
600 // Emit the expression as an lvalue.
601 LValue LV = EmitLValue(E);
602 assert(LV.isSimple());
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800603 llvm::Value *Value = LV.getPointer(*this);
Richard Smith736a9472013-06-12 20:42:33 +0000604
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000605 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000606 // C++11 [dcl.ref]p5 (as amended by core issue 453):
607 // If a glvalue to which a reference is directly bound designates neither
608 // an existing object or function of an appropriate type nor a region of
609 // storage of suitable size and alignment to contain an object of the
610 // reference's type, the behavior is undefined.
611 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000612 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000613 }
John McCall8680f872010-07-21 06:29:51 +0000614
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000615 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000616}
617
618
Mike Stump4a3999f2009-09-09 13:00:44 +0000619/// getAccessedFieldNo - Given an encoded value and a result number, return the
620/// input field number being accessed.
621unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000622 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000623 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
624 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000625}
626
Richard Smith4d3110a2012-10-25 02:14:12 +0000627/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
628static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
629 llvm::Value *High) {
630 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
631 llvm::Value *K47 = Builder.getInt64(47);
632 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
633 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
634 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
635 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
636 return Builder.CreateMul(B1, KMul);
637}
638
Vedant Kumar24792e32017-10-03 01:27:25 +0000639bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) {
640 return TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
Stephan Bergmannd71ad172017-12-28 12:45:41 +0000641 TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation;
Vedant Kumar24792e32017-10-03 01:27:25 +0000642}
643
644bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) {
645 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
646 return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
647 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
648 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
Stephan Bergmannd71ad172017-12-28 12:45:41 +0000649 TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation);
Vedant Kumar24792e32017-10-03 01:27:25 +0000650}
651
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000652bool CodeGenFunction::sanitizePerformTypeCheck() const {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000653 return SanOpts.has(SanitizerKind::Null) |
654 SanOpts.has(SanitizerKind::Alignment) |
655 SanOpts.has(SanitizerKind::ObjectSize) |
656 SanOpts.has(SanitizerKind::Vptr);
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000657}
658
Richard Smithe30752c2012-10-09 19:52:38 +0000659void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +0000660 llvm::Value *Ptr, QualType Ty,
Vedant Kumar18348ea2017-02-17 23:22:55 +0000661 CharUnits Alignment,
Richard Smithcfa79b22019-01-23 03:37:29 +0000662 SanitizerSet SkippedChecks,
663 llvm::Value *ArraySize) {
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000664 if (!sanitizePerformTypeCheck())
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000665 return;
666
Richard Smith2d8b2942012-11-01 07:22:08 +0000667 // Don't check pointers outside the default address space. The null check
668 // isn't correct, the object-size check isn't supported by LLVM, and we can't
669 // communicate the addresses to the runtime handler for the vptr check.
John McCall7f416cc2015-09-08 08:05:57 +0000670 if (Ptr->getType()->getPointerAddressSpace())
Richard Smith2d8b2942012-11-01 07:22:08 +0000671 return;
672
Vedant Kumarc420d142017-06-16 03:27:36 +0000673 // Don't check pointers to volatile data. The behavior here is implementation-
674 // defined.
675 if (Ty.isVolatileQualified())
676 return;
677
Alexey Samsonov24cad992014-07-17 18:46:27 +0000678 SanitizerScope SanScope(this);
679
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000680 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
Craig Topper8a13c412014-05-21 05:09:00 +0000681 llvm::BasicBlock *Done = nullptr;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000682
Vedant Kumare859ebb2017-04-26 02:17:21 +0000683 // Quickly determine whether we have a pointer to an alloca. It's possible
684 // to skip null checks, and some alignment checks, for these pointers. This
685 // can reduce compile-time significantly.
Peter Collingbourne2452d702019-08-22 19:56:14 +0000686 auto PtrToAlloca = dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCasts());
Vedant Kumare859ebb2017-04-26 02:17:21 +0000687
Vedant Kumara8ff3b32017-10-03 01:27:26 +0000688 llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000689 llvm::Value *IsNonNull = nullptr;
690 bool IsGuaranteedNonNull =
691 SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
Vedant Kumar24792e32017-10-03 01:27:25 +0000692 bool AllowNullPointers = isNullPointerAllowed(TCK);
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000693 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000694 !IsGuaranteedNonNull) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000695 // The glvalue must not be an empty glvalue.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000696 IsNonNull = Builder.CreateIsNotNull(Ptr);
Richard Smith2c5868c2013-02-13 21:18:23 +0000697
Vedant Kumardbbdda42017-04-17 22:26:10 +0000698 // The IR builder can constant-fold the null check if the pointer points to
699 // a constant.
Vedant Kumara8ff3b32017-10-03 01:27:26 +0000700 IsGuaranteedNonNull = IsNonNull == True;
Vedant Kumardbbdda42017-04-17 22:26:10 +0000701
702 // Skip the null check if the pointer is known to be non-null.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000703 if (!IsGuaranteedNonNull) {
Vedant Kumardbbdda42017-04-17 22:26:10 +0000704 if (AllowNullPointers) {
705 // When performing pointer casts, it's OK if the value is null.
706 // Skip the remaining checks in that case.
707 Done = createBasicBlock("null");
708 llvm::BasicBlock *Rest = createBasicBlock("not.null");
709 Builder.CreateCondBr(IsNonNull, Rest, Done);
710 EmitBlock(Rest);
711 } else {
712 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
713 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000714 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000715 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000716
Vedant Kumar18348ea2017-02-17 23:22:55 +0000717 if (SanOpts.has(SanitizerKind::ObjectSize) &&
718 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
719 !Ty->isIncompleteType()) {
Richard Smith0130b6c2020-01-31 19:06:21 -0800720 uint64_t TySize = CGM.getMinimumObjectSize(Ty).getQuantity();
Richard Smithcfa79b22019-01-23 03:37:29 +0000721 llvm::Value *Size = llvm::ConstantInt::get(IntPtrTy, TySize);
722 if (ArraySize)
723 Size = Builder.CreateMul(Size, ArraySize);
Richard Smith69d0d262012-08-24 00:54:33 +0000724
Richard Smithcfa79b22019-01-23 03:37:29 +0000725 // Degenerate case: new X[0] does not need an objectsize check.
726 llvm::Constant *ConstantSize = dyn_cast<llvm::Constant>(Size);
727 if (!ConstantSize || !ConstantSize->isNullValue()) {
728 // The glvalue must refer to a large enough storage region.
729 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
730 // to check this.
731 // FIXME: Get object address space
732 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
James Y Knight8799cae2019-02-03 21:53:49 +0000733 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smithcfa79b22019-01-23 03:37:29 +0000734 llvm::Value *Min = Builder.getFalse();
735 llvm::Value *NullIsUnknown = Builder.getFalse();
Erik Pilkington600e9de2019-01-30 20:34:35 +0000736 llvm::Value *Dynamic = Builder.getFalse();
Richard Smithcfa79b22019-01-23 03:37:29 +0000737 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
738 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
Erik Pilkington600e9de2019-01-30 20:34:35 +0000739 Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown, Dynamic}), Size);
Richard Smithcfa79b22019-01-23 03:37:29 +0000740 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
741 }
Richard Smithe30752c2012-10-09 19:52:38 +0000742 }
Richard Smith69d0d262012-08-24 00:54:33 +0000743
Richard Smithb1b0ab42012-11-05 22:21:05 +0000744 uint64_t AlignVal = 0;
Vedant Kumar8a715332017-10-03 01:27:24 +0000745 llvm::Value *PtrAsInt = nullptr;
Richard Smithb1b0ab42012-11-05 22:21:05 +0000746
Vedant Kumar18348ea2017-02-17 23:22:55 +0000747 if (SanOpts.has(SanitizerKind::Alignment) &&
748 !SkippedChecks.has(SanitizerKind::Alignment)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000749 AlignVal = Alignment.getQuantity();
750 if (!Ty->isIncompleteType() && !AlignVal)
Richard Smith0130b6c2020-01-31 19:06:21 -0800751 AlignVal =
752 getNaturalTypeAlignment(Ty, nullptr, nullptr, /*ForPointeeType=*/true)
753 .getQuantity();
Richard Smithb1b0ab42012-11-05 22:21:05 +0000754
Richard Smith69d0d262012-08-24 00:54:33 +0000755 // The glvalue must be suitably aligned.
Vedant Kumare859ebb2017-04-26 02:17:21 +0000756 if (AlignVal > 1 &&
757 (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
Vedant Kumar8a715332017-10-03 01:27:24 +0000758 PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
759 llvm::Value *Align = Builder.CreateAnd(
760 PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000761 llvm::Value *Aligned =
Vedant Kumar8a715332017-10-03 01:27:24 +0000762 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
Vedant Kumara8ff3b32017-10-03 01:27:26 +0000763 if (Aligned != True)
764 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000765 }
Richard Smith69d0d262012-08-24 00:54:33 +0000766 }
767
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000768 if (Checks.size() > 0) {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000769 // Make sure we're not losing information. Alignment needs to be a power of
770 // 2
771 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
Richard Smithe30752c2012-10-09 19:52:38 +0000772 llvm::Constant *StaticData[] = {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000773 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
774 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
775 llvm::ConstantInt::get(Int8Ty, TCK)};
Vedant Kumar8a715332017-10-03 01:27:24 +0000776 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData,
777 PtrAsInt ? PtrAsInt : Ptr);
Richard Smithe30752c2012-10-09 19:52:38 +0000778 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000779
Richard Smithb1b0ab42012-11-05 22:21:05 +0000780 // If possible, check that the vptr indicates that there is a subobject of
781 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000782 //
783 // C++11 [basic.life]p5,6:
784 // [For storage which does not refer to an object within its lifetime]
785 // The program has undefined behavior if:
786 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000787 // or call a non-static member function
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000788 if (SanOpts.has(SanitizerKind::Vptr) &&
Vedant Kumar24792e32017-10-03 01:27:25 +0000789 !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000790 // Ensure that the pointer is non-null before loading it. If there is no
Vedant Kumara0c36712017-08-02 18:10:31 +0000791 // compile-time guarantee, reuse the run-time null check or emit a new one.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000792 if (!IsGuaranteedNonNull) {
Vedant Kumara0c36712017-08-02 18:10:31 +0000793 if (!IsNonNull)
794 IsNonNull = Builder.CreateIsNotNull(Ptr);
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000795 if (!Done)
796 Done = createBasicBlock("vptr.null");
797 llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
798 Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
799 EmitBlock(VptrNotNull);
800 }
801
Richard Smith4d3110a2012-10-25 02:14:12 +0000802 // Compute a hash of the mangled name of the type.
803 //
804 // FIXME: This is not guaranteed to be deterministic! Move to a
805 // fingerprinting mechanism once LLVM provides one. For the time
806 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000807 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000808 llvm::raw_svector_ostream Out(MangledName);
809 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
810 Out);
Richard Smith4d3110a2012-10-25 02:14:12 +0000811
Alexey Samsonov84856012014-07-10 22:34:19 +0000812 // Blacklist based on the mangled type.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000813 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +0000814 SanitizerKind::Vptr, Out.str())) {
Alexey Samsonov84856012014-07-10 22:34:19 +0000815 llvm::hash_code TypeHash = hash_value(Out.str());
Richard Smith4d3110a2012-10-25 02:14:12 +0000816
Alexey Samsonov84856012014-07-10 22:34:19 +0000817 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
818 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
819 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
John McCall7f416cc2015-09-08 08:05:57 +0000820 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000821 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
822 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
Richard Smith4d3110a2012-10-25 02:14:12 +0000823
Alexey Samsonov84856012014-07-10 22:34:19 +0000824 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
825 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
Richard Smith4d3110a2012-10-25 02:14:12 +0000826
Alexey Samsonov84856012014-07-10 22:34:19 +0000827 // Look the hash up in our cache.
828 const int CacheSize = 128;
829 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
830 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
831 "__ubsan_vptr_type_cache");
832 llvm::Value *Slot = Builder.CreateAnd(Hash,
833 llvm::ConstantInt::get(IntPtrTy,
834 CacheSize-1));
835 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
836 llvm::Value *CacheVal =
John McCall7f416cc2015-09-08 08:05:57 +0000837 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
838 getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000839
840 // If the hash isn't in the cache, call a runtime handler to perform the
841 // hard work of checking whether the vptr is for an object of the right
842 // type. This will either fill in the cache and return, or produce a
843 // diagnostic.
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000844 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
Alexey Samsonov84856012014-07-10 22:34:19 +0000845 llvm::Constant *StaticData[] = {
846 EmitCheckSourceLocation(Loc),
847 EmitCheckTypeDescriptor(Ty),
848 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
849 llvm::ConstantInt::get(Int8Ty, TCK)
850 };
John McCall7f416cc2015-09-08 08:05:57 +0000851 llvm::Value *DynamicData[] = { Ptr, Hash };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000852 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000853 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
854 DynamicData);
Alexey Samsonov84856012014-07-10 22:34:19 +0000855 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000856 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000857
858 if (Done) {
859 Builder.CreateBr(Done);
860 EmitBlock(Done);
861 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000862}
Chris Lattner4647a212007-08-31 22:49:20 +0000863
Richard Smith539e4a72013-02-23 02:53:19 +0000864/// Determine whether this expression refers to a flexible array member in a
865/// struct. We disable array bounds checks for such members.
866static bool isFlexibleArrayMemberExpr(const Expr *E) {
867 // For compatibility with existing code, we treat arrays of length 0 or
868 // 1 as flexible array members.
Richard Smithf18233d2020-03-18 15:46:31 -0700869 // FIXME: This is inconsistent with the warning code in SemaChecking. Unify
870 // the two mechanisms.
Richard Smith539e4a72013-02-23 02:53:19 +0000871 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000872 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smithf18233d2020-03-18 15:46:31 -0700873 // FIXME: Sema doesn't treat [1] as a flexible array member if the bound
874 // was produced by macro expansion.
Richard Smith539e4a72013-02-23 02:53:19 +0000875 if (CAT->getSize().ugt(1))
876 return false;
877 } else if (!isa<IncompleteArrayType>(AT))
878 return false;
879
880 E = E->IgnoreParens();
881
882 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000883 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000884 // FIXME: If the base type of the member expr is not FD->getParent(),
885 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000886 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smithf18233d2020-03-18 15:46:31 -0700887 // FIXME: Sema doesn't treat a T[1] union member as a flexible array
888 // member, only a T[0] or T[] member gets that treatment.
889 if (FD->getParent()->isUnion())
890 return true;
Richard Smith539e4a72013-02-23 02:53:19 +0000891 RecordDecl::field_iterator FI(
892 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
893 return ++FI == FD->getParent()->field_end();
894 }
Vedant Kumare356f1a2016-10-04 20:36:04 +0000895 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
896 return IRE->getDecl()->getNextIvar() == nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000897 }
898
899 return false;
900}
901
Vedant Kumar36347d92017-12-08 01:51:47 +0000902llvm::Value *CodeGenFunction::LoadPassedObjectSize(const Expr *E,
903 QualType EltTy) {
904 ASTContext &C = getContext();
905 uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity();
906 if (!EltSize)
907 return nullptr;
908
909 auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
910 if (!ArrayDeclRef)
911 return nullptr;
912
913 auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
914 if (!ParamDecl)
915 return nullptr;
916
Vedant Kumar36347d92017-12-08 01:51:47 +0000917 auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
918 if (!POSAttr)
919 return nullptr;
920
921 // Don't load the size if it's a lower bound.
922 int POSType = POSAttr->getType();
923 if (POSType != 0 && POSType != 1)
924 return nullptr;
925
926 // Find the implicit size parameter.
927 auto PassedSizeIt = SizeArguments.find(ParamDecl);
928 if (PassedSizeIt == SizeArguments.end())
929 return nullptr;
930
931 const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
932 assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
933 Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
934 llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false,
935 C.getSizeType(), E->getExprLoc());
936 llvm::Value *SizeOfElement =
937 llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
938 return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
939}
940
Richard Smith539e4a72013-02-23 02:53:19 +0000941/// If Base is known to point to the start of an array, return the length of
942/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000943static llvm::Value *getArrayIndexingBound(
944 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000945 // For the vector indexing extension, the bound is the number of elements.
946 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
947 IndexedType = Base->getType();
948 return CGF.Builder.getInt32(VT->getNumElements());
949 }
950
951 Base = Base->IgnoreParens();
952
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000953 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000954 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
955 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
956 IndexedType = CE->getSubExpr()->getType();
957 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000958 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000959 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000960 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Sander de Smalen891af03a2018-02-03 13:55:59 +0000961 return CGF.getVLASize(VAT).NumElts;
Vedant Kumar36347d92017-12-08 01:51:47 +0000962 // Ignore pass_object_size here. It's not applicable on decayed pointers.
Richard Smith539e4a72013-02-23 02:53:19 +0000963 }
964 }
965
Vedant Kumar36347d92017-12-08 01:51:47 +0000966 QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
967 if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) {
968 IndexedType = Base->getType();
969 return POS;
970 }
971
Craig Topper8a13c412014-05-21 05:09:00 +0000972 return nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000973}
974
975void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
976 llvm::Value *Index, QualType IndexType,
977 bool Accessed) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000978 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
Richard Smith6b53e222013-10-22 22:51:04 +0000979 "should not be called unless adding bounds checks");
Alexey Samsonov24cad992014-07-17 18:46:27 +0000980 SanitizerScope SanScope(this);
Richard Smith2847b222013-02-24 01:56:24 +0000981
Richard Smith539e4a72013-02-23 02:53:19 +0000982 QualType IndexedType;
983 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
984 if (!Bound)
985 return;
986
987 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
988 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
989 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
990
991 llvm::Constant *StaticData[] = {
992 EmitCheckSourceLocation(E->getExprLoc()),
993 EmitCheckTypeDescriptor(IndexedType),
994 EmitCheckTypeDescriptor(IndexType)
995 };
996 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
997 : Builder.CreateICmpULE(IndexVal, BoundVal);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000998 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
999 SanitizerHandler::OutOfBounds, StaticData, Index);
Richard Smith539e4a72013-02-23 02:53:19 +00001000}
1001
Chris Lattner116ce8f2010-01-09 21:40:03 +00001002
Chris Lattner116ce8f2010-01-09 21:40:03 +00001003CodeGenFunction::ComplexPairTy CodeGenFunction::
1004EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
1005 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001006 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00001007
Chris Lattner116ce8f2010-01-09 21:40:03 +00001008 llvm::Value *NextVal;
1009 if (isa<llvm::IntegerType>(InVal.first->getType())) {
1010 uint64_t AmountVal = isInc ? 1 : -1;
1011 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +00001012
Chris Lattner116ce8f2010-01-09 21:40:03 +00001013 // Add the inc/dec to the real part.
1014 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
1015 } else {
Simon Pilgrim7e38f0c2019-10-07 16:42:25 +00001016 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Chris Lattner116ce8f2010-01-09 21:40:03 +00001017 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
1018 if (!isInc)
1019 FVal.changeSign();
1020 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
Craig Topper99e79272013-07-26 05:59:26 +00001021
Chris Lattner116ce8f2010-01-09 21:40:03 +00001022 // Add the inc/dec to the real part.
1023 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
1024 }
Craig Topper99e79272013-07-26 05:59:26 +00001025
Chris Lattner116ce8f2010-01-09 21:40:03 +00001026 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +00001027
Chris Lattner116ce8f2010-01-09 21:40:03 +00001028 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +00001029 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Alexey Bataev7b518dc2020-01-06 16:14:34 -05001030 if (getLangOpts().OpenMP)
1031 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
1032 E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00001033
Chris Lattner116ce8f2010-01-09 21:40:03 +00001034 // If this is a postinc, return the value read from memory, otherwise use the
1035 // updated value.
1036 return isPre ? IncVal : InVal;
1037}
1038
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00001039void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
1040 CodeGenFunction *CGF) {
1041 // Bind VLAs in the cast type.
1042 if (CGF && E->getType()->isVariablyModifiedType())
1043 CGF->EmitVariablyModifiedType(E->getType());
1044
1045 if (CGDebugInfo *DI = getModuleDebugInfo())
1046 DI->EmitExplicitCastType(E->getType());
1047}
1048
Chris Lattnera45c5af2007-06-02 19:47:04 +00001049//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +00001050// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +00001051//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +00001052
John McCall7f416cc2015-09-08 08:05:57 +00001053/// EmitPointerWithAlignment - Given an expression of pointer type, try to
1054/// derive a more accurate bound on the alignment of the pointer.
1055Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00001056 LValueBaseInfo *BaseInfo,
1057 TBAAAccessInfo *TBAAInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00001058 // We allow this with ObjC object pointers because of fragile ABIs.
1059 assert(E->getType()->isPointerType() ||
1060 E->getType()->isObjCObjectPointerType());
1061 E = E->IgnoreParens();
1062
1063 // Casts:
1064 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00001065 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
1066 CGM.EmitExplicitCastExprType(ECE, this);
John McCall7f416cc2015-09-08 08:05:57 +00001067
1068 switch (CE->getCastKind()) {
1069 // Non-converting casts (but not C's implicit conversion from void*).
1070 case CK_BitCast:
1071 case CK_NoOp:
Anastasia Stulova0a72ed42017-09-27 14:37:00 +00001072 case CK_AddressSpaceConversion:
John McCall7f416cc2015-09-08 08:05:57 +00001073 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
1074 if (PtrTy->getPointeeType()->isVoidType())
1075 break;
1076
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00001077 LValueBaseInfo InnerBaseInfo;
1078 TBAAAccessInfo InnerTBAAInfo;
1079 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(),
1080 &InnerBaseInfo,
1081 &InnerTBAAInfo);
1082 if (BaseInfo) *BaseInfo = InnerBaseInfo;
1083 if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
John McCall7f416cc2015-09-08 08:05:57 +00001084
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00001085 if (isa<ExplicitCastExpr>(CE)) {
1086 LValueBaseInfo TargetTypeBaseInfo;
1087 TBAAAccessInfo TargetTypeTBAAInfo;
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001088 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(),
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00001089 &TargetTypeBaseInfo,
1090 &TargetTypeTBAAInfo);
1091 if (TBAAInfo)
1092 *TBAAInfo = CGM.mergeTBAAInfoForCast(*TBAAInfo,
1093 TargetTypeTBAAInfo);
1094 // If the source l-value is opaque, honor the alignment of the
1095 // casted-to type.
1096 if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
1097 if (BaseInfo)
1098 BaseInfo->mergeForCast(TargetTypeBaseInfo);
1099 Addr = Address(Addr.getPointer(), Align);
1100 }
John McCall7f416cc2015-09-08 08:05:57 +00001101 }
1102
Peter Collingbourne574975e2016-01-14 02:49:48 +00001103 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
1104 CE->getCastKind() == CK_BitCast) {
Peter Collingbourneee381ff2015-09-09 00:01:31 +00001105 if (auto PT = E->getType()->getAs<PointerType>())
1106 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
1107 /*MayBeNull=*/true,
1108 CodeGenFunction::CFITCK_UnrelatedCast,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001109 CE->getBeginLoc());
Peter Collingbourneee381ff2015-09-09 00:01:31 +00001110 }
Anastasia Stulova0a72ed42017-09-27 14:37:00 +00001111 return CE->getCastKind() != CK_AddressSpaceConversion
1112 ? Builder.CreateBitCast(Addr, ConvertType(E->getType()))
1113 : Builder.CreateAddrSpaceCast(Addr,
1114 ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00001115 }
1116 break;
1117
1118 // Array-to-pointer decay.
1119 case CK_ArrayToPointerDecay:
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00001120 return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
John McCall7f416cc2015-09-08 08:05:57 +00001121
1122 // Derived-to-base conversions.
1123 case CK_UncheckedDerivedToBase:
1124 case CK_DerivedToBase: {
Ivan A. Kosareved4f3302018-01-08 15:36:06 +00001125 // TODO: Support accesses to members of base classes in TBAA. For now, we
1126 // conservatively pretend that the complete object is of the base class
1127 // type.
1128 if (TBAAInfo)
1129 *TBAAInfo = CGM.getTBAAAccessInfo(E->getType());
1130 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +00001131 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
1132 return GetAddressOfBaseClass(Addr, Derived,
1133 CE->path_begin(), CE->path_end(),
1134 ShouldNullCheckClassCastValue(CE),
1135 CE->getExprLoc());
1136 }
1137
1138 // TODO: Is there any reason to treat base-to-derived conversions
1139 // specially?
1140 default:
1141 break;
1142 }
1143 }
1144
1145 // Unary &.
1146 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1147 if (UO->getOpcode() == UO_AddrOf) {
1148 LValue LV = EmitLValue(UO->getSubExpr());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001149 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00001150 if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001151 return LV.getAddress(*this);
John McCall7f416cc2015-09-08 08:05:57 +00001152 }
1153 }
1154
1155 // TODO: conditional operators, comma.
1156
1157 // Otherwise, use the alignment of the type.
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00001158 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), BaseInfo,
1159 TBAAInfo);
John McCall7f416cc2015-09-08 08:05:57 +00001160 return Address(EmitScalarExpr(E), Align);
1161}
1162
Daniel Dunbarc79407f2009-02-05 07:09:07 +00001163RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001164 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001165 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +00001166
1167 switch (getEvaluationKind(Ty)) {
1168 case TEK_Complex: {
1169 llvm::Type *EltTy =
1170 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +00001171 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +00001172 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001173 }
Craig Topper99e79272013-07-26 05:59:26 +00001174
Chris Lattner65526f02010-08-23 05:26:13 +00001175 // If this is a use of an undefined aggregate type, the aggregate must have an
1176 // identifiable address. Just because the contents of the value are undefined
1177 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +00001178 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00001179 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +00001180 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +00001181 }
John McCall47fb9502013-03-07 21:37:08 +00001182
1183 case TEK_Scalar:
1184 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1185 }
1186 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +00001187}
1188
Daniel Dunbarc79407f2009-02-05 07:09:07 +00001189RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
1190 const char *Name) {
1191 ErrorUnsupported(E, Name);
1192 return GetUndefRValue(E->getType());
1193}
1194
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001195LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
1196 const char *Name) {
1197 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001198 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00001199 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
1200 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001201}
1202
Vedant Kumarffd7c882017-04-14 22:03:34 +00001203bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001204 const Expr *Base = Obj;
1205 while (!isa<CXXThisExpr>(Base)) {
1206 // The result of a dynamic_cast can be null.
1207 if (isa<CXXDynamicCastExpr>(Base))
1208 return false;
1209
1210 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1211 Base = CE->getSubExpr();
1212 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
1213 Base = PE->getSubExpr();
1214 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1215 if (UO->getOpcode() == UO_Extension)
1216 Base = UO->getSubExpr();
1217 else
1218 return false;
1219 } else {
1220 return false;
1221 }
1222 }
1223 return true;
1224}
1225
Richard Smith4d1458e2012-09-08 02:08:36 +00001226LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +00001227 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001228 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +00001229 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1230 else
1231 LV = EmitLValue(E);
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001232 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1233 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00001234 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1235 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1236 if (IsBaseCXXThis)
1237 SkippedChecks.set(SanitizerKind::Alignment, true);
1238 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001239 SkippedChecks.set(SanitizerKind::Null, true);
Vedant Kumarffd7c882017-04-14 22:03:34 +00001240 }
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001241 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(*this), E->getType(),
1242 LV.getAlignment(), SkippedChecks);
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001243 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +00001244 return LV;
1245}
1246
Chris Lattner8394d792007-06-05 20:53:16 +00001247/// EmitLValue - Emit code to compute a designator that specifies the location
1248/// of the expression.
1249///
Mike Stump4a3999f2009-09-09 13:00:44 +00001250/// This can return one of two things: a simple address or a bitfield reference.
1251/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1252/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +00001253///
Mike Stump4a3999f2009-09-09 13:00:44 +00001254/// If this returns a bitfield reference, nothing about the pointee type of the
1255/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +00001256///
Mike Stump4a3999f2009-09-09 13:00:44 +00001257/// If this returns a normal address, and if the lvalue's C type is fixed size,
1258/// this method guarantees that the returned pointer type will point to an LLVM
1259/// type of the same size of the lvalue's type. If the lvalue has a variable
1260/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +00001261///
Chris Lattnerd7f58862007-06-02 05:24:33 +00001262LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +00001263 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +00001264 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001265 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +00001266
John McCallc109a252011-11-07 03:59:57 +00001267 case Expr::ObjCPropertyRefExprClass:
1268 llvm_unreachable("cannot emit a property reference directly");
1269
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00001270 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +00001271 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00001272 case Expr::ObjCIsaExprClass:
1273 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001274 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00001275 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001276 case Expr::CompoundAssignOperatorClass: {
1277 QualType Ty = E->getType();
1278 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1279 Ty = AT->getValueType();
1280 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +00001281 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1282 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001283 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001284 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +00001285 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001286 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001287 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001288 return EmitCallExprLValue(cast<CallExpr>(E));
Richard Smith778dc0f2019-10-19 00:04:38 +00001289 case Expr::CXXRewrittenBinaryOperatorClass:
1290 return EmitLValue(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm());
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00001291 case Expr::VAArgExprClass:
1292 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001293 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001294 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Bill Wendling8003edc2018-11-09 00:41:36 +00001295 case Expr::ConstantExprClass:
1296 return EmitLValue(cast<ConstantExpr>(E)->getSubExpr());
Eric Christopherd98e4242011-09-08 17:15:04 +00001297 case Expr::ParenExprClass:
1298 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +00001299 case Expr::GenericSelectionExprClass:
1300 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +00001301 case Expr::PredefinedExprClass:
1302 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +00001303 case Expr::StringLiteralClass:
1304 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001305 case Expr::ObjCEncodeExprClass:
1306 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +00001307 case Expr::PseudoObjectExprClass:
1308 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001309 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +00001310 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +00001311 case Expr::CXXTemporaryObjectExprClass:
1312 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001313 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1314 case Expr::CXXBindTemporaryExprClass:
1315 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +00001316 case Expr::CXXUuidofExprClass:
1317 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Erik Pilkington3299ead2019-04-02 19:48:07 +00001318 case Expr::LambdaExprClass:
1319 return EmitAggExprToLValue(E);
John McCall08ef4662011-11-10 08:15:53 +00001320
1321 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001322 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +00001323 enterFullExpression(cleanups);
1324 RunCleanupsScope Scope(*this);
Reid Kleckner092d0652017-03-06 22:18:34 +00001325 LValue LV = EmitLValue(cleanups->getSubExpr());
1326 if (LV.isSimple()) {
1327 // Defend against branches out of gnu statement expressions surrounded by
1328 // cleanups.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001329 llvm::Value *V = LV.getPointer(*this);
Reid Kleckner092d0652017-03-06 22:18:34 +00001330 Scope.ForceCleanup({&V});
1331 return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001332 getContext(), LV.getBaseInfo(), LV.getTBAAInfo());
Reid Kleckner092d0652017-03-06 22:18:34 +00001333 }
1334 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1335 // bitfield lvalue or some other non-simple lvalue?
1336 return LV;
John McCall08ef4662011-11-10 08:15:53 +00001337 }
1338
Eric Fiselier708afb52019-05-16 21:04:15 +00001339 case Expr::CXXDefaultArgExprClass: {
1340 auto *DAE = cast<CXXDefaultArgExpr>(E);
1341 CXXDefaultArgExprScope Scope(*this, DAE);
1342 return EmitLValue(DAE->getExpr());
1343 }
Richard Smith852c9db2013-04-20 22:23:05 +00001344 case Expr::CXXDefaultInitExprClass: {
Eric Fiselier708afb52019-05-16 21:04:15 +00001345 auto *DIE = cast<CXXDefaultInitExpr>(E);
1346 CXXDefaultInitExprScope Scope(*this, DIE);
1347 return EmitLValue(DIE->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001348 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001349 case Expr::CXXTypeidExprClass:
1350 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001351
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001352 case Expr::ObjCMessageExprClass:
1353 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001354 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001355 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001356 case Expr::StmtExprClass:
1357 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001358 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001359 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001360 case Expr::ArraySubscriptExprClass:
1361 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001362 case Expr::OMPArraySectionExprClass:
1363 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001364 case Expr::ExtVectorElementExprClass:
1365 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001366 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001367 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001368 case Expr::CompoundLiteralExprClass:
1369 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001370 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001371 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001372 case Expr::BinaryConditionalOperatorClass:
1373 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001374 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001375 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001376 case Expr::OpaqueValueExprClass:
1377 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001378 case Expr::SubstNonTypeTemplateParmExprClass:
1379 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001380 case Expr::ImplicitCastExprClass:
1381 case Expr::CStyleCastExprClass:
1382 case Expr::CXXFunctionalCastExprClass:
1383 case Expr::CXXStaticCastExprClass:
1384 case Expr::CXXDynamicCastExprClass:
1385 case Expr::CXXReinterpretCastExprClass:
1386 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001387 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001388 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001389
Douglas Gregorfe314812011-06-21 17:03:29 +00001390 case Expr::MaterializeTemporaryExprClass:
1391 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Eric Fiseliercddaf872017-06-15 19:43:36 +00001392
1393 case Expr::CoawaitExprClass:
1394 return EmitCoawaitLValue(cast<CoawaitExpr>(E));
1395 case Expr::CoyieldExprClass:
1396 return EmitCoyieldLValue(cast<CoyieldExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001397 }
1398}
1399
John McCall71335052012-03-10 03:05:10 +00001400/// Given an object of the given canonical type, can we safely copy a
1401/// value out of it based on its initializer?
1402static bool isConstantEmittableObjectType(QualType type) {
1403 assert(type.isCanonical());
1404 assert(!type->isReferenceType());
1405
1406 // Must be const-qualified but non-volatile.
1407 Qualifiers qs = type.getLocalQualifiers();
1408 if (!qs.hasConst() || qs.hasVolatile()) return false;
1409
1410 // Otherwise, all object types satisfy this except C++ classes with
1411 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001412 if (const auto *RT = dyn_cast<RecordType>(type))
1413 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001414 if (RD->hasMutableFields() || !RD->isTrivial())
1415 return false;
1416
1417 return true;
1418}
1419
1420/// Can we constant-emit a load of a reference to a variable of the
1421/// given type? This is different from predicates like
Richard Smith715f7a12019-06-11 17:50:32 +00001422/// Decl::mightBeUsableInConstantExpressions because we do want it to apply
John McCall71335052012-03-10 03:05:10 +00001423/// in situations that don't necessarily satisfy the language's rules
1424/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1425/// to do this with const float variables even if those variables
1426/// aren't marked 'constexpr'.
1427enum ConstantEmissionKind {
1428 CEK_None,
1429 CEK_AsReferenceOnly,
1430 CEK_AsValueOrReference,
1431 CEK_AsValueOnly
1432};
1433static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1434 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001435 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001436 if (isConstantEmittableObjectType(ref->getPointeeType()))
1437 return CEK_AsValueOrReference;
1438 return CEK_AsReferenceOnly;
1439 }
1440 if (isConstantEmittableObjectType(type))
1441 return CEK_AsValueOnly;
1442 return CEK_None;
1443}
1444
1445/// Try to emit a reference to the given value without producing it as
Richard Smith24cdcad2019-06-14 17:46:37 +00001446/// an l-value. This is just an optimization, but it avoids us needing
1447/// to emit global copies of variables if they're named without triggering
1448/// a formal use in a context where we can't emit a direct reference to them,
1449/// for instance if a block or lambda or a member of a local class uses a
1450/// const int variable or constexpr variable from an enclosing function.
John McCall71335052012-03-10 03:05:10 +00001451CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001452CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1453 ValueDecl *value = refExpr->getDecl();
1454
John McCall71335052012-03-10 03:05:10 +00001455 // The value needs to be an enum constant or a constant variable.
1456 ConstantEmissionKind CEK;
1457 if (isa<ParmVarDecl>(value)) {
1458 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001459 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001460 CEK = checkVarTypeForConstantEmission(var->getType());
1461 } else if (isa<EnumConstantDecl>(value)) {
1462 CEK = CEK_AsValueOnly;
1463 } else {
1464 CEK = CEK_None;
1465 }
1466 if (CEK == CEK_None) return ConstantEmission();
1467
John McCall71335052012-03-10 03:05:10 +00001468 Expr::EvalResult result;
1469 bool resultIsReference;
1470 QualType resultType;
1471
1472 // It's best to evaluate all the way as an r-value if that's permitted.
1473 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001474 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001475 resultIsReference = false;
1476 resultType = refExpr->getType();
1477
1478 // Otherwise, try to evaluate as an l-value.
1479 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001480 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001481 resultIsReference = true;
1482 resultType = value->getType();
1483
1484 // Failure.
1485 } else {
1486 return ConstantEmission();
1487 }
1488
1489 // In any case, if the initializer has side-effects, abandon ship.
1490 if (result.HasSideEffects)
1491 return ConstantEmission();
1492
1493 // Emit as a constant.
John McCallde0fe072017-08-15 21:42:52 +00001494 auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
1495 result.Val, resultType);
John McCall71335052012-03-10 03:05:10 +00001496
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001497 // Make sure we emit a debug reference to the global variable.
1498 // This should probably fire even for
1499 if (isa<VarDecl>(value)) {
1500 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001501 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001502 } else {
1503 assert(isa<EnumConstantDecl>(value));
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001504 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001505 }
John McCall71335052012-03-10 03:05:10 +00001506
1507 // If we emitted a reference constant, we need to dereference that.
1508 if (resultIsReference)
1509 return ConstantEmission::forReference(C);
1510
1511 return ConstantEmission::forValue(C);
1512}
1513
Alex Lorenz6cc83172017-08-25 10:07:00 +00001514static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
1515 const MemberExpr *ME) {
1516 if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
1517 // Try to emit static variable member expressions as DREs.
1518 return DeclRefExpr::Create(
1519 CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD,
1520 /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
Richard Smith1bbad592019-06-11 17:50:36 +00001521 ME->getType(), ME->getValueKind(), nullptr, nullptr, ME->isNonOdrUse());
Alex Lorenz6cc83172017-08-25 10:07:00 +00001522 }
1523 return nullptr;
1524}
1525
1526CodeGenFunction::ConstantEmission
1527CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
1528 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
1529 return tryEmitAsConstant(DRE);
1530 return ConstantEmission();
1531}
1532
Volodymyr Sapsaief1899b2018-11-01 21:57:05 +00001533llvm::Value *CodeGenFunction::emitScalarConstant(
1534 const CodeGenFunction::ConstantEmission &Constant, Expr *E) {
1535 assert(Constant && "not a constant");
1536 if (Constant.isReference())
1537 return EmitLoadOfLValue(Constant.getReferenceLValue(*this, E),
1538 E->getExprLoc())
1539 .getScalarVal();
1540 return Constant.getValue();
1541}
1542
Nick Lewycky2d84e842013-10-02 02:29:49 +00001543llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1544 SourceLocation Loc) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001545 return EmitLoadOfScalar(lvalue.getAddress(*this), lvalue.isVolatile(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001546 lvalue.getType(), Loc, lvalue.getBaseInfo(),
Ivan A. Kosareva511ed72017-10-03 10:52:39 +00001547 lvalue.getTBAAInfo(), lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001548}
1549
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001550static bool hasBooleanRepresentation(QualType Ty) {
1551 if (Ty->isBooleanType())
1552 return true;
1553
1554 if (const EnumType *ET = Ty->getAs<EnumType>())
1555 return ET->getDecl()->getIntegerType()->isBooleanType();
1556
Douglas Gregor298f43d2012-04-12 20:42:30 +00001557 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1558 return hasBooleanRepresentation(AT->getValueType());
1559
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001560 return false;
1561}
1562
Richard Smith1629da92012-12-13 07:11:50 +00001563static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1564 llvm::APInt &Min, llvm::APInt &End,
Vedant Kumar4593a462016-12-09 23:48:18 +00001565 bool StrictEnums, bool IsBool) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001566 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001567 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1568 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001569 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001570 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001571
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001572 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001573 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1574 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001575 } else {
1576 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001577 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001578 unsigned Bitwidth = LTy->getScalarSizeInBits();
1579 unsigned NumNegativeBits = ED->getNumNegativeBits();
1580 unsigned NumPositiveBits = ED->getNumPositiveBits();
1581
1582 if (NumNegativeBits) {
1583 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1584 assert(NumBits <= Bitwidth);
1585 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1586 Min = -End;
1587 } else {
1588 assert(NumPositiveBits <= Bitwidth);
1589 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1590 Min = llvm::APInt(Bitwidth, 0);
1591 }
1592 }
Richard Smith1629da92012-12-13 07:11:50 +00001593 return true;
1594}
1595
1596llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1597 llvm::APInt Min, End;
Vedant Kumar4593a462016-12-09 23:48:18 +00001598 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1599 hasBooleanRepresentation(Ty)))
Craig Topper8a13c412014-05-21 05:09:00 +00001600 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001601
Duncan Sandsc720e782012-04-15 18:04:54 +00001602 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001603 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001604}
1605
Vedant Kumar5a972652017-02-27 19:46:19 +00001606bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1607 SourceLocation Loc) {
1608 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1609 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1610 if (!HasBoolCheck && !HasEnumCheck)
1611 return false;
1612
1613 bool IsBool = hasBooleanRepresentation(Ty) ||
1614 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1615 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1616 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1617 if (!NeedsBoolCheck && !NeedsEnumCheck)
1618 return false;
1619
Vedant Kumar129edab2017-03-09 16:06:27 +00001620 // Single-bit booleans don't need to be checked. Special-case this to avoid
1621 // a bit width mismatch when handling bitfield values. This is handled by
1622 // EmitFromMemory for the non-bitfield case.
1623 if (IsBool &&
1624 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1625 return false;
1626
Vedant Kumar5a972652017-02-27 19:46:19 +00001627 llvm::APInt Min, End;
1628 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1629 return true;
1630
Vedant Kumar791f7012017-10-03 01:27:26 +00001631 auto &Ctx = getLLVMContext();
Vedant Kumar5a972652017-02-27 19:46:19 +00001632 SanitizerScope SanScope(this);
1633 llvm::Value *Check;
1634 --End;
1635 if (!Min) {
Vedant Kumar791f7012017-10-03 01:27:26 +00001636 Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
Vedant Kumar5a972652017-02-27 19:46:19 +00001637 } else {
Vedant Kumar791f7012017-10-03 01:27:26 +00001638 llvm::Value *Upper =
1639 Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
1640 llvm::Value *Lower =
1641 Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
Vedant Kumar5a972652017-02-27 19:46:19 +00001642 Check = Builder.CreateAnd(Upper, Lower);
1643 }
1644 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1645 EmitCheckTypeDescriptor(Ty)};
1646 SanitizerMask Kind =
1647 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1648 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1649 StaticArgs, EmitCheckValue(Value));
1650 return true;
1651}
1652
John McCall7f416cc2015-09-08 08:05:57 +00001653llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1654 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001655 SourceLocation Loc,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001656 LValueBaseInfo BaseInfo,
Ivan A. Kosareva511ed72017-10-03 10:52:39 +00001657 TBAAAccessInfo TBAAInfo,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001658 bool isNontemporal) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001659 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1660 // For better performance, handle vector loads differently.
1661 if (Ty->isVectorType()) {
1662 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001663
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001664 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001665
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001666 // Handle vectors of size 3 like size 4 for better performance.
1667 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001668
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001669 // Bitcast to vec4 type.
1670 llvm::VectorType *vec4Ty =
1671 llvm::VectorType::get(VTy->getElementType(), 4);
1672 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1673 // Now load value.
1674 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001675
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001676 // Shuffle vector to get vec3.
1677 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
Eli Friedman1ee6ec22020-03-31 13:08:59 -07001678 ArrayRef<int>{0, 1, 2}, "extractVec");
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001679 return EmitFromMemory(V, Ty);
1680 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001681 }
1682 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001683
1684 // Atomic operations have to be done on integral types.
David Majnemera38c9f12016-05-24 16:09:25 +00001685 LValue AtomicLValue =
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001686 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
David Majnemera38c9f12016-05-24 16:09:25 +00001687 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1688 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001689 }
Craig Topper99e79272013-07-26 05:59:26 +00001690
John McCall7f416cc2015-09-08 08:05:57 +00001691 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001692 if (isNontemporal) {
1693 llvm::MDNode *Node = llvm::MDNode::get(
1694 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1695 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1696 }
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001697
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001698 CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
Daniel Dunbar1d425462009-02-10 00:57:50 +00001699
Vedant Kumar5a972652017-02-27 19:46:19 +00001700 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1701 // In order to prevent the optimizer from throwing away the check, don't
1702 // attach range metadata to the load.
Richard Smith1629da92012-12-13 07:11:50 +00001703 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001704 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1705 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001706
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001707 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001708}
1709
John McCall3a7f6922010-10-27 20:58:56 +00001710llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1711 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001712 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001713 // This should really always be an i1, but sometimes it's already
1714 // an i8, and it's awkward to track those cases down.
1715 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001716 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1717 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1718 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001719 }
1720
1721 return Value;
1722}
1723
1724llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1725 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001726 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001727 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1728 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001729 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1730 }
1731
1732 return Value;
1733}
1734
John McCall7f416cc2015-09-08 08:05:57 +00001735void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1736 bool Volatile, QualType Ty,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001737 LValueBaseInfo BaseInfo,
Ivan A. Kosareva511ed72017-10-03 10:52:39 +00001738 TBAAAccessInfo TBAAInfo,
1739 bool isInit, bool isNontemporal) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001740 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1741 // Handle vectors differently to get better performance.
1742 if (Ty->isVectorType()) {
1743 llvm::Type *SrcTy = Value->getType();
Simon Pilgrima5dbbc62017-06-01 20:13:34 +00001744 auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001745 // Handle vec3 special.
Simon Pilgrima5dbbc62017-06-01 20:13:34 +00001746 if (VecTy && VecTy->getNumElements() == 3) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001747 // Our source is a vec3, do a shuffle vector to make it a vec4.
1748 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1749 Builder.getInt32(2),
1750 llvm::UndefValue::get(Builder.getInt32Ty())};
1751 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1752 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
1753 MaskV, "extractVec");
1754 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1755 }
1756 if (Addr.getElementType() != SrcTy) {
1757 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1758 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001759 }
1760 }
Craig Topper99e79272013-07-26 05:59:26 +00001761
John McCall3a7f6922010-10-27 20:58:56 +00001762 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001763
David Majnemera38c9f12016-05-24 16:09:25 +00001764 LValue AtomicLValue =
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001765 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
David Majnemera5b195a2015-02-14 01:35:12 +00001766 if (Ty->isAtomicType() ||
David Majnemera38c9f12016-05-24 16:09:25 +00001767 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1768 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
John McCalla8ec7eb2013-03-07 21:37:17 +00001769 return;
1770 }
1771
Daniel Dunbar03816342010-08-21 02:24:36 +00001772 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001773 if (isNontemporal) {
1774 llvm::MDNode *Node =
1775 llvm::MDNode::get(Store->getContext(),
1776 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1777 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1778 }
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001779
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00001780 CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
Daniel Dunbar1d425462009-02-10 00:57:50 +00001781}
1782
David Chisnallfa35df62012-01-16 17:27:18 +00001783void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001784 bool isInit) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001785 EmitStoreOfScalar(value, lvalue.getAddress(*this), lvalue.isVolatile(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001786 lvalue.getType(), lvalue.getBaseInfo(),
Ivan A. Kosareva511ed72017-10-03 10:52:39 +00001787 lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001788}
1789
Mike Stump4a3999f2009-09-09 13:00:44 +00001790/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1791/// method emits the address of the lvalue, then loads the result as an rvalue,
1792/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001793RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001794 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001795 // load of a __weak object.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001796 Address AddrWeakObj = LV.getAddress(*this);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001797 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1798 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001799 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001800 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001801 // In MRC mode, we do a load+autorelease.
1802 if (!getLangOpts().ObjCAutoRefCount) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001803 return RValue::get(EmitARCLoadWeak(LV.getAddress(*this)));
John McCall460ce582015-10-22 18:38:17 +00001804 }
1805
1806 // In ARC mode, we load retained and then consume the value.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001807 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress(*this));
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001808 Object = EmitObjCConsumeObject(LV.getType(), Object);
1809 return RValue::get(Object);
1810 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001811
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001812 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001813 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001814
John McCalla1dee5302010-08-22 10:59:02 +00001815 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001816 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001817 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001818
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001819 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001820 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001821 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001822 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001823 "vecext"));
1824 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001825
1826 // If this is a reference to a subset of the elements of a vector, either
1827 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001828 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001829 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001830
Renato Golin230c5eb2014-05-19 18:15:42 +00001831 // Global Register variables always invoke intrinsics
1832 if (LV.isGlobalReg())
1833 return EmitLoadOfGlobalRegLValue(LV);
1834
John McCallc109a252011-11-07 03:59:57 +00001835 assert(LV.isBitField() && "Unknown LValue type!");
Vedant Kumar129edab2017-03-09 16:06:27 +00001836 return EmitLoadOfBitfieldLValue(LV, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +00001837}
1838
Vedant Kumar129edab2017-03-09 16:06:27 +00001839RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1840 SourceLocation Loc) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001841 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001842
Daniel Dunbar3447a022010-04-13 23:34:15 +00001843 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001844 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001845
John McCall7f416cc2015-09-08 08:05:57 +00001846 Address Ptr = LV.getBitFieldAddress();
1847 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001848
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001849 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001850 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001851 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1852 if (HighBits)
1853 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1854 if (Info.Offset + HighBits)
1855 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1856 } else {
1857 if (Info.Offset)
1858 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001859 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001860 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1861 Info.Size),
1862 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001863 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001864 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Vedant Kumar129edab2017-03-09 16:06:27 +00001865 EmitScalarRangeCheck(Val, LV.getType(), Loc);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001866 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001867}
1868
Nate Begemanb699c9b2009-01-18 06:42:49 +00001869// If this is a reference to a subset of the elements of a vector, create an
1870// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001871RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001872 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1873 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001874
Nate Begemanf322eab2008-05-09 06:41:27 +00001875 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001876
1877 // If the result of the expression is a non-vector type, we must be extracting
1878 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001879 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001880 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001881 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001882 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001883 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001884 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001885
1886 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001887 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001888
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001889 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001890 for (unsigned i = 0; i != NumResultElts; ++i)
1891 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001892
Chris Lattner91c08ad2011-02-15 00:14:06 +00001893 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1894 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001895 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001896 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001897}
1898
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001899/// Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001900Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1901 Address VectorAddress = LV.getExtVectorAddress();
Simon Pilgrim16c53ff2020-01-11 15:33:25 +00001902 QualType EQT = LV.getType()->castAs<VectorType>()->getElementType();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001903 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fangrui Song6907ce22018-07-30 19:24:48 +00001904
John McCall7f416cc2015-09-08 08:05:57 +00001905 Address CastToPointerElement =
1906 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1907 "conv.ptr.element");
Fangrui Song6907ce22018-07-30 19:24:48 +00001908
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001909 const llvm::Constant *Elts = LV.getExtVectorElts();
1910 unsigned ix = getAccessedFieldNo(0, Elts);
Fangrui Song6907ce22018-07-30 19:24:48 +00001911
John McCall7f416cc2015-09-08 08:05:57 +00001912 Address VectorBasePtrPlusIx =
1913 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
John McCall7f416cc2015-09-08 08:05:57 +00001914 "vector.elt");
1915
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001916 return VectorBasePtrPlusIx;
1917}
1918
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001919/// Load of global gamed gegisters are always calls to intrinsics.
Renato Golin230c5eb2014-05-19 18:15:42 +00001920RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001921 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1922 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001923 llvm::MDNode *RegName = cast<llvm::MDNode>(
1924 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001925
1926 // We accept integer and pointer types only
1927 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1928 llvm::Type *Ty = OrigTy;
1929 if (OrigTy->isPointerTy())
1930 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1931 llvm::Type *Types[] = { Ty };
1932
James Y Knight8799cae2019-02-03 21:53:49 +00001933 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001934 llvm::Value *Call = Builder.CreateCall(
1935 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001936 if (OrigTy->isPointerTy())
1937 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001938 return RValue::get(Call);
1939}
Chris Lattner40ff7012007-08-03 16:18:34 +00001940
Chris Lattner9369a562007-06-29 16:31:29 +00001941
Chris Lattner8394d792007-06-05 20:53:16 +00001942/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1943/// lvalue, where both are guaranteed to the have the same type, and that type
1944/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001945void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001946 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001947 if (!Dst.isSimple()) {
1948 if (Dst.isVectorElt()) {
1949 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001950 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1951 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001952 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001953 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001954 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1955 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001956 return;
1957 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001958
Nate Begemance4d7fc2008-04-18 23:10:10 +00001959 // If this is an update of extended vector elements, insert them as
1960 // appropriate.
1961 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001962 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001963
Renato Golin230c5eb2014-05-19 18:15:42 +00001964 if (Dst.isGlobalReg())
1965 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1966
John McCallc109a252011-11-07 03:59:57 +00001967 assert(Dst.isBitField() && "Unknown LValue type");
1968 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001969 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001970
John McCall31168b02011-06-15 23:02:42 +00001971 // There's special magic for assigning into an ARC-qualified l-value.
1972 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1973 switch (Lifetime) {
1974 case Qualifiers::OCL_None:
1975 llvm_unreachable("present but none");
1976
1977 case Qualifiers::OCL_ExplicitNone:
1978 // nothing special
1979 break;
1980
1981 case Qualifiers::OCL_Strong:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001982 if (isInit) {
1983 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1984 break;
1985 }
John McCall55e1fbc2011-06-25 02:11:03 +00001986 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001987 return;
1988
1989 case Qualifiers::OCL_Weak:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001990 if (isInit)
1991 // Initialize and then skip the primitive store.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001992 EmitARCInitWeak(Dst.getAddress(*this), Src.getScalarVal());
Akira Hatanaka642f7992016-10-18 19:05:41 +00001993 else
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001994 EmitARCStoreWeak(Dst.getAddress(*this), Src.getScalarVal(),
1995 /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001996 return;
1997
1998 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001999 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
2000 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00002001 // fall into the normal path
2002 break;
2003 }
2004 }
2005
Fariborz Jahanian10bec102009-02-21 00:30:43 +00002006 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00002007 // load of a __weak object.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002008 Address LvalueDst = Dst.getAddress(*this);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00002009 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00002010 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00002011 return;
2012 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002013
Fariborz Jahanian10bec102009-02-21 00:30:43 +00002014 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00002015 // load of a __strong object.
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002016 Address LvalueDst = Dst.getAddress(*this);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00002017 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002018 if (Dst.isObjCIvar()) {
2019 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00002020 llvm::Type *ResultType = IntPtrTy;
2021 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
2022 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002023 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00002024 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00002025 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
2026 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002027 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00002028 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002029 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002030 } else if (Dst.isGlobalObjCRef()) {
2031 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
2032 Dst.isThreadLocalRef());
2033 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00002034 else
2035 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00002036 return;
2037 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002038
Chris Lattner6278e6a2007-08-11 00:04:45 +00002039 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00002040 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00002041}
2042
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00002043void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00002044 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00002045 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00002046 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00002047 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00002048
Daniel Dunbar67aba792010-04-15 03:47:33 +00002049 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00002050 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00002051
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002052 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00002053 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002054 /*isSigned=*/false);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002055 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00002056
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002057 // See if there are other bits in the bitfield's storage we'll need to load
2058 // and mask together with source before storing.
2059 if (Info.StorageSize != Info.Size) {
2060 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00002061 llvm::Value *Val =
2062 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002063
2064 // Mask the source value as needed.
2065 if (!hasBooleanRepresentation(Dst.getType()))
2066 SrcVal = Builder.CreateAnd(SrcVal,
2067 llvm::APInt::getLowBitsSet(Info.StorageSize,
2068 Info.Size),
2069 "bf.value");
2070 MaskedVal = SrcVal;
2071 if (Info.Offset)
2072 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
2073
2074 // Mask out the original value.
2075 Val = Builder.CreateAnd(Val,
2076 ~llvm::APInt::getBitsSet(Info.StorageSize,
2077 Info.Offset,
2078 Info.Offset + Info.Size),
2079 "bf.clear");
2080
2081 // Or together the unchanged values and the source value.
2082 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
2083 } else {
2084 assert(Info.Offset == 0);
Diogo Sampaio9d869182020-02-07 10:03:59 +00002085 // According to the AACPS:
2086 // When a volatile bit-field is written, and its container does not overlap
2087 // with any non-bit-field member, its container must be read exactly once and
2088 // written exactly once using the access width appropriate to the type of the
2089 // container. The two accesses are not atomic.
2090 if (Dst.isVolatileQualified() && isAAPCS(CGM.getTarget()) &&
2091 CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad)
2092 Builder.CreateLoad(Ptr, true, "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002093 }
2094
2095 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00002096 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00002097
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00002098 // Return the new value of the bit-field, if requested.
2099 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002100 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00002101
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002102 // Sign extend the value if needed.
2103 if (Info.IsSigned) {
2104 assert(Info.Size <= Info.StorageSize);
2105 unsigned HighBits = Info.StorageSize - Info.Size;
2106 if (HighBits) {
2107 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
2108 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
2109 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00002110 }
2111
Chandler Carruthff0e3a12012-12-06 11:14:44 +00002112 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
2113 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00002114 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00002115 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00002116}
2117
Nate Begemance4d7fc2008-04-18 23:10:10 +00002118void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00002119 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00002120 // This access turns into a read/modify/write of the vector. Load the input
2121 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00002122 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
2123 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00002124 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00002125
Chris Lattner4647a212007-08-31 22:49:20 +00002126 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00002127
John McCall55e1fbc2011-06-25 02:11:03 +00002128 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00002129 unsigned NumSrcElts = VTy->getNumElements();
Craig Topperf2f1a092016-07-08 02:17:35 +00002130 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00002131 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00002132 // Use shuffle vector is the src and destination are the same number of
2133 // elements and restore the vector mask since it is on the side it will be
2134 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002135 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002136 for (unsigned i = 0; i != NumSrcElts; ++i)
2137 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00002138
Chris Lattner91c08ad2011-02-15 00:14:06 +00002139 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00002140 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00002141 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002142 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00002143 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00002144 // Extended the source vector to the same length and then shuffle it
2145 // into the destination.
2146 // FIXME: since we're shuffling with undef, can we just use the indices
2147 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002148 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00002149 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002150 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00002151 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00002152 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00002153 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00002154 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00002155 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002156 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00002157 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002158 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002159 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002160 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002161
Joey Goulycf4143b2013-11-21 17:09:05 +00002162 // When the vector size is odd and .odd or .hi is used, the last element
2163 // of the Elts constant array will be one past the size of the vector.
2164 // Ignore the last element here, if it is greater than the mask size.
2165 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
2166 NumSrcElts--;
2167
Nate Begemanb699c9b2009-01-18 06:42:49 +00002168 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002169 for (unsigned i = 0; i != NumSrcElts; ++i)
2170 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00002171 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002172 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00002173 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00002174 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00002175 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00002176 }
2177 } else {
2178 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00002179 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00002180 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002181 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00002182 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002183
John McCall7f416cc2015-09-08 08:05:57 +00002184 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
2185 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00002186}
2187
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002188/// Store of global named registers are always calls to intrinsics.
Renato Golin230c5eb2014-05-19 18:15:42 +00002189void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00002190 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
2191 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002192 llvm::MDNode *RegName = cast<llvm::MDNode>(
2193 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00002194 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00002195
2196 // We accept integer and pointer types only
2197 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
2198 llvm::Type *Ty = OrigTy;
2199 if (OrigTy->isPointerTy())
2200 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2201 llvm::Type *Types[] = { Ty };
2202
James Y Knight8799cae2019-02-03 21:53:49 +00002203 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
Renato Golin230c5eb2014-05-19 18:15:42 +00002204 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00002205 if (OrigTy->isPointerTy())
2206 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00002207 Builder.CreateCall(
2208 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00002209}
2210
Eric Christopherc9e2a682014-05-20 17:10:39 +00002211// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002212// generating write-barries API. It is currently a global, ivar,
2213// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002214static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002215 LValue &LV,
2216 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002217 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002218 return;
Craig Topper99e79272013-07-26 05:59:26 +00002219
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002220 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002221 QualType ExpTy = E->getType();
2222 if (IsMemberAccess && ExpTy->isPointerType()) {
2223 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00002224 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002225 // writer-barrier conservatively.
Simon Pilgrim7e38f0c2019-10-07 16:42:25 +00002226 ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002227 if (ExpTy->isRecordType()) {
2228 LV.setObjCIvar(false);
2229 return;
2230 }
2231 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002232 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002233 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002234 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002235 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002236 return;
2237 }
Craig Topper99e79272013-07-26 05:59:26 +00002238
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002239 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
2240 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00002241 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002242 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00002243 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002244 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002245 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002246 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002247 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002248 }
Craig Topper99e79272013-07-26 05:59:26 +00002249
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002250 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002251 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002252 return;
2253 }
Craig Topper99e79272013-07-26 05:59:26 +00002254
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002255 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002256 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002257 if (LV.isObjCIvar()) {
2258 // If cast is to a structure pointer, follow gcc's behavior and make it
2259 // a non-ivar write-barrier.
2260 QualType ExpTy = E->getType();
2261 if (ExpTy->isPointerType())
Simon Pilgrim7e38f0c2019-10-07 16:42:25 +00002262 ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002263 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00002264 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002265 }
2266 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002267 }
Peter Collingbourne91147592011-04-15 00:35:48 +00002268
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002269 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00002270 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2271 return;
2272 }
2273
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002274 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002275 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002276 return;
2277 }
Craig Topper99e79272013-07-26 05:59:26 +00002278
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002279 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002280 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002281 return;
2282 }
John McCall31168b02011-06-15 23:02:42 +00002283
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002284 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002285 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00002286 return;
2287 }
2288
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002289 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002290 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00002291 if (LV.isObjCIvar() && !LV.isObjCArray())
2292 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002293 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00002294 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002295 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00002296 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002297 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002298 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002299 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002300 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002301
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002302 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002303 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002304 // We don't know if member is an 'ivar', but this flag is looked at
2305 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002306 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002307 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002308 }
2309}
2310
Chris Lattner3f32d692011-07-12 06:52:18 +00002311static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00002312EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00002313 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002314 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00002315 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00002316 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00002317}
2318
Alexey Bataev97720002014-11-11 04:05:39 +00002319static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00002320 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2321 llvm::Type *RealVarTy, SourceLocation Loc) {
2322 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2323 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002324 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
John McCall7f416cc2015-09-08 08:05:57 +00002325}
2326
Gheorghe-Teodor Bercea0034e842019-06-20 18:04:47 +00002327static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF,
2328 const VarDecl *VD, QualType T) {
Alexey Bataevd01b7492018-08-15 19:45:12 +00002329 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2330 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Gheorghe-Teodor Bercea0034e842019-06-20 18:04:47 +00002331 // Return an invalid address if variable is MT_To and unified
2332 // memory is not enabled. For all other cases: MT_Link and
2333 // MT_To with unified memory, return a valid address.
2334 if (!Res || (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2335 !CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory()))
Alexey Bataevd01b7492018-08-15 19:45:12 +00002336 return Address::invalid();
Gheorghe-Teodor Bercea0034e842019-06-20 18:04:47 +00002337 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
2338 (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2339 CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) &&
2340 "Expected link clause OR to clause with unified memory enabled.");
Alexey Bataevd01b7492018-08-15 19:45:12 +00002341 QualType PtrTy = CGF.getContext().getPointerType(VD->getType());
Gheorghe-Teodor Bercea0034e842019-06-20 18:04:47 +00002342 Address Addr = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
Alexey Bataevd01b7492018-08-15 19:45:12 +00002343 return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>());
Alexey Bataev92327c52018-03-26 16:40:55 +00002344}
2345
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002346Address
2347CodeGenFunction::EmitLoadOfReference(LValue RefLVal,
2348 LValueBaseInfo *PointeeBaseInfo,
2349 TBAAAccessInfo *PointeeTBAAInfo) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002350 llvm::LoadInst *Load =
2351 Builder.CreateLoad(RefLVal.getAddress(*this), RefLVal.isVolatile());
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00002352 CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002353
2354 CharUnits Align = getNaturalTypeAlignment(RefLVal.getType()->getPointeeType(),
2355 PointeeBaseInfo, PointeeTBAAInfo,
2356 /* forPointeeType= */ true);
2357 return Address(Load, Align);
John McCall7f416cc2015-09-08 08:05:57 +00002358}
2359
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002360LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) {
2361 LValueBaseInfo PointeeBaseInfo;
2362 TBAAAccessInfo PointeeTBAAInfo;
2363 Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
2364 &PointeeTBAAInfo);
2365 return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
2366 PointeeBaseInfo, PointeeTBAAInfo);
Alexey Bataev97720002014-11-11 04:05:39 +00002367}
2368
Alexey Bataev31300ed2016-02-04 11:27:03 +00002369Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2370 const PointerType *PtrTy,
Ivan A. Kosarev90295642017-10-13 16:47:22 +00002371 LValueBaseInfo *BaseInfo,
2372 TBAAAccessInfo *TBAAInfo) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00002373 llvm::Value *Addr = Builder.CreateLoad(Ptr);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002374 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(),
Ivan A. Kosarev78f486d2017-10-13 16:58:30 +00002375 BaseInfo, TBAAInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00002376 /*forPointeeType=*/true));
2377}
2378
2379LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2380 const PointerType *PtrTy) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002381 LValueBaseInfo BaseInfo;
Ivan A. Kosarev90295642017-10-13 16:47:22 +00002382 TBAAAccessInfo TBAAInfo;
2383 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
2384 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00002385}
2386
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002387static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2388 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00002389 QualType T = E->getType();
2390
2391 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00002392 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
Richard Smith00223822019-09-12 20:00:24 +00002393 CGF.CGM.getCXXABI().usesThreadWrapperFunction(VD))
Richard Smith0f383742014-03-26 22:48:22 +00002394 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
Alexey Bataev92327c52018-03-26 16:40:55 +00002395 // Check if the variable is marked as declare target with link clause in
2396 // device codegen.
2397 if (CGF.getLangOpts().OpenMPIsDevice) {
Gheorghe-Teodor Bercea0034e842019-06-20 18:04:47 +00002398 Address Addr = emitDeclTargetVarDeclLValue(CGF, VD, T);
Alexey Bataev92327c52018-03-26 16:40:55 +00002399 if (Addr.isValid())
2400 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2401 }
Richard Smith0f383742014-03-26 22:48:22 +00002402
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002403 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002404 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2405 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00002406 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00002407 Address Addr(V, Alignment);
Alexey Bataev97720002014-11-11 04:05:39 +00002408 // Emit reference to the private copy of the variable if it is an OpenMP
2409 // threadprivate variable.
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00002410 if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
2411 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
John McCall7f416cc2015-09-08 08:05:57 +00002412 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002413 E->getExprLoc());
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00002414 }
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002415 LValue LV = VD->getType()->isReferenceType() ?
2416 CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
2417 AlignmentSource::Decl) :
2418 CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002419 setObjCGCLValueClass(CGF.getContext(), E, LV);
2420 return LV;
2421}
2422
John McCallb92ab1a2016-10-26 23:46:34 +00002423static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
Yaxun (Sam) Liu29e1a162020-03-05 12:02:13 -05002424 GlobalDecl GD) {
2425 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
John McCallb92ab1a2016-10-26 23:46:34 +00002426 if (FD->hasAttr<WeakRefAttr>()) {
2427 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2428 return aliasee.getPointer();
2429 }
2430
Yaxun (Sam) Liu29e1a162020-03-05 12:02:13 -05002431 llvm::Constant *V = CGM.GetAddrOfFunction(GD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002432 if (!FD->hasPrototype()) {
2433 if (const FunctionProtoType *Proto =
2434 FD->getType()->getAs<FunctionProtoType>()) {
2435 // Ugly case: for a K&R-style definition, the type of the definition
2436 // isn't the same as the type of a use. Correct for this with a
2437 // bitcast.
2438 QualType NoProtoType =
John McCallb92ab1a2016-10-26 23:46:34 +00002439 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2440 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2441 V = llvm::ConstantExpr::getBitCast(V,
2442 CGM.getTypes().ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002443 }
2444 }
John McCallb92ab1a2016-10-26 23:46:34 +00002445 return V;
2446}
2447
Yaxun (Sam) Liu29e1a162020-03-05 12:02:13 -05002448static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E,
2449 GlobalDecl GD) {
2450 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2451 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, GD);
Eli Friedmana0544d62011-12-03 04:14:32 +00002452 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002453 return CGF.MakeAddrLValue(V, E->getType(), Alignment,
2454 AlignmentSource::Decl);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002455}
2456
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00002457static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2458 llvm::Value *ThisValue) {
2459 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2460 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2461 return CGF.EmitLValueForField(LV, FD);
2462}
2463
Renato Golin230c5eb2014-05-19 18:15:42 +00002464/// Named Registers are named metadata pointing to the register name
2465/// which will be read from/written to as an argument to the intrinsic
2466/// @llvm.read/write_register.
2467/// So far, only the name is being passed down, but other options such as
2468/// register type, allocation type or even optimization options could be
2469/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002470static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002471 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002472 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002473 assert(Asm->getLabel().size() < 64-Name.size() &&
2474 "Register name too big");
2475 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002476 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002477 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002478 if (M->getNumOperands() == 0) {
2479 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2480 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002481 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002482 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2483 }
John McCall7f416cc2015-09-08 08:05:57 +00002484
2485 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2486
2487 llvm::Value *Ptr =
2488 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2489 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002490}
2491
Richard Smith24cdcad2019-06-14 17:46:37 +00002492/// Determine whether we can emit a reference to \p VD from the current
2493/// context, despite not necessarily having seen an odr-use of the variable in
2494/// this context.
2495static bool canEmitSpuriousReferenceToVariable(CodeGenFunction &CGF,
2496 const DeclRefExpr *E,
2497 const VarDecl *VD,
2498 bool IsConstant) {
2499 // For a variable declared in an enclosing scope, do not emit a spurious
2500 // reference even if we have a capture, as that will emit an unwarranted
2501 // reference to our capture state, and will likely generate worse code than
2502 // emitting a local copy.
2503 if (E->refersToEnclosingVariableOrCapture())
2504 return false;
2505
2506 // For a local declaration declared in this function, we can always reference
2507 // it even if we don't have an odr-use.
2508 if (VD->hasLocalStorage()) {
2509 return VD->getDeclContext() ==
2510 dyn_cast_or_null<DeclContext>(CGF.CurCodeDecl);
2511 }
2512
2513 // For a global declaration, we can emit a reference to it if we know
2514 // for sure that we are able to emit a definition of it.
2515 VD = VD->getDefinition(CGF.getContext());
2516 if (!VD)
2517 return false;
2518
2519 // Don't emit a spurious reference if it might be to a variable that only
2520 // exists on a different device / target.
2521 // FIXME: This is unnecessarily broad. Check whether this would actually be a
2522 // cross-target reference.
2523 if (CGF.getLangOpts().OpenMP || CGF.getLangOpts().CUDA ||
2524 CGF.getLangOpts().OpenCL) {
2525 return false;
2526 }
2527
2528 // We can emit a spurious reference only if the linkage implies that we'll
2529 // be emitting a non-interposable symbol that will be retained until link
2530 // time.
2531 switch (CGF.CGM.getLLVMLinkageVarDefinition(VD, IsConstant)) {
2532 case llvm::GlobalValue::ExternalLinkage:
2533 case llvm::GlobalValue::LinkOnceODRLinkage:
2534 case llvm::GlobalValue::WeakODRLinkage:
2535 case llvm::GlobalValue::InternalLinkage:
2536 case llvm::GlobalValue::PrivateLinkage:
2537 return true;
2538 default:
2539 return false;
2540 }
2541}
2542
Chris Lattnerd7f58862007-06-02 05:24:33 +00002543LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002544 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002545 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002546
Richard Smith24cdcad2019-06-14 17:46:37 +00002547 assert(E->isNonOdrUse() != NOUR_Unevaluated &&
2548 "should not emit an unevaluated operand");
2549
Renato Goline7b3d5d2014-05-27 16:46:27 +00002550 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2551 // Global Named registers access via intrinsics only
2552 if (VD->getStorageClass() == SC_Register &&
2553 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002554 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002555
Richard Smith24cdcad2019-06-14 17:46:37 +00002556 // If this DeclRefExpr does not constitute an odr-use of the variable,
2557 // we're not permitted to emit a reference to it in general, and it might
2558 // not be captured if capture would be necessary for a use. Emit the
2559 // constant value directly instead.
2560 if (E->isNonOdrUse() == NOUR_Constant &&
2561 (VD->getType()->isReferenceType() ||
2562 !canEmitSpuriousReferenceToVariable(*this, E, VD, true))) {
2563 VD->getAnyInitializer(VD);
2564 llvm::Constant *Val = ConstantEmitter(*this).emitAbstract(
2565 E->getLocation(), *VD->evaluateValue(), VD->getType());
2566 assert(Val && "failed to emit constant expression");
John McCall7f416cc2015-09-08 08:05:57 +00002567
Richard Smith24cdcad2019-06-14 17:46:37 +00002568 Address Addr = Address::invalid();
2569 if (!VD->getType()->isReferenceType()) {
2570 // Spill the constant value to a global.
2571 Addr = CGM.createUnnamedGlobalFrom(*VD, Val,
2572 getContext().getDeclAlign(VD));
Alexey Bataevb5890a32019-09-10 19:16:56 +00002573 llvm::Type *VarTy = getTypes().ConvertTypeForMem(VD->getType());
2574 auto *PTy = llvm::PointerType::get(
2575 VarTy, getContext().getTargetAddressSpace(VD->getType()));
2576 if (PTy != Addr.getType())
2577 Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy);
Richard Smith24cdcad2019-06-14 17:46:37 +00002578 } else {
2579 // Should we be using the alignment of the constant pointer we emitted?
2580 CharUnits Alignment =
2581 getNaturalTypeAlignment(E->getType(),
2582 /* BaseInfo= */ nullptr,
2583 /* TBAAInfo= */ nullptr,
2584 /* forPointeeType= */ true);
2585 Addr = Address(Val, Alignment);
2586 }
2587 return MakeAddrLValue(Addr, T, AlignmentSource::Decl);
Richard Smith5a1104b2012-10-20 01:38:33 +00002588 }
David Majnemer602cfe72015-01-01 09:49:44 +00002589
Richard Smith715f7a12019-06-11 17:50:32 +00002590 // FIXME: Handle other kinds of non-odr-use DeclRefExprs.
2591
David Majnemer602cfe72015-01-01 09:49:44 +00002592 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002593 if (E->refersToEnclosingVariableOrCapture()) {
Alexey Bataev6a71f362017-08-22 17:54:52 +00002594 VD = VD->getCanonicalDecl();
David Majnemer602cfe72015-01-01 09:49:44 +00002595 if (auto *FD = LambdaCaptureFields.lookup(VD))
2596 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
Alexey Bataev0860db92019-12-19 10:01:10 -05002597 if (CapturedStmtInfo) {
Alexey Bataevac5eabb2016-11-07 11:16:04 +00002598 auto I = LocalDeclMap.find(VD);
2599 if (I != LocalDeclMap.end()) {
Alexey Bataev0860db92019-12-19 10:01:10 -05002600 LValue CapLVal;
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002601 if (VD->getType()->isReferenceType())
Alexey Bataev0860db92019-12-19 10:01:10 -05002602 CapLVal = EmitLoadOfReferenceLValue(I->second, VD->getType(),
2603 AlignmentSource::Decl);
2604 else
2605 CapLVal = MakeAddrLValue(I->second, T);
2606 // Mark lvalue as nontemporal if the variable is marked as nontemporal
2607 // in simd context.
2608 if (getLangOpts().OpenMP &&
2609 CGM.getOpenMPRuntime().isNontemporalDecl(VD))
2610 CapLVal.setNontemporal(/*Value=*/true);
2611 return CapLVal;
Alexey Bataevcaacd532015-09-04 11:26:21 +00002612 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002613 LValue CapLVal =
2614 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2615 CapturedStmtInfo->getContextValue());
Alexey Bataev0860db92019-12-19 10:01:10 -05002616 CapLVal = MakeAddrLValue(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002617 Address(CapLVal.getPointer(*this), getContext().getDeclAlign(VD)),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00002618 CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl),
2619 CapLVal.getTBAAInfo());
Alexey Bataev0860db92019-12-19 10:01:10 -05002620 // Mark lvalue as nontemporal if the variable is marked as nontemporal
2621 // in simd context.
2622 if (getLangOpts().OpenMP &&
2623 CGM.getOpenMPRuntime().isNontemporalDecl(VD))
2624 CapLVal.setNontemporal(/*Value=*/true);
2625 return CapLVal;
David Majnemer602cfe72015-01-01 09:49:44 +00002626 }
John McCall7f416cc2015-09-08 08:05:57 +00002627
David Majnemer602cfe72015-01-01 09:49:44 +00002628 assert(isa<BlockDecl>(CurCodeDecl));
Akira Hatanaka8e57b072018-10-01 21:51:28 +00002629 Address addr = GetAddrOfBlockDecl(VD);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002630 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002631 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002632 }
2633
Eli Friedman5720e342012-01-21 04:52:58 +00002634 // FIXME: We should be able to assert this for FunctionDecls as well!
2635 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2636 // those with a valid source location.
Richard Smith24cdcad2019-06-14 17:46:37 +00002637 assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() ||
Eli Friedman5720e342012-01-21 04:52:58 +00002638 !E->getLocation().isValid()) &&
2639 "Should not use decl without marking it used!");
2640
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002641 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002642 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002643 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002644 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002645 }
2646
Renato Goline7b3d5d2014-05-27 16:46:27 +00002647 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002648 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002649 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002650 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002651
John McCall7f416cc2015-09-08 08:05:57 +00002652 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002653
John McCall7f416cc2015-09-08 08:05:57 +00002654 // The variable should generally be present in the local decl map.
2655 auto iter = LocalDeclMap.find(VD);
2656 if (iter != LocalDeclMap.end()) {
2657 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002658
John McCall7f416cc2015-09-08 08:05:57 +00002659 // Otherwise, it might be static local we haven't emitted yet for
2660 // some reason; most likely, because it's in an outer function.
2661 } else if (VD->isStaticLocal()) {
2662 addr = Address(CGM.getOrCreateStaticVarDecl(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00002663 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false)),
John McCall7f416cc2015-09-08 08:05:57 +00002664 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002665
John McCall7f416cc2015-09-08 08:05:57 +00002666 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002667 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002668 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2669 }
2670
2671
2672 // Check for OpenMP threadprivate variables.
Alexey Bataeva8a9153a2017-12-29 18:07:07 +00002673 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
2674 VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
John McCall7f416cc2015-09-08 08:05:57 +00002675 return EmitThreadPrivateVarDeclLValue(
2676 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2677 E->getExprLoc());
2678 }
2679
2680 // Drill into block byref variables.
Akira Hatanaka8e57b072018-10-01 21:51:28 +00002681 bool isBlockByref = VD->isEscapingByref();
John McCall7f416cc2015-09-08 08:05:57 +00002682 if (isBlockByref) {
2683 addr = emitBlockByrefAddress(addr, VD);
2684 }
2685
2686 // Drill into reference types.
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00002687 LValue LV = VD->getType()->isReferenceType() ?
2688 EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) :
2689 MakeAddrLValue(addr, T, AlignmentSource::Decl);
Chris Lattner3f32d692011-07-12 06:52:18 +00002690
John McCallcdda29c2013-03-13 03:10:54 +00002691 bool isLocalStorage = VD->hasLocalStorage();
2692
2693 bool NonGCable = isLocalStorage &&
2694 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002695 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002696 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002697 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002698 LV.setNonGC(true);
2699 }
John McCallcdda29c2013-03-13 03:10:54 +00002700
2701 bool isImpreciseLifetime =
2702 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2703 if (isImpreciseLifetime)
2704 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002705 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002706 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002707 }
John McCallf3a88602011-02-03 08:15:49 +00002708
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002709 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002710 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002711
Richard Smithda383632016-08-15 01:33:41 +00002712 // FIXME: While we're emitting a binding from an enclosing scope, all other
2713 // DeclRefExprs we see should be implicitly treated as if they also refer to
2714 // an enclosing scope.
2715 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2716 return EmitLValue(BD->getBinding());
2717
David Blaikie83d382b2011-09-23 05:06:16 +00002718 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002719}
Chris Lattnere47e4402007-06-01 18:02:12 +00002720
Chris Lattner8394d792007-06-05 20:53:16 +00002721LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2722 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002723 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002724 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002725
Chris Lattner0f398c42008-07-26 22:37:01 +00002726 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002727 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002728 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002729 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002730 QualType T = E->getSubExpr()->getType()->getPointeeType();
2731 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002732
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002733 LValueBaseInfo BaseInfo;
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00002734 TBAAAccessInfo TBAAInfo;
2735 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo,
2736 &TBAAInfo);
2737 LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002738 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002739
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002740 // We should not generate __weak write barrier on indirect reference
2741 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2742 // But, we continue to generate __strong write barrier on indirect write
2743 // into a pointer to object.
Erik Pilkingtonfa983902018-10-30 20:31:30 +00002744 if (getLangOpts().ObjC &&
Richard Smith9c6890a2012-11-01 22:30:59 +00002745 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002746 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002747 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002748 return LV;
2749 }
John McCalle3027922010-08-25 11:45:40 +00002750 case UO_Real:
2751 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002752 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002753 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002754
Richard Smith0b6b8e42012-02-18 20:53:32 +00002755 // __real is valid on scalars. This is a faster way of testing that.
2756 // __imag can only produce an rvalue on scalars.
2757 if (E->getOpcode() == UO_Real &&
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002758 !LV.getAddress(*this).getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002759 assert(E->getSubExpr()->getType()->isArithmeticType());
2760 return LV;
2761 }
2762
Alexey Bataev611b0a12016-11-07 18:15:02 +00002763 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
John McCalla2342eb2010-12-05 02:00:02 +00002764
John McCall7f416cc2015-09-08 08:05:57 +00002765 Address Component =
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002766 (E->getOpcode() == UO_Real
2767 ? emitAddrOfRealComponent(LV.getAddress(*this), LV.getType())
2768 : emitAddrOfImagComponent(LV.getAddress(*this), LV.getType()));
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00002769 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00002770 CGM.getTBAAInfoForSubobject(LV, T));
Alexey Bataev611b0a12016-11-07 18:15:02 +00002771 ElemLV.getQuals().addQualifiers(LV.getQuals());
2772 return ElemLV;
Chris Lattner595db862007-10-30 22:53:42 +00002773 }
John McCalle3027922010-08-25 11:45:40 +00002774 case UO_PreInc:
2775 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002776 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002777 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002778
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002779 if (E->getType()->isAnyComplexType())
2780 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2781 else
2782 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2783 return LV;
2784 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002785 }
Chris Lattner8394d792007-06-05 20:53:16 +00002786}
2787
Chris Lattner4347e3692007-06-06 04:54:52 +00002788LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002789 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002790 E->getType(), AlignmentSource::Decl);
Chris Lattner4347e3692007-06-06 04:54:52 +00002791}
2792
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002793LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002794 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002795 E->getType(), AlignmentSource::Decl);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002796}
2797
Mike Stump4a3999f2009-09-09 13:00:44 +00002798LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002799 auto SL = E->getFunctionName();
2800 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2801 StringRef FnName = CurFn->getName();
2802 if (FnName.startswith("\01"))
2803 FnName = FnName.substr(1);
2804 StringRef NameItems[] = {
Bruno Ricci17ff0262018-10-27 19:21:19 +00002805 PredefinedExpr::getIdentKindName(E->getIdentKind()), FnName};
Alexey Bataevec474782014-10-09 08:45:04 +00002806 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Shoaib Meenai34aa1312018-04-11 18:17:35 +00002807 if (auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl)) {
Benjamin Krameradcd0262020-01-28 20:23:46 +01002808 std::string Name = std::string(SL->getString());
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002809 if (!Name.empty()) {
2810 unsigned Discriminator =
2811 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2812 if (Discriminator)
2813 Name += "_" + Twine(Discriminator + 1).str();
2814 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002815 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002816 } else {
Benjamin Krameradcd0262020-01-28 20:23:46 +01002817 auto C =
2818 CGM.GetAddrOfConstantCString(std::string(FnName), GVName.c_str());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002819 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002820 }
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002821 }
Alexey Bataevec474782014-10-09 08:45:04 +00002822 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00002823 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002824}
2825
Richard Smithe30752c2012-10-09 19:52:38 +00002826/// Emit a type description suitable for use by a runtime sanitizer library. The
2827/// format of a type descriptor is
2828///
2829/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002830/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002831/// \endcode
2832///
Richard Smith683398a2012-10-09 23:55:19 +00002833/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2834/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002835llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002836 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002837 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002838 return C;
2839
Richard Smithe30752c2012-10-09 19:52:38 +00002840 uint16_t TypeKind = -1;
2841 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002842
Richard Smithe30752c2012-10-09 19:52:38 +00002843 if (T->isIntegerType()) {
2844 TypeKind = 0;
2845 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002846 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002847 } else if (T->isFloatingType()) {
2848 TypeKind = 1;
2849 TypeInfo = getContext().getTypeSize(T);
2850 }
2851
2852 // Format the type name as if for a diagnostic, including quotes and
2853 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002854 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002855 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2856 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002857 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002858 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002859
2860 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002861 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2862 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002863 };
2864 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2865
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002866 auto *GV = new llvm::GlobalVariable(
2867 CGM.getModule(), Descriptor->getType(),
2868 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002869 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002870 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002871
2872 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002873 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002874
Richard Smithe30752c2012-10-09 19:52:38 +00002875 return GV;
2876}
2877
2878llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2879 llvm::Type *TargetTy = IntPtrTy;
2880
Vedant Kumar8a715332017-10-03 01:27:24 +00002881 if (V->getType() == TargetTy)
2882 return V;
2883
Richard Smith48366f72013-03-22 00:47:07 +00002884 // Floating-point types which fit into intptr_t are bitcast to integers
2885 // and then passed directly (after zero-extension, if necessary).
2886 if (V->getType()->isFloatingPointTy()) {
2887 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2888 if (Bits <= TargetTy->getIntegerBitWidth())
2889 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2890 Bits));
2891 }
2892
Richard Smithe30752c2012-10-09 19:52:38 +00002893 // Integers which fit in intptr_t are zero-extended and passed directly.
2894 if (V->getType()->isIntegerTy() &&
2895 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2896 return Builder.CreateZExt(V, TargetTy);
2897
2898 // Pointers are passed directly, everything else is passed by address.
2899 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002900 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002901 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002902 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002903 }
2904 return Builder.CreatePtrToInt(V, TargetTy);
2905}
2906
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002907/// Emit a representation of a SourceLocation for passing to a handler
Richard Smithe30752c2012-10-09 19:52:38 +00002908/// in a sanitizer runtime library. The format for this data is:
2909/// \code
2910/// struct SourceLocation {
2911/// const char *Filename;
2912/// int32_t Line, Column;
2913/// };
2914/// \endcode
2915/// For an invalid SourceLocation, the Filename pointer is null.
2916llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002917 llvm::Constant *Filename;
2918 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002919
Alexey Samsonov6c124142014-07-18 17:50:06 +00002920 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2921 if (PLoc.isValid()) {
Filipe Cabecinhasab731f72016-05-12 16:51:36 +00002922 StringRef FilenameString = PLoc.getFilename();
2923
2924 int PathComponentsToStrip =
2925 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2926 if (PathComponentsToStrip < 0) {
2927 assert(PathComponentsToStrip != INT_MIN);
2928 int PathComponentsToKeep = -PathComponentsToStrip;
2929 auto I = llvm::sys::path::rbegin(FilenameString);
2930 auto E = llvm::sys::path::rend(FilenameString);
2931 while (I != E && --PathComponentsToKeep)
2932 ++I;
2933
2934 FilenameString = FilenameString.substr(I - E);
2935 } else if (PathComponentsToStrip > 0) {
2936 auto I = llvm::sys::path::begin(FilenameString);
2937 auto E = llvm::sys::path::end(FilenameString);
2938 while (I != E && PathComponentsToStrip--)
2939 ++I;
2940
2941 if (I != E)
2942 FilenameString =
2943 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2944 else
2945 FilenameString = llvm::sys::path::filename(FilenameString);
2946 }
2947
Benjamin Krameradcd0262020-01-28 20:23:46 +01002948 auto FilenameGV =
2949 CGM.GetAddrOfConstantCString(std::string(FilenameString), ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002950 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2951 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2952 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002953 Line = PLoc.getLine();
2954 Column = PLoc.getColumn();
2955 } else {
2956 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2957 Line = Column = 0;
2958 }
2959
2960 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2961 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002962
2963 return llvm::ConstantStruct::getAnon(Data);
2964}
2965
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002966namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002967/// Specify under what conditions this check can be recovered
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002968enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002969 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002970 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002971 /// Check supports recovering, runtime has both fatal (noreturn) and
2972 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002973 Recoverable,
2974 /// Runtime conditionally aborts, always need to support recovery.
2975 AlwaysRecoverable
2976};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002977}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002978
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002979static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
Pierre Gousseauae5303d2019-03-01 10:05:15 +00002980 assert(Kind.countPopulation() == 1);
Stephan Bergmanne2159962019-07-16 06:23:27 +00002981 if (Kind == SanitizerKind::Function || Kind == SanitizerKind::Vptr)
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002982 return CheckRecoverableKind::AlwaysRecoverable;
Pierre Gousseauae5303d2019-03-01 10:05:15 +00002983 else if (Kind == SanitizerKind::Return || Kind == SanitizerKind::Unreachable)
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002984 return CheckRecoverableKind::Unrecoverable;
Pierre Gousseauae5303d2019-03-01 10:05:15 +00002985 else
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002986 return CheckRecoverableKind::Recoverable;
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002987}
2988
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002989namespace {
2990struct SanitizerHandlerInfo {
2991 char const *const Name;
2992 unsigned Version;
2993};
Saleem Abdulrasoolca6e2b42016-12-13 03:27:35 +00002994}
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002995
2996const SanitizerHandlerInfo SanitizerHandlers[] = {
2997#define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2998 LIST_SANITIZER_CHECKS
2999#undef SANITIZER_CHECK
3000};
3001
Alexey Samsonov88459522015-01-12 22:39:12 +00003002static void emitCheckHandlerCall(CodeGenFunction &CGF,
3003 llvm::FunctionType *FnType,
3004 ArrayRef<llvm::Value *> FnArgs,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00003005 SanitizerHandler CheckHandler,
Alexey Samsonov88459522015-01-12 22:39:12 +00003006 CheckRecoverableKind RecoverKind, bool IsFatal,
3007 llvm::BasicBlock *ContBB) {
3008 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
Adrian Prantlc9f24732018-11-28 21:44:06 +00003009 Optional<ApplyDebugLocation> DL;
3010 if (!CGF.Builder.getCurrentDebugLocation()) {
3011 // Ensure that the call has at least an artificial debug location.
3012 DL.emplace(CGF, SourceLocation());
3013 }
Alexey Samsonov88459522015-01-12 22:39:12 +00003014 bool NeedsAbortSuffix =
3015 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00003016 bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00003017 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
3018 const StringRef CheckName = CheckInfo.Name;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00003019 std::string FnName = "__ubsan_handle_" + CheckName.str();
3020 if (CheckInfo.Version && !MinimalRuntime)
3021 FnName += "_v" + llvm::utostr(CheckInfo.Version);
3022 if (MinimalRuntime)
3023 FnName += "_minimal";
3024 if (NeedsAbortSuffix)
3025 FnName += "_abort";
Alexey Samsonov88459522015-01-12 22:39:12 +00003026 bool MayReturn =
3027 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
3028
3029 llvm::AttrBuilder B;
3030 if (!MayReturn) {
3031 B.addAttribute(llvm::Attribute::NoReturn)
3032 .addAttribute(llvm::Attribute::NoUnwind);
3033 }
3034 B.addAttribute(llvm::Attribute::UWTable);
3035
James Y Knight9871db02019-02-05 16:42:33 +00003036 llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(
Alexey Samsonov88459522015-01-12 22:39:12 +00003037 FnType, FnName,
Reid Klecknerde864822017-03-21 16:57:30 +00003038 llvm::AttributeList::get(CGF.getLLVMContext(),
3039 llvm::AttributeList::FunctionIndex, B),
Saleem Abdulrasool05b8fde2016-12-15 16:30:20 +00003040 /*Local=*/true);
Alexey Samsonov88459522015-01-12 22:39:12 +00003041 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
3042 if (!MayReturn) {
3043 HandlerCall->setDoesNotReturn();
3044 CGF.Builder.CreateUnreachable();
3045 } else {
3046 CGF.Builder.CreateBr(ContBB);
3047 }
3048}
3049
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003050void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00003051 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00003052 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003053 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003054 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003055 assert(Checked.size() > 0);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00003056 assert(CheckHandler >= 0 &&
Zachary Turner260fe3e2017-12-14 22:07:03 +00003057 size_t(CheckHandler) < llvm::array_lengthof(SanitizerHandlers));
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00003058 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
Alexey Samsonov88459522015-01-12 22:39:12 +00003059
3060 llvm::Value *FatalCond = nullptr;
3061 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00003062 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00003063 for (int i = 0, n = Checked.size(); i < n; ++i) {
3064 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00003065 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00003066 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00003067 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
3068 ? TrapCond
3069 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
3070 ? RecoverableCond
3071 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00003072 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
3073 }
3074
Peter Collingbourne9881b782015-06-18 23:59:22 +00003075 if (TrapCond)
3076 EmitTrapCheck(TrapCond);
3077 if (!FatalCond && !RecoverableCond)
3078 return;
3079
Alexey Samsonov88459522015-01-12 22:39:12 +00003080 llvm::Value *JointCond;
3081 if (FatalCond && RecoverableCond)
3082 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
3083 else
3084 JointCond = FatalCond ? FatalCond : RecoverableCond;
3085 assert(JointCond);
3086
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003087 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00003088 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00003089#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003090 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003091 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00003092 "All recoverable kinds in a single check must be same!");
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00003093 assert(SanOpts.has(Checked[i].second));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003094 }
Alexey Samsonov88459522015-01-12 22:39:12 +00003095#endif
Chad Rosierae229d52013-01-29 23:31:22 +00003096
Richard Smith4d1458e2012-09-08 02:08:36 +00003097 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00003098 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
3099 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00003100 // Give hint that we very much don't expect to execute the handler
3101 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
3102 llvm::MDBuilder MDHelper(getLLVMContext());
3103 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
3104 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00003105 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00003106
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003107 // Handler functions take an i8* pointing to the (handler-specific) static
3108 // information block, followed by a sequence of intptr_t arguments
3109 // representing operand values.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003110 SmallVector<llvm::Value *, 4> Args;
3111 SmallVector<llvm::Type *, 4> ArgTypes;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00003112 if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
3113 Args.reserve(DynamicArgs.size() + 1);
3114 ArgTypes.reserve(DynamicArgs.size() + 1);
Richard Smithe30752c2012-10-09 19:52:38 +00003115
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00003116 // Emit handler arguments and create handler function type.
3117 if (!StaticArgs.empty()) {
3118 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
3119 auto *InfoPtr =
3120 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
3121 llvm::GlobalVariable::PrivateLinkage, Info);
3122 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3123 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
3124 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
3125 ArgTypes.push_back(Int8PtrTy);
3126 }
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003127
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00003128 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
3129 Args.push_back(EmitCheckValue(DynamicArgs[i]));
3130 ArgTypes.push_back(IntPtrTy);
3131 }
Richard Smithe30752c2012-10-09 19:52:38 +00003132 }
3133
3134 llvm::FunctionType *FnType =
3135 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00003136
Alexey Samsonov88459522015-01-12 22:39:12 +00003137 if (!FatalCond || !RecoverableCond) {
3138 // Simple case: we need to generate a single handler call, either
3139 // fatal, or non-fatal.
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00003140 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
Alexey Samsonov88459522015-01-12 22:39:12 +00003141 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00003142 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00003143 // Emit two handler calls: first one for set of unrecoverable checks,
3144 // another one for recoverable.
3145 llvm::BasicBlock *NonFatalHandlerBB =
3146 createBasicBlock("non_fatal." + CheckName);
3147 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
3148 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
3149 EmitBlock(FatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00003150 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
Alexey Samsonov88459522015-01-12 22:39:12 +00003151 NonFatalHandlerBB);
3152 EmitBlock(NonFatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00003153 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
Alexey Samsonov88459522015-01-12 22:39:12 +00003154 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00003155 }
Richard Smithe30752c2012-10-09 19:52:38 +00003156
Richard Smith4d1458e2012-09-08 02:08:36 +00003157 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00003158}
3159
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003160void CodeGenFunction::EmitCfiSlowPathCheck(
3161 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
3162 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00003163 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
3164
3165 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
3166 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
3167
3168 llvm::MDBuilder MDHelper(getLLVMContext());
3169 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
3170 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
3171
3172 EmitBlock(CheckBB);
3173
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003174 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
3175
3176 llvm::CallInst *CheckCall;
James Y Knight13680222019-02-01 02:28:03 +00003177 llvm::FunctionCallee SlowPathFn;
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003178 if (WithDiag) {
3179 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
3180 auto *InfoPtr =
3181 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
3182 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00003183 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003184 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
3185
Rafael Espindolab2c47fb2018-03-29 22:08:01 +00003186 SlowPathFn = CGM.getModule().getOrInsertFunction(
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003187 "__cfi_slowpath_diag",
3188 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
3189 false));
3190 CheckCall = Builder.CreateCall(
Rafael Espindolab2c47fb2018-03-29 22:08:01 +00003191 SlowPathFn, {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003192 } else {
Rafael Espindolab2c47fb2018-03-29 22:08:01 +00003193 SlowPathFn = CGM.getModule().getOrInsertFunction(
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003194 "__cfi_slowpath",
3195 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
3196 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
3197 }
3198
James Y Knight13680222019-02-01 02:28:03 +00003199 CGM.setDSOLocal(
3200 cast<llvm::GlobalValue>(SlowPathFn.getCallee()->stripPointerCasts()));
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00003201 CheckCall->setDoesNotThrow();
3202
3203 EmitBlock(Cont);
3204}
3205
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +00003206// Emit a stub for __cfi_check function so that the linker knows about this
3207// symbol in LTO mode.
3208void CodeGenFunction::EmitCfiCheckStub() {
3209 llvm::Module *M = &CGM.getModule();
3210 auto &Ctx = M->getContext();
3211 llvm::Function *F = llvm::Function::Create(
3212 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
3213 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
Rafael Espindola54d44bf2018-03-29 20:51:30 +00003214 CGM.setDSOLocal(F);
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +00003215 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
3216 // FIXME: consider emitting an intrinsic call like
3217 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
3218 // which can be lowered in CrossDSOCFI pass to the actual contents of
3219 // __cfi_check. This would allow inlining of __cfi_check calls.
3220 llvm::CallInst::Create(
3221 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
3222 llvm::ReturnInst::Create(Ctx, nullptr, BB);
3223}
3224
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003225// This function is basically a switch over the CFI failure kind, which is
3226// extracted from CFICheckFailData (1st function argument). Each case is either
3227// llvm.trap or a call to one of the two runtime handlers, based on
3228// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
3229// failure kind) traps, but this should really never happen. CFICheckFailData
3230// can be nullptr if the calling module has -fsanitize-trap behavior for this
3231// check kind; in this case __cfi_check_fail traps as well.
3232void CodeGenFunction::EmitCfiCheckFail() {
3233 SanitizerScope SanScope(this);
3234 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00003235 ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
3236 ImplicitParamDecl::Other);
3237 ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
3238 ImplicitParamDecl::Other);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003239 Args.push_back(&ArgData);
3240 Args.push_back(&ArgAddr);
3241
John McCallc56a8b32016-03-11 04:30:31 +00003242 const CGFunctionInfo &FI =
3243 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003244
3245 llvm::Function *F = llvm::Function::Create(
3246 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
3247 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
Peter Collingbourne90b8bc02019-11-25 12:28:11 -08003248
3249 CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F);
3250 CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003251 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
3252
3253 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
3254 SourceLocation());
3255
Evgeniy Stepanovfb762b22018-06-21 23:22:37 +00003256 // This function should not be affected by blacklist. This function does
3257 // not have a source location, but "src:*" would still apply. Revert any
3258 // changes to SanOpts made in StartFunction.
3259 SanOpts = CGM.getLangOpts().Sanitize;
3260
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003261 llvm::Value *Data =
3262 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
3263 CGM.getContext().VoidPtrTy, ArgData.getLocation());
3264 llvm::Value *Addr =
3265 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
3266 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
3267
3268 // Data == nullptr means the calling module has trap behaviour for this check.
3269 llvm::Value *DataIsNotNullPtr =
3270 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
3271 EmitTrapCheck(DataIsNotNullPtr);
3272
3273 llvm::StructType *SourceLocationTy =
Serge Guelton1d993272017-05-09 19:31:30 +00003274 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003275 llvm::StructType *CfiCheckFailDataTy =
Serge Guelton1d993272017-05-09 19:31:30 +00003276 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003277
3278 llvm::Value *V = Builder.CreateConstGEP2_32(
3279 CfiCheckFailDataTy,
3280 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
3281 0);
3282 Address CheckKindAddr(V, getIntAlign());
3283 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
3284
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00003285 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
3286 CGM.getLLVMContext(),
3287 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
3288 llvm::Value *ValidVtable = Builder.CreateZExt(
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00003289 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00003290 {Addr, AllVtables}),
3291 IntPtrTy);
3292
Evgeniy Stepanov4d3b0872016-01-25 23:45:37 +00003293 const std::pair<int, SanitizerMask> CheckKinds[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003294 {CFITCK_VCall, SanitizerKind::CFIVCall},
3295 {CFITCK_NVCall, SanitizerKind::CFINVCall},
3296 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
3297 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
3298 {CFITCK_ICall, SanitizerKind::CFIICall}};
3299
3300 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
3301 for (auto CheckKindMaskPair : CheckKinds) {
3302 int Kind = CheckKindMaskPair.first;
3303 SanitizerMask Mask = CheckKindMaskPair.second;
3304 llvm::Value *Cond =
3305 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00003306 if (CGM.getLangOpts().Sanitize.has(Mask))
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00003307 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00003308 {Data, Addr, ValidVtable});
3309 else
3310 EmitTrapCheck(Cond);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003311 }
3312
3313 FinishFunction();
3314 // The only reference to this function will be created during LTO link.
3315 // Make sure it survives until then.
3316 CGM.addUsedGlobal(F);
3317}
3318
Vedant Kumar09b5bfd2017-12-21 00:10:25 +00003319void CodeGenFunction::EmitUnreachable(SourceLocation Loc) {
3320 if (SanOpts.has(SanitizerKind::Unreachable)) {
3321 SanitizerScope SanScope(this);
3322 EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()),
3323 SanitizerKind::Unreachable),
3324 SanitizerHandler::BuiltinUnreachable,
3325 EmitCheckSourceLocation(Loc), None);
3326 }
3327 Builder.CreateUnreachable();
3328}
3329
Chad Rosierae229d52013-01-29 23:31:22 +00003330void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00003331 llvm::BasicBlock *Cont = createBasicBlock("cont");
3332
3333 // If we're optimizing, collapse all calls to trap down to just one per
3334 // function to save on code size.
3335 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
3336 TrapBB = createBasicBlock("trap");
3337 Builder.CreateCondBr(Checked, Cont, TrapBB);
3338 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003339 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00003340 TrapCall->setDoesNotReturn();
3341 TrapCall->setDoesNotThrow();
3342 Builder.CreateUnreachable();
3343 } else {
3344 Builder.CreateCondBr(Checked, Cont, TrapBB);
3345 }
3346
3347 EmitBlock(Cont);
3348}
3349
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003350llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00003351 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003352
Amaury Sechet21f51b32016-09-09 04:42:49 +00003353 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3354 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3355 CGM.getCodeGenOpts().TrapFuncName);
Reid Klecknerde864822017-03-21 16:57:30 +00003356 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
Amaury Sechet21f51b32016-09-09 04:42:49 +00003357 }
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003358
3359 return TrapCall;
3360}
3361
John McCall7f416cc2015-09-08 08:05:57 +00003362Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003363 LValueBaseInfo *BaseInfo,
3364 TBAAAccessInfo *TBAAInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00003365 assert(E->getType()->isArrayType() &&
3366 "Array to pointer decay must have array source type!");
3367
3368 // Expressions of array type can't be bitfields or vector elements.
3369 LValue LV = EmitLValue(E);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003370 Address Addr = LV.getAddress(*this);
John McCall7f416cc2015-09-08 08:05:57 +00003371
3372 // If the array type was an incomplete type, we need to make sure
3373 // the decay ends up being the right type.
3374 llvm::Type *NewTy = ConvertType(E->getType());
3375 Addr = Builder.CreateElementBitCast(Addr, NewTy);
3376
3377 // Note that VLA pointers are always decayed, so we don't need to do
3378 // anything here.
3379 if (!E->getType()->isVariableArrayType()) {
3380 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3381 "Expected pointer to array");
James Y Knightf5f1b0e2019-02-08 15:34:12 +00003382 Addr = Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
John McCall7f416cc2015-09-08 08:05:57 +00003383 }
3384
Ivan A. Kosarevf761d0e2017-10-20 12:35:17 +00003385 // The result of this decay conversion points to an array element within the
3386 // base lvalue. However, since TBAA currently does not support representing
3387 // accesses to elements of member arrays, we conservatively represent accesses
3388 // to the pointee object as if it had no any base lvalue specified.
3389 // TODO: Support TBAA for member arrays.
John McCall7f416cc2015-09-08 08:05:57 +00003390 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
Ivan A. Kosarevf761d0e2017-10-20 12:35:17 +00003391 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
3392 if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
3393
John McCall7f416cc2015-09-08 08:05:57 +00003394 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
3395}
3396
Chris Lattner6c5abe82010-06-26 23:03:20 +00003397/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
3398/// array to pointer, return the array subexpression.
3399static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
3400 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003401 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00003402 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00003403 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00003404
Chris Lattner6c5abe82010-06-26 23:03:20 +00003405 // If this is a decay from variable width array, bail out.
3406 const Expr *SubExpr = CE->getSubExpr();
3407 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00003408 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00003409
Chris Lattner6c5abe82010-06-26 23:03:20 +00003410 return SubExpr;
3411}
3412
John McCall7f416cc2015-09-08 08:05:57 +00003413static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3414 llvm::Value *ptr,
3415 ArrayRef<llvm::Value*> indices,
3416 bool inbounds,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003417 bool signedIndices,
Vedant Kumara125eb52017-06-01 19:22:18 +00003418 SourceLocation loc,
John McCall7f416cc2015-09-08 08:05:57 +00003419 const llvm::Twine &name = "arrayidx") {
3420 if (inbounds) {
Vedant Kumar175b6d12017-07-13 20:55:26 +00003421 return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices,
3422 CodeGenFunction::NotSubtraction, loc,
3423 name);
John McCall7f416cc2015-09-08 08:05:57 +00003424 } else {
3425 return CGF.Builder.CreateGEP(ptr, indices, name);
3426 }
3427}
3428
3429static CharUnits getArrayElementAlign(CharUnits arrayAlign,
3430 llvm::Value *idx,
3431 CharUnits eltSize) {
3432 // If we have a constant index, we can use the exact offset of the
3433 // element we're accessing.
3434 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3435 CharUnits offset = constantIdx->getZExtValue() * eltSize;
3436 return arrayAlign.alignmentAtOffset(offset);
3437
3438 // Otherwise, use the worst-case alignment for any element.
3439 } else {
3440 return arrayAlign.alignmentOfArrayElement(eltSize);
3441 }
3442}
3443
3444static QualType getFixedSizeElementType(const ASTContext &ctx,
3445 const VariableArrayType *vla) {
3446 QualType eltType;
3447 do {
3448 eltType = vla->getElementType();
3449 } while ((vla = ctx.getAsVariableArrayType(eltType)));
3450 return eltType;
3451}
3452
Yonghong Song4e2ce222019-11-01 22:16:59 -07003453/// Given an array base, check whether its member access belongs to a record
3454/// with preserve_access_index attribute or not.
3455static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase) {
3456 if (!ArrayBase || !CGF.getDebugInfo())
3457 return false;
3458
Yonghong Song4e2ce222019-11-01 22:16:59 -07003459 // Only support base as either a MemberExpr or DeclRefExpr.
3460 // DeclRefExpr to cover cases like:
3461 // struct s { int a; int b[10]; };
3462 // struct s *p;
3463 // p[1].a
3464 // p[1] will generate a DeclRefExpr and p[1].a is a MemberExpr.
3465 // p->b[5] is a MemberExpr example.
Yonghong Songdd16b3f2019-11-14 10:34:35 -08003466 const Expr *E = ArrayBase->IgnoreImpCasts();
3467 if (const auto *ME = dyn_cast<MemberExpr>(E))
3468 return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
Yonghong Song4e2ce222019-11-01 22:16:59 -07003469
Yonghong Songdd16b3f2019-11-14 10:34:35 -08003470 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3471 const auto *VarDef = dyn_cast<VarDecl>(DRE->getDecl());
Yonghong Song4e2ce222019-11-01 22:16:59 -07003472 if (!VarDef)
3473 return false;
3474
Yonghong Songdd16b3f2019-11-14 10:34:35 -08003475 const auto *PtrT = VarDef->getType()->getAs<PointerType>();
Yonghong Song4e2ce222019-11-01 22:16:59 -07003476 if (!PtrT)
3477 return false;
Yonghong Song4e2ce222019-11-01 22:16:59 -07003478
Yonghong Songdd16b3f2019-11-14 10:34:35 -08003479 const auto *PointeeT = PtrT->getPointeeType()
3480 ->getUnqualifiedDesugaredType();
3481 if (const auto *RecT = dyn_cast<RecordType>(PointeeT))
3482 return RecT->getDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
3483 return false;
Yonghong Song4e2ce222019-11-01 22:16:59 -07003484 }
3485
3486 return false;
3487}
3488
John McCall7f416cc2015-09-08 08:05:57 +00003489static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
Vedant Kumara125eb52017-06-01 19:22:18 +00003490 ArrayRef<llvm::Value *> indices,
John McCall7f416cc2015-09-08 08:05:57 +00003491 QualType eltType, bool inbounds,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003492 bool signedIndices, SourceLocation loc,
Yonghong Songd0ea05d2019-08-02 21:28:28 +00003493 QualType *arrayType = nullptr,
Yonghong Song4e2ce222019-11-01 22:16:59 -07003494 const Expr *Base = nullptr,
John McCall7f416cc2015-09-08 08:05:57 +00003495 const llvm::Twine &name = "arrayidx") {
3496 // All the indices except that last must be zero.
3497#ifndef NDEBUG
3498 for (auto idx : indices.drop_back())
3499 assert(isa<llvm::ConstantInt>(idx) &&
3500 cast<llvm::ConstantInt>(idx)->isZero());
Fangrui Song6907ce22018-07-30 19:24:48 +00003501#endif
John McCall7f416cc2015-09-08 08:05:57 +00003502
3503 // Determine the element size of the statically-sized base. This is
3504 // the thing that the indices are expressed in terms of.
3505 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3506 eltType = getFixedSizeElementType(CGF.getContext(), vla);
3507 }
3508
3509 // We can use that to compute the best alignment of the element.
3510 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3511 CharUnits eltAlign =
3512 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3513
Yonghong Song048493f2019-07-09 04:21:50 +00003514 llvm::Value *eltPtr;
3515 auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back());
Yonghong Song4e2ce222019-11-01 22:16:59 -07003516 if (!LastIndex ||
3517 (!CGF.IsInPreservedAIRegion && !IsPreserveAIArrayBase(CGF, Base))) {
Yonghong Song048493f2019-07-09 04:21:50 +00003518 eltPtr = emitArraySubscriptGEP(
3519 CGF, addr.getPointer(), indices, inbounds, signedIndices,
3520 loc, name);
3521 } else {
3522 // Remember the original array subscript for bpf target
3523 unsigned idx = LastIndex->getZExtValue();
Yonghong Songd0ea05d2019-08-02 21:28:28 +00003524 llvm::DIType *DbgInfo = nullptr;
3525 if (arrayType)
3526 DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(*arrayType, loc);
Craig Topper910718b2019-11-03 09:30:08 -08003527 eltPtr = CGF.Builder.CreatePreserveArrayAccessIndex(addr.getElementType(),
3528 addr.getPointer(),
Yonghong Song048493f2019-07-09 04:21:50 +00003529 indices.size() - 1,
Yonghong Songd0ea05d2019-08-02 21:28:28 +00003530 idx, DbgInfo);
Yonghong Song048493f2019-07-09 04:21:50 +00003531 }
3532
John McCall7f416cc2015-09-08 08:05:57 +00003533 return Address(eltPtr, eltAlign);
3534}
3535
Richard Smith539e4a72013-02-23 02:53:19 +00003536LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3537 bool Accessed) {
Richard Smith9e67b992016-09-26 23:49:47 +00003538 // The index must always be an integer, which is not an aggregate. Emit it
3539 // in lexical order (this complexity is, sadly, required by C++17).
3540 llvm::Value *IdxPre =
3541 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003542 bool SignedIndices = false;
Richard Smith40885712016-09-27 00:53:24 +00003543 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
Richard Smith9e67b992016-09-26 23:49:47 +00003544 auto *Idx = IdxPre;
3545 if (E->getLHS() != E->getIdx()) {
3546 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3547 Idx = EmitScalarExpr(E->getIdx());
3548 }
Eli Friedman07bbeca2009-06-06 19:09:26 +00003549
Richard Smith9e67b992016-09-26 23:49:47 +00003550 QualType IdxTy = E->getIdx()->getType();
3551 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003552 SignedIndices |= IdxSigned;
Richard Smith9e67b992016-09-26 23:49:47 +00003553
3554 if (SanOpts.has(SanitizerKind::ArrayBounds))
3555 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3556
3557 // Extend or truncate the index type to 32 or 64-bits.
3558 if (Promote && Idx->getType() != IntPtrTy)
3559 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3560
3561 return Idx;
3562 };
3563 IdxPre = nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +00003564
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003565 // If the base is a vector type, then we are forming a vector element lvalue
3566 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003567 if (E->getBase()->getType()->isVectorType() &&
3568 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003569 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00003570 LValue LHS = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003571 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
Ted Kremenekc81614d2007-08-20 16:18:38 +00003572 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003573 return LValue::MakeVectorElt(LHS.getAddress(*this), Idx,
3574 E->getBase()->getType(), LHS.getBaseInfo(),
3575 TBAAAccessInfo());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003576 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003577
John McCall7f416cc2015-09-08 08:05:57 +00003578 // All the other cases basically behave like simple offsetting.
3579
John McCall7f416cc2015-09-08 08:05:57 +00003580 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003581 if (isa<ExtVectorElementExpr>(E->getBase())) {
3582 LValue LV = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003583 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003584 Address Addr = EmitExtVectorElementLValue(LV);
3585
3586 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
Vedant Kumara125eb52017-06-01 19:22:18 +00003587 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003588 SignedIndices, E->getExprLoc());
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00003589 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003590 CGM.getTBAAInfoForSubobject(LV, EltType));
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003591 }
John McCall7f416cc2015-09-08 08:05:57 +00003592
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003593 LValueBaseInfo EltBaseInfo;
3594 TBAAAccessInfo EltTBAAInfo;
John McCall7f416cc2015-09-08 08:05:57 +00003595 Address Addr = Address::invalid();
3596 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003597 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00003598 // The base must be a pointer, which is not an aggregate. Emit
3599 // it. It needs to be emitted first in case it's what captures
3600 // the VLA bounds.
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003601 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003602 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Mike Stump4a3999f2009-09-09 13:00:44 +00003603
John McCall23c29fe2011-06-24 21:55:10 +00003604 // The element count here is the total number of non-VLA elements.
Sander de Smalen891af03a2018-02-03 13:55:59 +00003605 llvm::Value *numElements = getVLASize(vla).NumElts;
Mike Stump4a3999f2009-09-09 13:00:44 +00003606
John McCall77527a82011-06-25 01:32:37 +00003607 // Effectively, the multiply by the VLA size is part of the GEP.
3608 // GEP indexes are signed, and scaling an index isn't permitted to
3609 // signed-overflow, so we use the same semantics for our explicit
3610 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003611 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00003612 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003613 } else {
3614 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003615 }
John McCall7f416cc2015-09-08 08:05:57 +00003616
3617 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003618 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003619 SignedIndices, E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00003620
Chris Lattner6c5abe82010-06-26 23:03:20 +00003621 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3622 // Indexing over an interface, as in "NSString *P; P[4];"
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003623
John McCall7f416cc2015-09-08 08:05:57 +00003624 // Emit the base pointer.
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003625 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003626 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3627
3628 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3629 llvm::Value *InterfaceSizeVal =
3630 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3631
3632 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
John McCall7f416cc2015-09-08 08:05:57 +00003633
3634 // We don't necessarily build correct LLVM struct types for ObjC
3635 // interfaces, so we can't rely on GEP to do this scaling
3636 // correctly, so we need to cast to i8*. FIXME: is this actually
3637 // true? A lot of other things in the fragile ABI would break...
3638 llvm::Type *OrigBaseTy = Addr.getType();
3639 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3640
3641 // Do the GEP.
3642 CharUnits EltAlign =
3643 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003644 llvm::Value *EltPtr =
3645 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false,
3646 SignedIndices, E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00003647 Addr = Address(EltPtr, EltAlign);
3648
3649 // Cast back.
3650 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00003651 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3652 // If this is A[i] where A is an array, the frontend will have decayed the
3653 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3654 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3655 // "gep x, i" here. Emit one "gep A, 0, i".
3656 assert(Array->getType()->isArrayType() &&
3657 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00003658 LValue ArrayLV;
3659 // For simple multidimensional array indexing, set the 'accessed' flag for
3660 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003661 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00003662 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3663 else
3664 ArrayLV = EmitLValue(Array);
Richard Smith9e67b992016-09-26 23:49:47 +00003665 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Craig Topper99e79272013-07-26 05:59:26 +00003666
Daniel Dunbar82634272011-04-01 00:49:43 +00003667 // Propagate the alignment from the array itself to the result.
Yonghong Songd0ea05d2019-08-02 21:28:28 +00003668 QualType arrayType = Array->getType();
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003669 Addr = emitArraySubscriptGEP(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003670 *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003671 E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
Yonghong Song4e2ce222019-11-01 22:16:59 -07003672 E->getExprLoc(), &arrayType, E->getBase());
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003673 EltBaseInfo = ArrayLV.getBaseInfo();
3674 EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003675 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003676 // The base must be a pointer; emit it with an estimate of its alignment.
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003677 Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003678 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Yonghong Songd0ea05d2019-08-02 21:28:28 +00003679 QualType ptrType = E->getBase()->getType();
John McCall7f416cc2015-09-08 08:05:57 +00003680 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003681 !getLangOpts().isSignedOverflowDefined(),
Yonghong Song4e2ce222019-11-01 22:16:59 -07003682 SignedIndices, E->getExprLoc(), &ptrType,
3683 E->getBase());
Anders Carlsson3d312f82008-12-21 00:11:23 +00003684 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003685
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003686 LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
John McCall8ccfcb52009-09-24 19:53:00 +00003687
Erik Pilkingtonfa983902018-10-30 20:31:30 +00003688 if (getLangOpts().ObjC &&
Richard Smith9c6890a2012-11-01 22:30:59 +00003689 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00003690 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00003691 setObjCGCLValueClass(getContext(), E, LV);
3692 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00003693 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00003694}
3695
Alexey Bataev31300ed2016-02-04 11:27:03 +00003696static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003697 LValueBaseInfo &BaseInfo,
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003698 TBAAAccessInfo &TBAAInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003699 QualType BaseTy, QualType ElTy,
3700 bool IsLowerBound) {
3701 LValue BaseLVal;
3702 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3703 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3704 if (BaseTy->isArrayType()) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003705 Address Addr = BaseLVal.getAddress(CGF);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003706 BaseInfo = BaseLVal.getBaseInfo();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003707
3708 // If the array type was an incomplete type, we need to make sure
3709 // the decay ends up being the right type.
3710 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3711 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3712
3713 // Note that VLA pointers are always decayed, so we don't need to do
3714 // anything here.
3715 if (!BaseTy->isVariableArrayType()) {
3716 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3717 "Expected pointer to array");
James Y Knightf5f1b0e2019-02-08 15:34:12 +00003718 Addr = CGF.Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
Alexey Bataev31300ed2016-02-04 11:27:03 +00003719 }
3720
3721 return CGF.Builder.CreateElementBitCast(Addr,
3722 CGF.ConvertTypeForMem(ElTy));
3723 }
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003724 LValueBaseInfo TypeBaseInfo;
3725 TBAAAccessInfo TypeTBAAInfo;
3726 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &TypeBaseInfo,
3727 &TypeTBAAInfo);
3728 BaseInfo.mergeForCast(TypeBaseInfo);
3729 TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003730 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress(CGF)), Align);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003731 }
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003732 return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003733}
3734
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003735LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3736 bool IsLowerBound) {
Alexey Bataev7b0f1f02017-10-12 15:18:41 +00003737 QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(E->getBase());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003738 QualType ResultExprTy;
3739 if (auto *AT = getContext().getAsArrayType(BaseTy))
3740 ResultExprTy = AT->getElementType();
3741 else
3742 ResultExprTy = BaseTy->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003743 llvm::Value *Idx = nullptr;
Benjamin Kramer5ff67472016-04-11 08:26:13 +00003744 if (IsLowerBound || E->getColonLoc().isInvalid()) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003745 // Requesting lower bound or upper bound, but without provided length and
3746 // without ':' symbol for the default length -> length = 1.
3747 // Idx = LowerBound ?: 0;
3748 if (auto *LowerBound = E->getLowerBound()) {
3749 Idx = Builder.CreateIntCast(
3750 EmitScalarExpr(LowerBound), IntPtrTy,
3751 LowerBound->getType()->hasSignedIntegerRepresentation());
3752 } else
3753 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3754 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003755 // Try to emit length or lower bound as constant. If this is possible, 1
3756 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3757 // IR (LB + Len) - 1.
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003758 auto &C = CGM.getContext();
3759 auto *Length = E->getLength();
3760 llvm::APSInt ConstLength;
3761 if (Length) {
3762 // Idx = LowerBound + Length - 1;
3763 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3764 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3765 Length = nullptr;
3766 }
3767 auto *LowerBound = E->getLowerBound();
3768 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3769 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3770 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3771 LowerBound = nullptr;
3772 }
3773 if (!Length)
3774 --ConstLength;
3775 else if (!LowerBound)
3776 --ConstLowerBound;
3777
3778 if (Length || LowerBound) {
3779 auto *LowerBoundVal =
3780 LowerBound
3781 ? Builder.CreateIntCast(
3782 EmitScalarExpr(LowerBound), IntPtrTy,
3783 LowerBound->getType()->hasSignedIntegerRepresentation())
3784 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3785 auto *LengthVal =
3786 Length
3787 ? Builder.CreateIntCast(
3788 EmitScalarExpr(Length), IntPtrTy,
3789 Length->getType()->hasSignedIntegerRepresentation())
3790 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3791 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3792 /*HasNUW=*/false,
3793 !getLangOpts().isSignedOverflowDefined());
3794 if (Length && LowerBound) {
3795 Idx = Builder.CreateSub(
3796 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3797 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3798 }
3799 } else
3800 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3801 } else {
3802 // Idx = ArraySize - 1;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003803 QualType ArrayTy = BaseTy->isPointerType()
3804 ? E->getBase()->IgnoreParenImpCasts()->getType()
3805 : BaseTy;
3806 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003807 Length = VAT->getSizeExpr();
3808 if (Length->isIntegerConstantExpr(ConstLength, C))
3809 Length = nullptr;
3810 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003811 auto *CAT = C.getAsConstantArrayType(ArrayTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003812 ConstLength = CAT->getSize();
3813 }
3814 if (Length) {
3815 auto *LengthVal = Builder.CreateIntCast(
3816 EmitScalarExpr(Length), IntPtrTy,
3817 Length->getType()->hasSignedIntegerRepresentation());
3818 Idx = Builder.CreateSub(
3819 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3820 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3821 } else {
3822 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3823 --ConstLength;
3824 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3825 }
3826 }
3827 }
3828 assert(Idx);
3829
Alexey Bataev31300ed2016-02-04 11:27:03 +00003830 Address EltPtr = Address::invalid();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003831 LValueBaseInfo BaseInfo;
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003832 TBAAAccessInfo TBAAInfo;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003833 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003834 // The base must be a pointer, which is not an aggregate. Emit
3835 // it. It needs to be emitted first in case it's what captures
3836 // the VLA bounds.
3837 Address Base =
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003838 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
3839 BaseTy, VLA->getElementType(), IsLowerBound);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003840 // The element count here is the total number of non-VLA elements.
Sander de Smalen891af03a2018-02-03 13:55:59 +00003841 llvm::Value *NumElements = getVLASize(VLA).NumElts;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003842
3843 // Effectively, the multiply by the VLA size is part of the GEP.
3844 // GEP indexes are signed, and scaling an index isn't permitted to
3845 // signed-overflow, so we use the same semantics for our explicit
3846 // multiply. We suppress this if overflow is not undefined behavior.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003847 if (getLangOpts().isSignedOverflowDefined())
3848 Idx = Builder.CreateMul(Idx, NumElements);
3849 else
3850 Idx = Builder.CreateNSWMul(Idx, NumElements);
3851 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003852 !getLangOpts().isSignedOverflowDefined(),
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003853 /*signedIndices=*/false, E->getExprLoc());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003854 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3855 // If this is A[i] where A is an array, the frontend will have decayed the
3856 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3857 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3858 // "gep x, i" here. Emit one "gep A, 0, i".
3859 assert(Array->getType()->isArrayType() &&
3860 "Array to pointer decay must have array source type!");
3861 LValue ArrayLV;
3862 // For simple multidimensional array indexing, set the 'accessed' flag for
3863 // better bounds-checking of the base expression.
3864 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3865 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3866 else
3867 ArrayLV = EmitLValue(Array);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003868
Alexey Bataev31300ed2016-02-04 11:27:03 +00003869 // Propagate the alignment from the array itself to the result.
3870 EltPtr = emitArraySubscriptGEP(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003871 *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
Vedant Kumara125eb52017-06-01 19:22:18 +00003872 ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003873 /*signedIndices=*/false, E->getExprLoc());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003874 BaseInfo = ArrayLV.getBaseInfo();
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00003875 TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003876 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003877 Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003878 TBAAInfo, BaseTy, ResultExprTy,
3879 IsLowerBound);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003880 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
Vedant Kumara125eb52017-06-01 19:22:18 +00003881 !getLangOpts().isSignedOverflowDefined(),
Rui Ueyama49a3ad22019-07-16 04:46:31 +00003882 /*signedIndices=*/false, E->getExprLoc());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003883 }
3884
Ivan A. Kosarevcbee2192017-10-13 17:34:18 +00003885 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003886}
3887
Chris Lattner9e751ca2007-08-02 23:37:31 +00003888LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00003889EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00003890 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003891 LValue Base;
3892
3893 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00003894 if (E->isArrow()) {
3895 // If it is a pointer to a vector, emit the address and form an lvalue with
3896 // it.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003897 LValueBaseInfo BaseInfo;
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003898 TBAAAccessInfo TBAAInfo;
3899 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
Simon Pilgrim16c53ff2020-01-11 15:33:25 +00003900 const auto *PT = E->getBase()->getType()->castAs<PointerType>();
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003901 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
Daniel Dunbarf166a522010-08-21 03:44:13 +00003902 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00003903 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00003904 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3905 // emit the base as an lvalue.
3906 assert(E->getBase()->getType()->isVectorType());
3907 Base = EmitLValue(E->getBase());
3908 } else {
3909 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00003910 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00003911 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00003912 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00003913
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00003914 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00003915 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00003916 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00003917 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00003918 AlignmentSource::Decl);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003919 }
John McCall1553b192011-06-16 04:16:24 +00003920
3921 QualType type =
3922 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00003923
Nate Begemand3862152008-05-13 21:03:02 +00003924 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00003925 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00003926 E->getEncodedElementAccess(Indices);
3927
3928 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00003929 llvm::Constant *CV =
3930 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003931 return LValue::MakeExtVectorElt(Base.getAddress(*this), CV, type,
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00003932 Base.getBaseInfo(), TBAAAccessInfo());
Nate Begemand3862152008-05-13 21:03:02 +00003933 }
3934 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3935
3936 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003937 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00003938
Chris Lattner595ba3a2012-01-30 06:20:36 +00003939 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3940 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00003941 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00003942 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00003943 Base.getBaseInfo(), TBAAAccessInfo());
Chris Lattner9e751ca2007-08-02 23:37:31 +00003944}
3945
Devang Patel30efa2e2007-10-23 20:28:39 +00003946LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Alex Lorenz6cc83172017-08-25 10:07:00 +00003947 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
3948 EmitIgnoredExpr(E->getBase());
3949 return EmitDeclRefLValue(DRE);
3950 }
3951
Devang Pateld68df202007-10-24 22:26:28 +00003952 Expr *BaseExpr = E->getBase();
Chris Lattner4e4186b2007-12-02 18:52:07 +00003953 // 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 +00003954 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00003955 if (E->isArrow()) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003956 LValueBaseInfo BaseInfo;
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003957 TBAAAccessInfo TBAAInfo;
3958 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
Richard Smith69d0d262012-08-24 00:54:33 +00003959 QualType PtrTy = BaseExpr->getType()->getPointeeType();
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003960 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00003961 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
3962 if (IsBaseCXXThis)
3963 SkippedChecks.set(SanitizerKind::Alignment, true);
3964 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003965 SkippedChecks.set(SanitizerKind::Null, true);
3966 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
3967 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
Ivan A. Kosareved141ba2017-10-17 09:12:13 +00003968 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
Richard Smith69d0d262012-08-24 00:54:33 +00003969 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003970 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003971
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003972 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003973 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003974 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003975 setObjCGCLValueClass(getContext(), E, LV);
Alexey Bataev0860db92019-12-19 10:01:10 -05003976 if (getLangOpts().OpenMP) {
3977 // If the member was explicitly marked as nontemporal, mark it as
3978 // nontemporal. If the base lvalue is marked as nontemporal, mark access
3979 // to children as nontemporal too.
3980 if ((IsWrappedCXXThis(BaseExpr) &&
3981 CGM.getOpenMPRuntime().isNontemporalDecl(Field)) ||
3982 BaseLV.isNontemporal())
3983 LV.setNontemporal(/*Value=*/true);
3984 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003985 return LV;
3986 }
Craig Topper99e79272013-07-26 05:59:26 +00003987
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003988 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003989 return EmitFunctionDeclLValue(*this, E, FD);
3990
David Blaikie83d382b2011-09-23 05:06:16 +00003991 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003992}
Devang Patel30efa2e2007-10-23 20:28:39 +00003993
John McCalldec348f72013-05-03 07:33:41 +00003994/// Given that we are currently emitting a lambda, emit an l-value for
3995/// one of its members.
3996LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3997 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3998 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3999 QualType LambdaTagType =
4000 getContext().getTagDeclType(Field->getParent());
4001 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
4002 return EmitLValueForField(LambdaLV, Field);
4003}
4004
Yonghong Song47548142019-07-16 17:24:33 +00004005/// Get the field index in the debug info. The debug info structure/union
4006/// will ignore the unnamed bitfields.
4007unsigned CodeGenFunction::getDebugInfoFIndex(const RecordDecl *Rec,
4008 unsigned FieldIndex) {
4009 unsigned I = 0, Skipped = 0;
4010
4011 for (auto F : Rec->getDefinition()->fields()) {
4012 if (I == FieldIndex)
4013 break;
4014 if (F->isUnnamedBitfield())
4015 Skipped++;
4016 I++;
4017 }
4018
4019 return FieldIndex - Skipped;
4020}
4021
Richard Smith78b239e2019-06-20 20:44:45 +00004022/// Get the address of a zero-sized field within a record. The resulting
4023/// address doesn't necessarily have the right type.
4024static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base,
4025 const FieldDecl *Field) {
4026 CharUnits Offset = CGF.getContext().toCharUnitsFromBits(
4027 CGF.getContext().getFieldOffset(Field));
4028 if (Offset.isZero())
4029 return Base;
4030 Base = CGF.Builder.CreateElementBitCast(Base, CGF.Int8Ty);
4031 return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
4032}
4033
John McCall7f416cc2015-09-08 08:05:57 +00004034/// Drill down to the storage of a field without walking into
4035/// reference types.
4036///
4037/// The resulting address doesn't necessarily have the right type.
4038static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
4039 const FieldDecl *field) {
Richard Smith78b239e2019-06-20 20:44:45 +00004040 if (field->isZeroSize(CGF.getContext()))
4041 return emitAddrOfZeroSizeField(CGF, base, field);
4042
John McCall7f416cc2015-09-08 08:05:57 +00004043 const RecordDecl *rec = field->getParent();
Fangrui Song6907ce22018-07-30 19:24:48 +00004044
John McCall7f416cc2015-09-08 08:05:57 +00004045 unsigned idx =
4046 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
4047
James Y Knight751fe282019-02-09 22:22:28 +00004048 return CGF.Builder.CreateStructGEP(base, idx, field->getName());
John McCall7f416cc2015-09-08 08:05:57 +00004049}
4050
Yonghong Song9271cab2020-02-02 14:54:16 -08004051static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base,
4052 Address addr, const FieldDecl *field) {
Yonghong Song048493f2019-07-09 04:21:50 +00004053 const RecordDecl *rec = field->getParent();
Yonghong Song9271cab2020-02-02 14:54:16 -08004054 llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(
4055 base.getType(), rec->getLocation());
Yonghong Song048493f2019-07-09 04:21:50 +00004056
4057 unsigned idx =
4058 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
4059
4060 return CGF.Builder.CreatePreserveStructAccessIndex(
Yonghong Song9271cab2020-02-02 14:54:16 -08004061 addr, idx, CGF.getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo);
Yonghong Song048493f2019-07-09 04:21:50 +00004062}
4063
Piotr Padlewskic1d26062017-06-01 18:39:34 +00004064static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
4065 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
4066 if (!RD)
4067 return false;
4068
4069 if (RD->isDynamicClass())
4070 return true;
4071
4072 for (const auto &Base : RD->bases())
4073 if (hasAnyVptr(Base.getType(), Context))
4074 return true;
4075
4076 for (const FieldDecl *Field : RD->fields())
4077 if (hasAnyVptr(Field->getType(), Context))
4078 return true;
4079
4080 return false;
4081}
4082
Eli Friedman7f1ff602012-04-16 03:54:45 +00004083LValue CodeGenFunction::EmitLValueForField(LValue base,
4084 const FieldDecl *field) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004085 LValueBaseInfo BaseInfo = base.getBaseInfo();
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00004086
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00004087 if (field->isBitField()) {
4088 const CGRecordLayout &RL =
Diogo Sampaio21477032020-01-21 15:31:33 +00004089 CGM.getTypes().getCGRecordLayout(field->getParent());
4090 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004091 Address Addr = base.getAddress(*this);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00004092 unsigned Idx = RL.getLLVMFieldNo(field);
Yonghong Song4e2ce222019-11-01 22:16:59 -07004093 const RecordDecl *rec = field->getParent();
4094 if (!IsInPreservedAIRegion &&
4095 (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
Yonghong Song05e46972019-10-08 18:23:17 +00004096 if (Idx != 0)
4097 // For structs, we GEP to the field that the record layout suggests.
4098 Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
4099 } else {
Yonghong Song05e46972019-10-08 18:23:17 +00004100 llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType(
4101 getContext().getRecordType(rec), rec->getLocation());
4102 Addr = Builder.CreatePreserveStructAccessIndex(Addr, Idx,
4103 getDebugInfoFIndex(rec, field->getFieldIndex()),
4104 DbgInfo);
4105 }
4106
Chandler Carruthff0e3a12012-12-06 11:14:44 +00004107 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00004108 llvm::Type *FieldIntTy =
4109 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
4110 if (Addr.getElementType() != FieldIntTy)
4111 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00004112
Diogo Sampaio21477032020-01-21 15:31:33 +00004113 QualType fieldType =
4114 field->getType().withCVRQualifiers(base.getVRQualifiers());
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00004115 // TODO: Support TBAA for bit fields.
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004116 LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
Diogo Sampaio21477032020-01-21 15:31:33 +00004117 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
Ivan A. Kosarevd17f12a2017-10-17 10:17:43 +00004118 TBAAAccessInfo());
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00004119 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004120
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00004121 // Fields of may-alias structures are may-alias themselves.
4122 // FIXME: this should get propagated down through anonymous structs
4123 // and unions.
4124 QualType FieldType = field->getType();
4125 const RecordDecl *rec = field->getParent();
4126 AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004127 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00004128 TBAAAccessInfo FieldTBAAInfo;
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004129 if (base.getTBAAInfo().isMayAlias() ||
4130 rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
4131 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
Hal Finkela5986b92017-12-03 03:10:13 +00004132 } else if (rec->isUnion()) {
4133 // TODO: Support TBAA for unions.
4134 FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00004135 } else {
4136 // If no base type been assigned for the base access, then try to generate
4137 // one for this base lvalue.
4138 FieldTBAAInfo = base.getTBAAInfo();
4139 if (!FieldTBAAInfo.BaseType) {
4140 FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
4141 assert(!FieldTBAAInfo.Offset &&
4142 "Nonzero offset for an access with no base type!");
4143 }
4144
Hal Finkela5986b92017-12-03 03:10:13 +00004145 // Adjust offset to be relative to the base type.
4146 const ASTRecordLayout &Layout =
4147 getContext().getASTRecordLayout(field->getParent());
4148 unsigned CharWidth = getContext().getCharWidth();
4149 if (FieldTBAAInfo.BaseType)
4150 FieldTBAAInfo.Offset +=
4151 Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00004152
Ivan A. Kosarev617c3b72017-12-21 08:14:16 +00004153 // Update the final access type and size.
Hal Finkela5986b92017-12-03 03:10:13 +00004154 FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
Ivan A. Kosarev617c3b72017-12-21 08:14:16 +00004155 FieldTBAAInfo.Size =
4156 getContext().getTypeSizeInChars(FieldType).getQuantity();
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00004157 }
4158
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004159 Address addr = base.getAddress(*this);
Piotr Padlewski07058292018-07-02 19:21:36 +00004160 if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) {
4161 if (CGM.getCodeGenOpts().StrictVTablePointers &&
4162 ClassDef->isDynamicClass()) {
4163 // Getting to any field of dynamic object requires stripping dynamic
4164 // information provided by invariant.group. This is because accessing
4165 // fields may leak the real address of dynamic object, which could result
4166 // in miscompilation when leaked pointer would be compared.
4167 auto *stripped = Builder.CreateStripInvariantGroup(addr.getPointer());
4168 addr = Address(stripped, addr.getAlignment());
4169 }
4170 }
4171
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00004172 unsigned RecordCVR = base.getVRQualifiers();
John McCall53fcbd22011-02-26 08:07:02 +00004173 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00004174 // For unions, there is no pointer adjustment.
Piotr Padlewskic1d26062017-06-01 18:39:34 +00004175 if (CGM.getCodeGenOpts().StrictVTablePointers &&
4176 hasAnyVptr(FieldType, getContext()))
4177 // Because unions can easily skip invariant.barriers, we need to add
4178 // a barrier every time CXXRecord field with vptr is referenced.
Piotr Padlewski5dde8092018-05-03 11:03:01 +00004179 addr = Address(Builder.CreateLaunderInvariantGroup(addr.getPointer()),
Piotr Padlewskic1d26062017-06-01 18:39:34 +00004180 addr.getAlignment());
Yonghong Song048493f2019-07-09 04:21:50 +00004181
Yonghong Song4e2ce222019-11-01 22:16:59 -07004182 if (IsInPreservedAIRegion ||
4183 (getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
Yonghong Song048493f2019-07-09 04:21:50 +00004184 // Remember the original union field index
Yonghong Song9271cab2020-02-02 14:54:16 -08004185 llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(base.getType(),
4186 rec->getLocation());
Yonghong Song048493f2019-07-09 04:21:50 +00004187 addr = Address(
4188 Builder.CreatePreserveUnionAccessIndex(
Yonghong Song47548142019-07-16 17:24:33 +00004189 addr.getPointer(), getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo),
Yonghong Song048493f2019-07-09 04:21:50 +00004190 addr.getAlignment());
4191 }
Yonghong Song048493f2019-07-09 04:21:50 +00004192
Aaron Ballman0299dbd22019-08-27 12:42:45 +00004193 if (FieldType->isReferenceType())
4194 addr = Builder.CreateElementBitCast(
4195 addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
4196 } else {
Yonghong Song4e2ce222019-11-01 22:16:59 -07004197 if (!IsInPreservedAIRegion &&
4198 (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>()))
Yonghong Song048493f2019-07-09 04:21:50 +00004199 // For structs, we GEP to the field that the record layout suggests.
4200 addr = emitAddrOfFieldStorage(*this, addr, field);
4201 else
4202 // Remember the original struct field index
Yonghong Song9271cab2020-02-02 14:54:16 -08004203 addr = emitPreserveStructAccess(*this, base, addr, field);
Aaron Ballman0299dbd22019-08-27 12:42:45 +00004204 }
John McCall53fcbd22011-02-26 08:07:02 +00004205
Aaron Ballman0299dbd22019-08-27 12:42:45 +00004206 // If this is a reference field, load the reference right now.
4207 if (FieldType->isReferenceType()) {
4208 LValue RefLVal =
4209 MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
4210 if (RecordCVR & Qualifiers::Volatile)
4211 RefLVal.getQuals().addVolatile();
4212 addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
John McCall53fcbd22011-02-26 08:07:02 +00004213
Aaron Ballman0299dbd22019-08-27 12:42:45 +00004214 // Qualifiers on the struct don't apply to the referencee.
4215 RecordCVR = 0;
4216 FieldType = FieldType->getPointeeType();
Devang Pateled93c3c2007-10-26 19:42:18 +00004217 }
Craig Topper99e79272013-07-26 05:59:26 +00004218
Chris Lattner13ee4f42011-07-10 05:34:54 +00004219 // Make sure that the address is pointing to the right type. This is critical
4220 // for both unions and structs. A union needs a bitcast, a struct element
4221 // will need a bitcast if the LLVM type laid out doesn't match the desired
4222 // type.
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00004223 addr = Builder.CreateElementBitCast(
4224 addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00004225
Julien Lerouge5a6b6982011-09-09 22:41:49 +00004226 if (field->hasAttr<AnnotateAttr>())
4227 addr = EmitFieldAnnotations(field, addr);
4228
Ivan A. Kosarev17db3a12017-10-17 11:20:19 +00004229 LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
Ivan A. Kosarev9f9d1572017-10-30 11:49:31 +00004230 LV.getQuals().addCVRQualifiers(RecordCVR);
Ivan A. Kosarev383890b2017-10-06 08:17:48 +00004231
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00004232 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00004233 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
4234 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00004235
Daniel Dunbarf166a522010-08-21 03:44:13 +00004236 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00004237}
4238
Craig Topper99e79272013-07-26 05:59:26 +00004239LValue
4240CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00004241 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00004242 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00004243
Anders Carlssondb78f0a2010-01-29 05:24:29 +00004244 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00004245 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00004246
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004247 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(*this), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00004248
John McCall7f416cc2015-09-08 08:05:57 +00004249 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00004250 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00004251 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00004252
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004253 // TODO: Generate TBAA information that describes this access as a structure
4254 // member access and not just an access to an object of the field's type. This
4255 // should be similar to what we do in EmitLValueForField().
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004256 LValueBaseInfo BaseInfo = Base.getBaseInfo();
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004257 AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
4258 LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004259 return MakeAddrLValue(V, FieldType, FieldBaseInfo,
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004260 CGM.getTBAAInfoForSubobject(Base, FieldType));
Anders Carlssondb78f0a2010-01-29 05:24:29 +00004261}
4262
Chris Lattnerf53c0962010-09-06 00:11:41 +00004263LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00004264 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00004265 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004266 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
Richard Smith2d988f02011-11-22 22:48:32 +00004267 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00004268 if (E->getType()->isVariablyModifiedType())
4269 // make sure to emit the VLA size.
4270 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00004271
John McCall7f416cc2015-09-08 08:05:57 +00004272 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00004273 const Expr *InitExpr = E->getInitializer();
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004274 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
Eli Friedman9fd8b682008-05-13 23:18:27 +00004275
Chad Rosier615ed1a2012-03-29 17:37:10 +00004276 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
4277 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00004278
Akira Hatanaka40568fe2020-03-10 14:06:25 -07004279 // Block-scope compound literals are destroyed at the end of the enclosing
4280 // scope in C.
4281 if (!getLangOpts().CPlusPlus)
4282 if (QualType::DestructionKind DtorKind = E->getType().isDestructedType())
4283 pushLifetimeExtendedDestroy(getCleanupKind(DtorKind), DeclPtr,
4284 E->getType(), getDestroyer(DtorKind),
4285 DtorKind & EHCleanup);
4286
Eli Friedman9fd8b682008-05-13 23:18:27 +00004287 return Result;
4288}
4289
Richard Smithbb653bd2012-05-14 21:57:21 +00004290LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
4291 if (!E->isGLValue())
4292 // Initializing an aggregate temporary in C++11: T{...}.
4293 return EmitAggExprToLValue(E);
4294
4295 // An lvalue initializer list must be initializing a reference.
Richard Smith122f88d2016-12-06 23:52:28 +00004296 assert(E->isTransparent() && "non-transparent glvalue init list");
Richard Smithbb653bd2012-05-14 21:57:21 +00004297 return EmitLValue(E->getInit(0));
4298}
4299
Richard Smithf3076ff2014-06-20 18:43:47 +00004300/// Emit the operand of a glvalue conditional operator. This is either a glvalue
4301/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
4302/// LValue is returned and the current block has been terminated.
4303static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
4304 const Expr *Operand) {
4305 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
4306 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
4307 return None;
4308 }
4309
4310 return CGF.EmitLValue(Operand);
4311}
4312
John McCallc07a0c72011-02-17 10:25:35 +00004313LValue CodeGenFunction::
4314EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
4315 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00004316 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00004317 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00004318 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00004319 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00004320 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00004321
Eli Friedman59954892012-01-25 05:04:17 +00004322 OpaqueValueMapping binding(*this, expr);
4323
John McCallc07a0c72011-02-17 10:25:35 +00004324 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00004325 bool CondExprBool;
4326 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00004327 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00004328 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00004329
Justin Bogneref512b92014-01-06 22:27:43 +00004330 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00004331 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00004332 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00004333 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00004334 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00004335 }
John McCall0a6bf2e2011-01-26 19:21:13 +00004336 }
4337
John McCallc07a0c72011-02-17 10:25:35 +00004338 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
4339 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
4340 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00004341
4342 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00004343 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00004344
John McCall0a6bf2e2011-01-26 19:21:13 +00004345 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00004346 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00004347 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00004348 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00004349 Optional<LValue> lhs =
4350 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00004351 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00004352
Richard Smithf3076ff2014-06-20 18:43:47 +00004353 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00004354 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00004355
John McCallc07a0c72011-02-17 10:25:35 +00004356 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00004357 if (lhs)
4358 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00004359
John McCall0a6bf2e2011-01-26 19:21:13 +00004360 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00004361 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00004362 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00004363 Optional<LValue> rhs =
4364 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00004365 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00004366 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00004367 return EmitUnsupportedLValue(expr, "conditional operator");
4368 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00004369
John McCallc07a0c72011-02-17 10:25:35 +00004370 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00004371
Richard Smithf3076ff2014-06-20 18:43:47 +00004372 if (lhs && rhs) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004373 llvm::PHINode *phi =
4374 Builder.CreatePHI(lhs->getPointer(*this)->getType(), 2, "cond-lvalue");
4375 phi->addIncoming(lhs->getPointer(*this), lhsBlock);
4376 phi->addIncoming(rhs->getPointer(*this), rhsBlock);
John McCall7f416cc2015-09-08 08:05:57 +00004377 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
4378 AlignmentSource alignSource =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004379 std::max(lhs->getBaseInfo().getAlignmentSource(),
4380 rhs->getBaseInfo().getAlignmentSource());
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004381 TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
4382 lhs->getTBAAInfo(), rhs->getTBAAInfo());
4383 return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
4384 TBAAInfo);
Richard Smithf3076ff2014-06-20 18:43:47 +00004385 } else {
4386 assert((lhs || rhs) &&
4387 "both operands of glvalue conditional are throw-expressions?");
4388 return lhs ? *lhs : *rhs;
4389 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00004390}
4391
Richard Smithbb653bd2012-05-14 21:57:21 +00004392/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
4393/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00004394/// otherwise if a cast is needed by the code generator in an lvalue context,
4395/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00004396/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00004397/// are permitted with aggregate result, including noop aggregate casts, and
4398/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00004399LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00004400 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00004401 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00004402 case CK_BitCast:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00004403 case CK_LValueToRValueBitCast:
John McCalle3027922010-08-25 11:45:40 +00004404 case CK_ArrayToPointerDecay:
4405 case CK_FunctionToPointerDecay:
4406 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00004407 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00004408 case CK_IntegralToPointer:
4409 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00004410 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00004411 case CK_VectorSplat:
4412 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00004413 case CK_BooleanToSignedIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00004414 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00004415 case CK_IntegralToFloating:
4416 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00004417 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00004418 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00004419 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00004420 case CK_FloatingComplexToReal:
4421 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00004422 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00004423 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00004424 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00004425 case CK_IntegralComplexToReal:
4426 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00004427 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00004428 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00004429 case CK_DerivedToBaseMemberPointer:
4430 case CK_BaseToDerivedMemberPointer:
4431 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00004432 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00004433 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00004434 case CK_ARCProduceObject:
4435 case CK_ARCConsumeObject:
4436 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00004437 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00004438 case CK_CopyAndAutoreleaseBlockObject:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00004439 case CK_IntToOCLSampler:
Leonard Chan99bda372018-10-15 16:07:02 +00004440 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +00004441 case CK_FixedPointToBoolean:
Leonard Chan8f7caae2019-03-06 00:28:43 +00004442 case CK_FixedPointToIntegral:
4443 case CK_IntegralToFixedPoint:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00004444 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
4445
4446 case CK_Dependent:
4447 llvm_unreachable("dependent cast kind in IR gen!");
4448
4449 case CK_BuiltinFnToFnPtr:
4450 llvm_unreachable("builtin functions are handled elsewhere");
4451
Eli Friedmanbe4504d2013-07-11 01:32:21 +00004452 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00004453 case CK_NonAtomicToAtomic:
4454 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00004455 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00004456
Anders Carlsson8a01a752011-04-11 02:03:26 +00004457 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00004458 LValue LV = EmitLValue(E->getSubExpr());
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004459 Address V = LV.getAddress(*this);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004460 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00004461 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00004462 }
4463
John McCalle3027922010-08-25 11:45:40 +00004464 case CK_ConstructorConversion:
4465 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00004466 case CK_CPointerToObjCPointerCast:
4467 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00004468 case CK_NoOp:
4469 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00004470 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00004471
John McCalle3027922010-08-25 11:45:40 +00004472 case CK_UncheckedDerivedToBase:
4473 case CK_DerivedToBase: {
Simon Pilgrim16c53ff2020-01-11 15:33:25 +00004474 const auto *DerivedClassTy =
4475 E->getSubExpr()->getType()->castAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004476 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00004477
Anders Carlssond95f9602009-09-12 16:16:49 +00004478 LValue LV = EmitLValue(E->getSubExpr());
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004479 Address This = LV.getAddress(*this);
Craig Topper99e79272013-07-26 05:59:26 +00004480
Anders Carlssond95f9602009-09-12 16:16:49 +00004481 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00004482 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00004483 This, DerivedClassDecl, E->path_begin(), E->path_end(),
4484 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00004485
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004486 // TODO: Support accesses to members of base classes in TBAA. For now, we
4487 // conservatively pretend that the complete object is of the base class
4488 // type.
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004489 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004490 CGM.getTBAAInfoForSubobject(LV, E->getType()));
Anders Carlssond95f9602009-09-12 16:16:49 +00004491 }
John McCalle3027922010-08-25 11:45:40 +00004492 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00004493 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00004494 case CK_BaseToDerived: {
Simon Pilgrim16c53ff2020-01-11 15:33:25 +00004495 const auto *DerivedClassTy = E->getType()->castAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004496 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00004497
Anders Carlsson8c793172009-11-23 17:57:54 +00004498 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00004499
Anders Carlsson8c793172009-11-23 17:57:54 +00004500 // Perform the base-to-derived conversion
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004501 Address Derived = GetAddressOfDerivedClass(
4502 LV.getAddress(*this), DerivedClassDecl, E->path_begin(), E->path_end(),
4503 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00004504
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004505 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
4506 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00004507 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004508 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00004509 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004510
Peter Collingbourned2926c92015-03-14 02:42:25 +00004511 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00004512 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004513 /*MayBeNull=*/false, CFITCK_DerivedCast,
4514 E->getBeginLoc());
Peter Collingbourned2926c92015-03-14 02:42:25 +00004515
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004516 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004517 CGM.getTBAAInfoForSubobject(LV, E->getType()));
Eli Friedman8c98dff2009-11-16 05:48:01 +00004518 }
John McCalle3027922010-08-25 11:45:40 +00004519 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00004520 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004521 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00004522
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00004523 CGM.EmitExplicitCastExprType(CE, this);
Anders Carlsson50cb3212009-11-14 21:21:42 +00004524 LValue LV = EmitLValue(E->getSubExpr());
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004525 Address V = Builder.CreateBitCast(LV.getAddress(*this),
John McCall7f416cc2015-09-08 08:05:57 +00004526 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00004527
4528 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00004529 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004530 /*MayBeNull=*/false, CFITCK_UnrelatedCast,
4531 E->getBeginLoc());
Peter Collingbourned2926c92015-03-14 02:42:25 +00004532
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004533 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004534 CGM.getTBAAInfoForSubobject(LV, E->getType()));
Anders Carlsson50cb3212009-11-14 21:21:42 +00004535 }
Anastasia Stulova04307942018-11-16 16:22:56 +00004536 case CK_AddressSpaceConversion: {
4537 LValue LV = EmitLValue(E->getSubExpr());
4538 QualType DestTy = getContext().getPointerType(E->getType());
4539 llvm::Value *V = getTargetHooks().performAddrSpaceCast(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004540 *this, LV.getPointer(*this),
4541 E->getSubExpr()->getType().getAddressSpace(),
Andrew Savonichev87a7e432018-12-12 09:51:23 +00004542 E->getType().getAddressSpace(), ConvertType(DestTy));
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004543 return MakeAddrLValue(Address(V, LV.getAddress(*this).getAlignment()),
Andrew Savonichev87a7e432018-12-12 09:51:23 +00004544 E->getType(), LV.getBaseInfo(), LV.getTBAAInfo());
Anastasia Stulova04307942018-11-16 16:22:56 +00004545 }
John McCalle3027922010-08-25 11:45:40 +00004546 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004547 LValue LV = EmitLValue(E->getSubExpr());
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004548 Address V = Builder.CreateElementBitCast(LV.getAddress(*this),
John McCall7f416cc2015-09-08 08:05:57 +00004549 ConvertType(E->getType()));
Ivan A. Kosarevf5f20462017-10-12 11:29:46 +00004550 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
Ivan A. Kosarevb9c59f32017-10-31 11:05:34 +00004551 CGM.getTBAAInfoForSubobject(LV, E->getType()));
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004552 }
Andrew Savonichevb555b762018-10-23 15:19:20 +00004553 case CK_ZeroToOCLOpaqueType:
4554 llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00004555 }
Craig Topper99e79272013-07-26 05:59:26 +00004556
Douglas Gregorcdb466e2010-07-15 18:58:16 +00004557 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00004558}
4559
John McCall1bf58462011-02-16 08:02:54 +00004560LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00004561 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
Akira Hatanaka797afe32018-03-20 01:47:58 +00004562 return getOrCreateOpaqueLValueMapping(e);
4563}
4564
4565LValue
4566CodeGenFunction::getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e) {
4567 assert(OpaqueValueMapping::shouldBindAsLValue(e));
4568
4569 llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
4570 it = OpaqueLValues.find(e);
4571
4572 if (it != OpaqueLValues.end())
4573 return it->second;
4574
4575 assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
4576 return EmitLValue(e->getSourceExpr());
4577}
4578
4579RValue
4580CodeGenFunction::getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e) {
4581 assert(!OpaqueValueMapping::shouldBindAsLValue(e));
4582
4583 llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
4584 it = OpaqueRValues.find(e);
4585
4586 if (it != OpaqueRValues.end())
4587 return it->second;
4588
4589 assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
4590 return EmitAnyExpr(e->getSourceExpr());
John McCall1bf58462011-02-16 08:02:54 +00004591}
4592
Eli Friedman7f1ff602012-04-16 03:54:45 +00004593RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004594 const FieldDecl *FD,
4595 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004596 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00004597 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00004598 switch (getEvaluationKind(FT)) {
4599 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004600 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00004601 case TEK_Aggregate:
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004602 return FieldLV.asAggregateRValue(*this);
John McCall47fb9502013-03-07 21:37:08 +00004603 case TEK_Scalar:
Reid Kleckner9d031092016-05-02 22:42:34 +00004604 // This routine is used to load fields one-by-one to perform a copy, so
4605 // don't load reference fields.
4606 if (FD->getType()->isReferenceType())
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004607 return RValue::get(FieldLV.getPointer(*this));
Akira Hatanakad8136f12019-11-29 09:56:02 -08004608 // Call EmitLoadOfScalar except when the lvalue is a bitfield to emit a
4609 // primitive load.
4610 if (FieldLV.isBitField())
4611 return EmitLoadOfLValue(FieldLV, Loc);
4612 return RValue::get(EmitLoadOfScalar(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00004613 }
4614 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004615}
Douglas Gregorfe314812011-06-21 17:03:29 +00004616
Chris Lattnere47e4402007-06-01 18:02:12 +00004617//===--------------------------------------------------------------------===//
4618// Expression Emission
4619//===--------------------------------------------------------------------===//
4620
Craig Topper99e79272013-07-26 05:59:26 +00004621RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00004622 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00004623 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00004624 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00004625 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00004626
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004627 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00004628 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00004629
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004630 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00004631 return EmitCUDAKernelCallExpr(CE, ReturnValue);
4632
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004633 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
John McCallb92ab1a2016-10-26 23:46:34 +00004634 if (const CXXMethodDecl *MD =
4635 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
Anders Carlssonbfb36712009-12-24 21:13:40 +00004636 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00004637
John McCallb92ab1a2016-10-26 23:46:34 +00004638 CGCallee callee = EmitCallee(E->getCallee());
Craig Topper99e79272013-07-26 05:59:26 +00004639
John McCallb92ab1a2016-10-26 23:46:34 +00004640 if (callee.isBuiltin()) {
4641 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
4642 E, ReturnValue);
Douglas Gregorad8a3362009-09-04 17:36:40 +00004643 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004644
John McCallb92ab1a2016-10-26 23:46:34 +00004645 if (callee.isPseudoDestructor()) {
4646 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
4647 }
4648
4649 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
4650}
4651
4652/// Emit a CallExpr without considering whether it might be a subclass.
4653RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
4654 ReturnValueSlot ReturnValue) {
4655 CGCallee Callee = EmitCallee(E->getCallee());
4656 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
4657}
4658
Yaxun (Sam) Liu29e1a162020-03-05 12:02:13 -05004659static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD) {
4660 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
serge-sans-pailled437fba2020-01-16 19:54:38 +01004661
John McCallb92ab1a2016-10-26 23:46:34 +00004662 if (auto builtinID = FD->getBuiltinID()) {
serge-sans-pailled437fba2020-01-16 19:54:38 +01004663 // Replaceable builtin provide their own implementation of a builtin. Unless
4664 // we are in the builtin implementation itself, don't call the actual
4665 // builtin. If we are in the builtin implementation, avoid trivial infinite
4666 // recursion.
4667 if (!FD->isInlineBuiltinDeclaration() ||
4668 CGF.CurFn->getName() == FD->getName())
4669 return CGCallee::forBuiltin(builtinID, FD);
John McCallb92ab1a2016-10-26 23:46:34 +00004670 }
4671
Yaxun (Sam) Liu29e1a162020-03-05 12:02:13 -05004672 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, GD);
4673 return CGCallee::forDirect(calleePtr, GD);
John McCallb92ab1a2016-10-26 23:46:34 +00004674}
4675
4676CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
4677 E = E->IgnoreParens();
4678
4679 // Look through function-to-pointer decay.
4680 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
4681 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
4682 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
4683 return EmitCallee(ICE->getSubExpr());
4684 }
4685
4686 // Resolve direct calls.
4687 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
4688 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Michael Liao4cf01ed2020-03-18 01:43:20 -04004689 return EmitDirectCallee(*this, FD);
John McCallb92ab1a2016-10-26 23:46:34 +00004690 }
4691 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
4692 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
4693 EmitIgnoredExpr(ME->getBase());
Michael Liao4cf01ed2020-03-18 01:43:20 -04004694 return EmitDirectCallee(*this, FD);
John McCallb92ab1a2016-10-26 23:46:34 +00004695 }
4696
4697 // Look through template substitutions.
4698 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4699 return EmitCallee(NTTP->getReplacement());
4700
4701 // Treat pseudo-destructor calls differently.
4702 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4703 return CGCallee::forPseudoDestructor(PDE);
4704 }
4705
4706 // Otherwise, we have an indirect reference.
4707 llvm::Value *calleePtr;
4708 QualType functionType;
4709 if (auto ptrType = E->getType()->getAs<PointerType>()) {
4710 calleePtr = EmitScalarExpr(E);
4711 functionType = ptrType->getPointeeType();
4712 } else {
4713 functionType = E->getType();
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004714 calleePtr = EmitLValue(E).getPointer(*this);
John McCallb92ab1a2016-10-26 23:46:34 +00004715 }
4716 assert(functionType->isFunctionType());
Erich Keanede6480a32018-11-13 15:48:08 +00004717
4718 GlobalDecl GD;
4719 if (const auto *VD =
4720 dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee()))
4721 GD = GlobalDecl(VD);
4722
4723 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD);
John McCallb92ab1a2016-10-26 23:46:34 +00004724 CGCallee callee(calleeInfo, calleePtr);
4725 return callee;
Chris Lattner9e47ead2007-08-31 04:44:06 +00004726}
4727
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004728LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00004729 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00004730 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00004731 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00004732 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00004733 return EmitLValue(E->getRHS());
4734 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004735
John McCalle3027922010-08-25 11:45:40 +00004736 if (E->getOpcode() == BO_PtrMemD ||
4737 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004738 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004739
John McCalla2342eb2010-12-05 02:00:02 +00004740 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00004741
4742 // Note that in all of these cases, __block variables need the RHS
4743 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00004744
4745 switch (getEvaluationKind(E->getType())) {
4746 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00004747 switch (E->getLHS()->getType().getObjCLifetime()) {
4748 case Qualifiers::OCL_Strong:
4749 return EmitARCStoreStrong(E, /*ignored*/ false).first;
4750
4751 case Qualifiers::OCL_Autoreleasing:
4752 return EmitARCStoreAutoreleasing(E).first;
4753
4754 // No reason to do any of these differently.
4755 case Qualifiers::OCL_None:
4756 case Qualifiers::OCL_ExplicitNone:
4757 case Qualifiers::OCL_Weak:
4758 break;
4759 }
4760
John McCalld0a30012010-12-06 06:10:02 +00004761 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00004762 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
Vedant Kumar6b22dda2017-04-26 21:55:17 +00004763 if (RV.isScalar())
4764 EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
John McCall55e1fbc2011-06-25 02:11:03 +00004765 EmitStoreThroughLValue(RV, LV);
Alexey Bataeva58da1a2019-12-27 09:44:43 -05004766 if (getLangOpts().OpenMP)
4767 CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
4768 E->getLHS());
Anders Carlsson0999aaf2009-10-19 18:28:22 +00004769 return LV;
4770 }
John McCall4f29b492010-11-16 23:07:28 +00004771
John McCall47fb9502013-03-07 21:37:08 +00004772 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00004773 return EmitComplexAssignmentLValue(E);
4774
John McCall47fb9502013-03-07 21:37:08 +00004775 case TEK_Aggregate:
4776 return EmitAggExprToLValue(E);
4777 }
4778 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004779}
4780
Christopher Lambd91c3d42007-12-29 05:02:41 +00004781LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00004782 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00004783
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004784 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004785 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004786 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00004787
David Majnemerced8bdf2015-02-25 17:36:15 +00004788 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004789 "Can't have a scalar return unless the return type is a "
4790 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00004791
John McCall7f416cc2015-09-08 08:05:57 +00004792 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00004793}
4794
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004795LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4796 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00004797 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004798}
4799
Anders Carlsson3be22e22009-05-30 23:23:33 +00004800LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004801 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
4802 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004803 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00004804 EmitCXXConstructExpr(E, Slot);
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004805 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
Anders Carlsson3be22e22009-05-30 23:23:33 +00004806}
4807
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004808LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00004809CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004810 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00004811}
4812
John McCall7f416cc2015-09-08 08:05:57 +00004813Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
4814 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4815 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00004816}
4817
4818LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004819 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004820 AlignmentSource::Decl);
Nico Webercf4ff5862012-10-11 10:13:44 +00004821}
4822
Mike Stumpc9b231c2009-11-15 08:09:41 +00004823LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004824CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004825 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00004826 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00004827 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004828 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004829 return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004830}
4831
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004832LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004833 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00004834
Anders Carlsson280e61f12010-06-21 20:59:55 +00004835 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004836 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004837 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00004838
Alp Toker314cc812014-01-25 16:55:45 +00004839 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00004840 "Can't have a scalar return unless the return type is a "
4841 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00004842
John McCall7f416cc2015-09-08 08:05:57 +00004843 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004844}
4845
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004846LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004847 Address V =
4848 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004849 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004850}
4851
Daniel Dunbar722f4242009-04-22 05:08:15 +00004852llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004853 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004854 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004855}
4856
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004857LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4858 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004859 const ObjCIvarDecl *Ivar,
4860 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00004861 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00004862 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004863}
4864
4865LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004866 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00004867 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004868 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00004869 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004870 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004871 if (E->isArrow()) {
4872 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004873 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00004874 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004875 } else {
4876 LValue BaseLV = EmitLValue(BaseExpr);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004877 BaseValue = BaseLV.getPointer(*this);
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004878 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00004879 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004880 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004881
Craig Topper99e79272013-07-26 05:59:26 +00004882 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00004883 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4884 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00004885 setObjCGCLValueClass(getContext(), E, LV);
4886 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00004887}
4888
Chris Lattnera4185c52009-04-25 19:35:26 +00004889LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00004890 // Can only get l-value for message expression returning aggregate type
4891 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00004892 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00004893 AlignmentSource::Decl);
Chris Lattnera4185c52009-04-25 19:35:26 +00004894}
4895
John McCallb92ab1a2016-10-26 23:46:34 +00004896RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004897 const CallExpr *E, ReturnValueSlot ReturnValue,
John McCallb92ab1a2016-10-26 23:46:34 +00004898 llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00004899 // Get the actual function type. The callee type will always be a pointer to
4900 // function type or a block pointer type.
4901 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00004902 "Call must have function pointer type!");
4903
Erich Keanede6480a32018-11-13 15:48:08 +00004904 const Decl *TargetDecl =
4905 OrigCallee.getAbstractInfo().getCalleeDecl().getDecl();
Samuel Antao798f11c2015-11-23 22:04:44 +00004906
John McCall6fd4c232009-10-23 08:22:42 +00004907 CalleeType = getContext().getCanonicalType(CalleeType);
4908
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00004909 auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType();
Daniel Dunbarc722b852008-08-30 03:02:31 +00004910
John McCallb92ab1a2016-10-26 23:46:34 +00004911 CGCallee Callee = OrigCallee;
4912
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004913 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004914 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4915 if (llvm::Constant *PrefixSig =
4916 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00004917 SanitizerScope SanScope(this);
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00004918 // Remove any (C++17) exception specifications, to allow calling e.g. a
4919 // noexcept function through a non-noexcept pointer.
4920 auto ProtoTy =
4921 getContext().getFunctionTypeWithExceptionSpec(PointeeType, EST_None);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004922 llvm::Constant *FTRTTIConst =
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00004923 CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
Vedant Kumarbb5d4852017-09-13 00:04:35 +00004924 llvm::Type *PrefixStructTyElems[] = {PrefixSig->getType(), Int32Ty};
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004925 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4926 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4927
John McCallb92ab1a2016-10-26 23:46:34 +00004928 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4929
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004930 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
John McCallb92ab1a2016-10-26 23:46:34 +00004931 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004932 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004933 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00004934 llvm::Value *CalleeSig =
4935 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004936 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4937
4938 llvm::BasicBlock *Cont = createBasicBlock("cont");
4939 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4940 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4941
4942 EmitBlock(TypeCheck);
4943 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004944 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
Vedant Kumarbb5d4852017-09-13 00:04:35 +00004945 llvm::Value *CalleeRTTIEncoded =
John McCall7f416cc2015-09-08 08:05:57 +00004946 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Vedant Kumarbb5d4852017-09-13 00:04:35 +00004947 llvm::Value *CalleeRTTI =
4948 DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004949 llvm::Value *CalleeRTTIMatch =
4950 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004951 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()),
4952 EmitCheckTypeDescriptor(CalleeType)};
Alexey Samsonove396bfc2014-11-11 22:03:54 +00004953 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
Stephan Bergmann5745ecc2019-05-02 06:40:33 +00004954 SanitizerHandler::FunctionTypeMismatch, StaticData,
4955 {CalleePtr, CalleeRTTI, FTRTTIConst});
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004956
4957 Builder.CreateBr(Cont);
4958 EmitBlock(Cont);
4959 }
4960 }
4961
Stephan Bergmann8c85bca2018-01-05 07:57:12 +00004962 const auto *FnType = cast<FunctionType>(PointeeType);
4963
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004964 // If we are checking indirect calls and this call is indirect, check that the
4965 // function pointer is a member of the bit set for the function type.
4966 if (SanOpts.has(SanitizerKind::CFIICall) &&
4967 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4968 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00004969 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004970
Vlad Tsyrklevich634c6012017-10-31 22:39:44 +00004971 llvm::Metadata *MD;
4972 if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
4973 MD = CGM.CreateMetadataIdentifierGeneralized(QualType(FnType, 0));
4974 else
4975 MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
4976
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004977 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004978
John McCallb92ab1a2016-10-26 23:46:34 +00004979 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4980 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004981 llvm::Value *TypeTest = Builder.CreateCall(
4982 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004983
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004984 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004985 llvm::Constant *StaticData[] = {
4986 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004987 EmitCheckSourceLocation(E->getBeginLoc()),
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004988 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4989 };
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004990 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4991 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004992 CastedCallee, StaticData);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004993 } else {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004994 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004995 SanitizerHandler::CFICheckFail, StaticData,
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004996 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004997 }
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004998 }
4999
Daniel Dunbarc722b852008-08-30 03:02:31 +00005000 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00005001 if (Chain)
5002 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
5003 CGM.getContext().VoidPtrTy);
Richard Smith762672a2016-09-28 19:09:10 +00005004
5005 // C++17 requires that we evaluate arguments to a call using assignment syntax
Richard Smitha560ccf2016-09-29 21:30:12 +00005006 // right-to-left, and that we evaluate arguments to certain other operators
5007 // left-to-right. Note that we allow this to override the order dictated by
5008 // the calling convention on the MS ABI, which means that parameter
5009 // destruction order is not necessarily reverse construction order.
5010 // FIXME: Revisit this based on C++ committee response to unimplementability.
5011 EvaluationOrder Order = EvaluationOrder::Default;
5012 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
5013 if (OCE->isAssignmentOp())
5014 Order = EvaluationOrder::ForceRightToLeft;
5015 else {
5016 switch (OCE->getOperator()) {
5017 case OO_LessLess:
5018 case OO_GreaterGreater:
5019 case OO_AmpAmp:
5020 case OO_PipePipe:
5021 case OO_Comma:
5022 case OO_ArrowStar:
5023 Order = EvaluationOrder::ForceLeftToRight;
5024 break;
5025 default:
5026 break;
5027 }
5028 }
5029 }
Richard Smith762672a2016-09-28 19:09:10 +00005030
David Blaikief05779e2015-07-21 18:37:18 +00005031 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
Richard Smitha560ccf2016-09-29 21:30:12 +00005032 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
Daniel Dunbarc722b852008-08-30 03:02:31 +00005033
Peter Collingbournef7706832014-12-12 23:41:25 +00005034 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00005035 Args, FnType, /*ChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00005036
5037 // C99 6.5.2.2p6:
5038 // If the expression that denotes the called function has a type
5039 // that does not include a prototype, [the default argument
5040 // promotions are performed]. If the number of arguments does not
5041 // equal the number of parameters, the behavior is undefined. If
5042 // the function is defined with a type that includes a prototype,
5043 // and either the prototype ends with an ellipsis (, ...) or the
5044 // types of the arguments after promotion are not compatible with
5045 // the types of the parameters, the behavior is undefined. If the
5046 // function is defined with a type that does not include a
5047 // prototype, and the types of the arguments after promotion are
5048 // not compatible with those of the parameters after promotion,
5049 // the behavior is undefined [except in some trivial cases].
5050 // That is, in the general case, we should assume that a call
5051 // through an unprototyped function type works like a *non-variadic*
5052 // call. The way we make this work is to cast to the exact type
5053 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00005054 //
5055 // Chain calls use this same code path to add the invisible chain parameter
5056 // to the function type.
5057 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00005058 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00005059 CalleeTy = CalleeTy->getPointerTo();
John McCallb92ab1a2016-10-26 23:46:34 +00005060
5061 llvm::Value *CalleePtr = Callee.getFunctionPointer();
5062 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
5063 Callee.setFunctionPointer(CalleePtr);
John McCallcbc038a2011-09-21 08:08:30 +00005064 }
5065
Djordje Todorovic0f651682019-06-27 06:44:44 +00005066 llvm::CallBase *CallOrInvoke = nullptr;
5067 RValue Call = EmitCall(FnInfo, Callee, ReturnValue, Args, &CallOrInvoke,
5068 E->getExprLoc());
5069
5070 // Generate function declaration DISuprogram in order to be used
5071 // in debug info about call sites.
5072 if (CGDebugInfo *DI = getDebugInfo()) {
5073 if (auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl))
5074 DI->EmitFuncDeclForCallSite(CallOrInvoke, QualType(FnType, 0),
5075 CalleeDecl);
5076 }
5077
5078 return Call;
Daniel Dunbar97db84c2008-08-23 03:46:30 +00005079}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00005080
Chris Lattnerab5e0af2009-10-28 17:39:19 +00005081LValue CodeGenFunction::
5082EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00005083 Address BaseAddr = Address::invalid();
5084 if (E->getOpcode() == BO_PtrMemI) {
5085 BaseAddr = EmitPointerWithAlignment(E->getLHS());
5086 } else {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08005087 BaseAddr = EmitLValue(E->getLHS()).getAddress(*this);
John McCall7f416cc2015-09-08 08:05:57 +00005088 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00005089
John McCallc134eb52010-08-31 21:07:20 +00005090 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
Simon Pilgrim16c53ff2020-01-11 15:33:25 +00005091 const auto *MPT = E->getRHS()->getType()->castAs<MemberPointerType>();
John McCallc134eb52010-08-31 21:07:20 +00005092
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00005093 LValueBaseInfo BaseInfo;
Ivan A. Kosarev229a6d82017-10-13 16:38:32 +00005094 TBAAAccessInfo TBAAInfo;
John McCall7f416cc2015-09-08 08:05:57 +00005095 Address MemberAddr =
Ivan A. Kosarev229a6d82017-10-13 16:38:32 +00005096 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo,
5097 &TBAAInfo);
John McCallc134eb52010-08-31 21:07:20 +00005098
Ivan A. Kosarev229a6d82017-10-13 16:38:32 +00005099 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00005100}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00005101
John McCall47fb9502013-03-07 21:37:08 +00005102/// Given the address of a temporary variable, produce an r-value of
5103/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00005104RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00005105 QualType type,
5106 SourceLocation loc) {
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00005107 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
John McCall47fb9502013-03-07 21:37:08 +00005108 switch (getEvaluationKind(type)) {
5109 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00005110 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00005111 case TEK_Aggregate:
Akira Hatanakaf139ae32019-12-03 15:17:01 -08005112 return lvalue.asAggregateRValue(*this);
John McCall47fb9502013-03-07 21:37:08 +00005113 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00005114 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00005115 }
5116 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00005117}
5118
Duncan Sandse81111c2012-04-10 08:23:07 +00005119void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00005120 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00005121 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00005122 return;
5123
Duncan Sands65229ed2012-04-16 16:29:47 +00005124 llvm::MDBuilder MDHelper(getLLVMContext());
5125 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00005126
Duncan Sands6fc46192012-04-14 12:37:26 +00005127 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00005128}
John McCallfe96e0b2011-11-06 09:01:30 +00005129
5130namespace {
5131 struct LValueOrRValue {
5132 LValue LV;
5133 RValue RV;
5134 };
5135}
5136
5137static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
5138 const PseudoObjectExpr *E,
5139 bool forLValue,
5140 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005141 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00005142
5143 // Find the result expression, if any.
5144 const Expr *resultExpr = E->getResultExpr();
5145 LValueOrRValue result;
5146
5147 for (PseudoObjectExpr::const_semantics_iterator
5148 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
5149 const Expr *semantic = *i;
5150
5151 // If this semantic expression is an opaque value, bind it
5152 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00005153 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
Akira Hatanaka797afe32018-03-20 01:47:58 +00005154 // Skip unique OVEs.
5155 if (ov->isUnique()) {
5156 assert(ov != resultExpr &&
5157 "A unique OVE cannot be used as the result expression");
5158 continue;
5159 }
John McCallfe96e0b2011-11-06 09:01:30 +00005160
5161 // If this is the result expression, we may need to evaluate
5162 // directly into the slot.
5163 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
5164 OVMA opaqueData;
5165 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00005166 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00005167 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
John McCall7f416cc2015-09-08 08:05:57 +00005168 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
Ivan A. Kosarev5f8c0ca2017-10-10 09:39:32 +00005169 AlignmentSource::Decl);
John McCallfe96e0b2011-11-06 09:01:30 +00005170 opaqueData = OVMA::bind(CGF, ov, LV);
5171 result.RV = slot.asRValue();
5172
5173 // Otherwise, emit as normal.
5174 } else {
5175 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
5176
5177 // If this is the result, also evaluate the result now.
5178 if (ov == resultExpr) {
5179 if (forLValue)
5180 result.LV = CGF.EmitLValue(ov);
5181 else
5182 result.RV = CGF.EmitAnyExpr(ov, slot);
5183 }
5184 }
5185
5186 opaques.push_back(opaqueData);
5187
5188 // Otherwise, if the expression is the result, evaluate it
5189 // and remember the result.
5190 } else if (semantic == resultExpr) {
5191 if (forLValue)
5192 result.LV = CGF.EmitLValue(semantic);
5193 else
5194 result.RV = CGF.EmitAnyExpr(semantic, slot);
5195
5196 // Otherwise, evaluate the expression in an ignored context.
5197 } else {
5198 CGF.EmitIgnoredExpr(semantic);
5199 }
5200 }
5201
5202 // Unbind all the opaques now.
5203 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
5204 opaques[i].unbind(CGF);
5205
5206 return result;
5207}
5208
5209RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
5210 AggValueSlot slot) {
5211 return emitPseudoObjectExpr(*this, E, false, slot).RV;
5212}
5213
5214LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
5215 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
5216}