blob: e87c4a9e2ed38fd75e9b355abfe2179b706d5eb0 [file] [log] [blame]
Chris Lattnere47e4402007-06-01 18:02:12 +00001//===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnere47e4402007-06-01 18:02:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
John McCall5d865c322010-08-31 07:33:07 +000014#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CGCall.h"
Tim Shen421119f2016-07-01 21:08:47 +000016#include "CGCleanup.h"
Devang Pateld3a6b0f2011-03-04 18:54:42 +000017#include "CGDebugInfo.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Alexey Bataev97720002014-11-11 04:05:39 +000019#include "CGOpenMPRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "CGRecordLayout.h"
Tim Shen421119f2016-07-01 21:08:47 +000021#include "CodeGenFunction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "CodeGenModule.h"
John McCallde0fe072017-08-15 21:42:52 +000023#include "ConstantEmitter.h"
John McCallcbc038a2011-09-21 08:08:30 +000024#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000025#include "clang/AST/ASTContext.h"
Renato Golin230c5eb2014-05-19 18:15:42 +000026#include "clang/AST/Attr.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000027#include "clang/AST/DeclObjC.h"
Vedant Kumar4593a462016-12-09 23:48:18 +000028#include "clang/AST/NSAPI.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000029#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "llvm/ADT/Hashing.h"
Alexey Bataevec474782014-10-09 08:45:04 +000031#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000032#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/Intrinsics.h"
34#include "llvm/IR/LLVMContext.h"
35#include "llvm/IR/MDBuilder.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000036#include "llvm/Support/ConvertUTF.h"
Peter Collingbourne3eea6772015-05-11 21:39:14 +000037#include "llvm/Support/MathExtras.h"
Filipe Cabecinhasab731f72016-05-12 16:51:36 +000038#include "llvm/Support/Path.h"
Peter Collingbournedc134532016-01-16 00:31:22 +000039#include "llvm/Transforms/Utils/SanitizerStats.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000040
Filipe Cabecinhas84171bd2016-12-12 16:43:40 +000041#include <string>
42
Chris Lattnere47e4402007-06-01 18:02:12 +000043using namespace clang;
44using namespace CodeGen;
45
Chris Lattnerd7f58862007-06-02 05:24:33 +000046//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000047// Miscellaneous Helper Methods
48//===--------------------------------------------------------------------===//
49
John McCallad7c5c12011-02-08 08:22:06 +000050llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
51 unsigned addressSpace =
Yaxun Liu39195062017-08-04 18:16:31 +000052 cast<llvm::PointerType>(value->getType())->getAddressSpace();
John McCallad7c5c12011-02-08 08:22:06 +000053
Chris Lattner2192fe52011-07-18 04:24:23 +000054 llvm::PointerType *destType = Int8PtrTy;
John McCallad7c5c12011-02-08 08:22:06 +000055 if (addressSpace)
56 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
57
58 if (value->getType() == destType) return value;
59 return Builder.CreateBitCast(value, destType);
60}
61
Chris Lattnere9a64532007-06-22 21:44:33 +000062/// CreateTempAlloca - This creates a alloca and inserts it into the entry
63/// block.
John McCall7f416cc2015-09-08 08:05:57 +000064Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
Yaxun Liu84744c12017-06-19 17:03:41 +000065 const Twine &Name,
66 llvm::Value *ArraySize,
67 bool CastToDefaultAddrSpace) {
68 auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
John McCall7f416cc2015-09-08 08:05:57 +000069 Alloca->setAlignment(Align.getQuantity());
Yaxun Liu84744c12017-06-19 17:03:41 +000070 llvm::Value *V = Alloca;
71 // Alloca always returns a pointer in alloca address space, which may
72 // be different from the type defined by the language. For example,
73 // in C++ the auto variables are in the default address space. Therefore
74 // cast alloca to the default address space when necessary.
75 if (CastToDefaultAddrSpace && getASTAllocaAddressSpace() != LangAS::Default) {
76 auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
Yaxun Liu9d33fb12017-07-18 14:46:03 +000077 auto CurIP = Builder.saveIP();
78 Builder.SetInsertPoint(AllocaInsertPt);
Yaxun Liu84744c12017-06-19 17:03:41 +000079 V = getTargetHooks().performAddrSpaceCast(
80 *this, V, getASTAllocaAddressSpace(), LangAS::Default,
81 Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
Yaxun Liu9d33fb12017-07-18 14:46:03 +000082 Builder.restoreIP(CurIP);
Yaxun Liu84744c12017-06-19 17:03:41 +000083 }
84
85 return Address(V, Align);
John McCall7f416cc2015-09-08 08:05:57 +000086}
87
Yaxun Liu84744c12017-06-19 17:03:41 +000088/// CreateTempAlloca - This creates an alloca and inserts it into the entry
89/// block if \p ArraySize is nullptr, otherwise inserts it at the current
90/// insertion point of the builder.
Chris Lattner2192fe52011-07-18 04:24:23 +000091llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Yaxun Liu84744c12017-06-19 17:03:41 +000092 const Twine &Name,
93 llvm::Value *ArraySize) {
94 if (ArraySize)
95 return Builder.CreateAlloca(Ty, ArraySize, Name);
Matt Arsenault502ad602017-04-10 22:28:02 +000096 return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
Yaxun Liu84744c12017-06-19 17:03:41 +000097 ArraySize, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +000098}
Chris Lattner8394d792007-06-05 20:53:16 +000099
John McCall7f416cc2015-09-08 08:05:57 +0000100/// CreateDefaultAlignTempAlloca - This creates an alloca with the
101/// default alignment of the corresponding LLVM type, which is *not*
102/// guaranteed to be related in any way to the expected alignment of
103/// an AST type that might have been lowered to Ty.
104Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
105 const Twine &Name) {
106 CharUnits Align =
107 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
108 return CreateTempAlloca(Ty, Align, Name);
109}
110
111void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
112 assert(isa<llvm::AllocaInst>(Var.getPointer()));
113 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
114 Store->setAlignment(Var.getAlignment().getQuantity());
John McCall2e6567a2010-04-22 01:10:34 +0000115 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +0000116 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
John McCall2e6567a2010-04-22 01:10:34 +0000117}
118
John McCall7f416cc2015-09-08 08:05:57 +0000119Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +0000120 CharUnits Align = getContext().getTypeAlignInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +0000121 return CreateTempAlloca(ConvertType(Ty), Align, Name);
Daniel Dunbard0049182010-02-16 19:44:13 +0000122}
123
Yaxun Liu84744c12017-06-19 17:03:41 +0000124Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
125 bool CastToDefaultAddrSpace) {
Daniel Dunbara7566f12010-02-09 02:48:28 +0000126 // FIXME: Should we prefer the preferred type alignment here?
Yaxun Liu84744c12017-06-19 17:03:41 +0000127 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name,
128 CastToDefaultAddrSpace);
John McCall7f416cc2015-09-08 08:05:57 +0000129}
130
131Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
Yaxun Liu84744c12017-06-19 17:03:41 +0000132 const Twine &Name,
133 bool CastToDefaultAddrSpace) {
134 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name, nullptr,
135 CastToDefaultAddrSpace);
Daniel Dunbara7566f12010-02-09 02:48:28 +0000136}
137
Chris Lattner8394d792007-06-05 20:53:16 +0000138/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
139/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000140llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000141 PGO.setCurrentStmt(E);
John McCall7a9aac22010-08-23 01:21:21 +0000142 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +0000143 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +0000144 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +0000145 }
John McCall7a9aac22010-08-23 01:21:21 +0000146
147 QualType BoolTy = getContext().BoolTy;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000148 SourceLocation Loc = E->getExprLoc();
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000149 if (!E->getType()->isAnyComplexType())
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000150 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +0000151
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000152 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
153 Loc);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000154}
155
John McCalla2342eb2010-12-05 02:00:02 +0000156/// EmitIgnoredExpr - Emit code to compute the specified expression,
157/// ignoring the result.
158void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
159 if (E->isRValue())
160 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
161
162 // Just emit it as an l-value and drop the result.
163 EmitLValue(E);
164}
165
John McCall7a626f62010-09-15 10:14:12 +0000166/// EmitAnyExpr - Emit code to compute the specified expression which
167/// can have any type. The result is returned as an RValue struct.
168/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000169/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000170RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
171 AggValueSlot aggSlot,
172 bool ignoreResult) {
John McCall47fb9502013-03-07 21:37:08 +0000173 switch (getEvaluationKind(E->getType())) {
174 case TEK_Scalar:
John McCall4e8ca4f2012-07-02 23:58:38 +0000175 return RValue::get(EmitScalarExpr(E, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000176 case TEK_Complex:
John McCall4e8ca4f2012-07-02 23:58:38 +0000177 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000178 case TEK_Aggregate:
179 if (!ignoreResult && aggSlot.isIgnored())
180 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
181 EmitAggExpr(E, aggSlot);
182 return aggSlot.asRValue();
183 }
184 llvm_unreachable("bad evaluation kind");
Chris Lattner4647a212007-08-31 22:49:20 +0000185}
186
Mike Stump4a3999f2009-09-09 13:00:44 +0000187/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
188/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000189RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
190 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000191
John McCall47fb9502013-03-07 21:37:08 +0000192 if (hasAggregateEvaluationKind(E->getType()))
John McCall7a626f62010-09-15 10:14:12 +0000193 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
194 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000195}
196
John McCall21886962010-04-21 10:05:39 +0000197/// EmitAnyExprToMem - Evaluate an expression into a given memory
198/// location.
199void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000200 Address Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000201 Qualifiers Quals,
202 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000203 // FIXME: This function should take an LValue as an argument.
John McCall47fb9502013-03-07 21:37:08 +0000204 switch (getEvaluationKind(E->getType())) {
205 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000206 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
John McCall47fb9502013-03-07 21:37:08 +0000207 /*isInit*/ false);
208 return;
209
210 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000211 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000212 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000213 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000214 AggValueSlot::IsAliased_t(!IsInit)));
John McCall47fb9502013-03-07 21:37:08 +0000215 return;
216 }
217
218 case TEK_Scalar: {
John McCall21886962010-04-21 10:05:39 +0000219 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000220 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000221 EmitStoreThroughLValue(RV, LV);
John McCall47fb9502013-03-07 21:37:08 +0000222 return;
John McCall21886962010-04-21 10:05:39 +0000223 }
John McCall47fb9502013-03-07 21:37:08 +0000224 }
225 llvm_unreachable("bad evaluation kind");
John McCall21886962010-04-21 10:05:39 +0000226}
227
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000228static void
229pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
John McCall7f416cc2015-09-08 08:05:57 +0000230 const Expr *E, Address ReferenceTemporary) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000231 // Objective-C++ ARC:
232 // If we are binding a reference to a temporary that has ownership, we
233 // need to perform retain/release operations on the temporary.
Richard Smith736a9472013-06-12 20:42:33 +0000234 //
235 // FIXME: This should be looking at E, not M.
John McCall460ce582015-10-22 18:38:17 +0000236 if (auto Lifetime = M->getType().getObjCLifetime()) {
237 switch (Lifetime) {
Richard Smith736a9472013-06-12 20:42:33 +0000238 case Qualifiers::OCL_None:
239 case Qualifiers::OCL_ExplicitNone:
240 // Carry on to normal cleanup handling.
241 break;
Sebastian Redl29526f02011-11-27 16:50:07 +0000242
Richard Smith736a9472013-06-12 20:42:33 +0000243 case Qualifiers::OCL_Autoreleasing:
244 // Nothing to do; cleaned up by an autorelease pool.
245 return;
246
247 case Qualifiers::OCL_Strong:
248 case Qualifiers::OCL_Weak:
249 switch (StorageDuration Duration = M->getStorageDuration()) {
250 case SD_Static:
251 // Note: we intentionally do not register a cleanup to release
252 // the object on program termination.
253 return;
254
255 case SD_Thread:
256 // FIXME: We should probably register a cleanup in this case.
257 return;
258
259 case SD_Automatic:
260 case SD_FullExpression:
Richard Smith736a9472013-06-12 20:42:33 +0000261 CodeGenFunction::Destroyer *Destroy;
262 CleanupKind CleanupKind;
263 if (Lifetime == Qualifiers::OCL_Strong) {
264 const ValueDecl *VD = M->getExtendingDecl();
265 bool Precise =
266 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
267 CleanupKind = CGF.getARCCleanupKind();
268 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
269 : &CodeGenFunction::destroyARCStrongImprecise;
270 } else {
271 // __weak objects always get EH cleanups; otherwise, exceptions
272 // could cause really nasty crashes instead of mere leaks.
273 CleanupKind = NormalAndEHCleanup;
274 Destroy = &CodeGenFunction::destroyARCWeak;
275 }
276 if (Duration == SD_FullExpression)
277 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000278 M->getType(), *Destroy,
Richard Smith736a9472013-06-12 20:42:33 +0000279 CleanupKind & EHCleanup);
280 else
281 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000282 M->getType(),
Richard Smith736a9472013-06-12 20:42:33 +0000283 *Destroy, CleanupKind & EHCleanup);
284 return;
285
286 case SD_Dynamic:
287 llvm_unreachable("temporary cannot have dynamic storage duration");
288 }
289 llvm_unreachable("unknown storage duration");
290 }
291 }
292
Craig Topper8a13c412014-05-21 05:09:00 +0000293 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
Richard Smith736a9472013-06-12 20:42:33 +0000294 if (const RecordType *RT =
295 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
296 // Get the destructor for the reference temporary.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000297 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith736a9472013-06-12 20:42:33 +0000298 if (!ClassDecl->hasTrivialDestructor())
299 ReferenceTemporaryDtor = ClassDecl->getDestructor();
300 }
301
302 if (!ReferenceTemporaryDtor)
303 return;
304
305 // Call the destructor for the temporary.
306 switch (M->getStorageDuration()) {
307 case SD_Static:
308 case SD_Thread: {
309 llvm::Constant *CleanupFn;
310 llvm::Constant *CleanupArg;
311 if (E->getType()->isArrayType()) {
312 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
John McCall7f416cc2015-09-08 08:05:57 +0000313 ReferenceTemporary, E->getType(),
David Blaikieebe87e12013-08-27 23:57:18 +0000314 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
315 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
Richard Smith736a9472013-06-12 20:42:33 +0000316 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
317 } else {
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000318 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
319 StructorType::Complete);
John McCall7f416cc2015-09-08 08:05:57 +0000320 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
Richard Smith736a9472013-06-12 20:42:33 +0000321 }
322 CGF.CGM.getCXXABI().registerGlobalDtor(
323 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
324 break;
325 }
326
327 case SD_FullExpression:
328 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
329 CodeGenFunction::destroyCXXObject,
330 CGF.getLangOpts().Exceptions);
331 break;
332
333 case SD_Automatic:
334 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
335 ReferenceTemporary, E->getType(),
336 CodeGenFunction::destroyCXXObject,
337 CGF.getLangOpts().Exceptions);
338 break;
339
340 case SD_Dynamic:
341 llvm_unreachable("temporary cannot have dynamic storage duration");
342 }
343}
344
Yaxun Liucbf647c2017-07-08 13:24:52 +0000345static Address createReferenceTemporary(CodeGenFunction &CGF,
346 const MaterializeTemporaryExpr *M,
347 const Expr *Inner) {
348 auto &TCG = CGF.getTargetHooks();
Richard Smith736a9472013-06-12 20:42:33 +0000349 switch (M->getStorageDuration()) {
350 case SD_FullExpression:
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000351 case SD_Automatic: {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000352 // If we have a constant temporary array or record try to promote it into a
353 // constant global under the same rules a normal constant would've been
354 // promoted. This is easier on the optimizer and generally emits fewer
355 // instructions.
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000356 QualType Ty = Inner->getType();
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000357 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000358 (Ty->isArrayType() || Ty->isRecordType()) &&
359 CGF.CGM.isTypeConstant(Ty, true))
John McCallde0fe072017-08-15 21:42:52 +0000360 if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
Yaxun Liucbf647c2017-07-08 13:24:52 +0000361 if (auto AddrSpace = CGF.getTarget().getConstantAddressSpace()) {
362 auto AS = AddrSpace.getValue();
363 auto *GV = new llvm::GlobalVariable(
364 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
365 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
366 llvm::GlobalValue::NotThreadLocal,
367 CGF.getContext().getTargetAddressSpace(AS));
368 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
369 GV->setAlignment(alignment.getQuantity());
370 llvm::Constant *C = GV;
371 if (AS != LangAS::Default)
372 C = TCG.performAddrSpaceCast(
373 CGF.CGM, GV, AS, LangAS::Default,
374 GV->getValueType()->getPointerTo(
375 CGF.getContext().getTargetAddressSpace(LangAS::Default)));
376 // FIXME: Should we put the new global into a COMDAT?
377 return Address(C, alignment);
378 }
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000379 }
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000380 return CGF.CreateMemTemp(Ty, "ref.tmp");
381 }
Richard Smith736a9472013-06-12 20:42:33 +0000382 case SD_Thread:
383 case SD_Static:
Hans Wennborgf9d865b2015-03-17 16:38:58 +0000384 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
Richard Smith736a9472013-06-12 20:42:33 +0000385
386 case SD_Dynamic:
387 llvm_unreachable("temporary can't have dynamic storage duration");
388 }
389 llvm_unreachable("unknown storage duration");
390}
391
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000392LValue CodeGenFunction::
393EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000394 const Expr *E = M->GetTemporaryExpr();
Richard Smith7c5d4dc2013-06-11 02:41:00 +0000395
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000396 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
397 // as that will cause the lifetime adjustment to be lost for ARC
John McCall460ce582015-10-22 18:38:17 +0000398 auto ownership = M->getType().getObjCLifetime();
399 if (ownership != Qualifiers::OCL_None &&
400 ownership != Qualifiers::OCL_ExplicitNone) {
John McCall7f416cc2015-09-08 08:05:57 +0000401 Address Object = createReferenceTemporary(*this, M, E);
402 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
403 Object = Address(llvm::ConstantExpr::getBitCast(Var,
404 ConvertTypeForMem(E->getType())
405 ->getPointerTo(Object.getAddressSpace())),
406 Object.getAlignment());
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000407
408 // createReferenceTemporary will promote the temporary to a global with a
409 // constant initializer if it can. It can only do this to a value of
410 // ARC-manageable type if the value is global and therefore "immune" to
411 // ref-counting operations. Therefore we have no need to emit either a
412 // dynamic initialization or a cleanup and we can just return the address
413 // of the temporary.
414 if (Var->hasInitializer())
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000415 return MakeAddrLValue(Object, M->getType(),
416 LValueBaseInfo(AlignmentSource::Decl, false));
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000417
Richard Smitha509f2f2013-06-14 03:07:01 +0000418 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
419 }
John McCall7f416cc2015-09-08 08:05:57 +0000420 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000421 LValueBaseInfo(AlignmentSource::Decl,
422 false));
Richard Smitha509f2f2013-06-14 03:07:01 +0000423
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000424 switch (getEvaluationKind(E->getType())) {
425 default: llvm_unreachable("expected scalar or aggregate expression");
426 case TEK_Scalar:
427 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
428 break;
429 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000430 EmitAggExpr(E, AggValueSlot::forAddr(Object,
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000431 E->getType().getQualifiers(),
432 AggValueSlot::IsDestructed,
433 AggValueSlot::DoesNotNeedGCBarriers,
434 AggValueSlot::IsNotAliased));
435 break;
436 }
437 }
Richard Smith736a9472013-06-12 20:42:33 +0000438
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000439 pushTemporaryCleanup(*this, M, E, Object);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000440 return RefTempDst;
Jordan Roseb1312a52013-04-11 00:58:58 +0000441 }
442
Richard Smithf3fabd22013-06-03 00:17:11 +0000443 SmallVector<const Expr *, 2> CommaLHSs;
Jordan Roseb1312a52013-04-11 00:58:58 +0000444 SmallVector<SubobjectAdjustment, 2> Adjustments;
Richard Smithf3fabd22013-06-03 00:17:11 +0000445 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
446
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000447 for (const auto &Ignored : CommaLHSs)
448 EmitIgnoredExpr(Ignored);
Richard Smithf3fabd22013-06-03 00:17:11 +0000449
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000450 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
Richard Smith736a9472013-06-12 20:42:33 +0000451 if (opaque->getType()->isRecordType()) {
452 assert(Adjustments.empty());
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000453 return EmitOpaqueValueLValue(opaque);
Jordan Roseb1312a52013-04-11 00:58:58 +0000454 }
455 }
456
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000457 // Create and initialize the reference temporary.
John McCall7f416cc2015-09-08 08:05:57 +0000458 Address Object = createReferenceTemporary(*this, M, E);
Yaxun Liucbf647c2017-07-08 13:24:52 +0000459 if (auto *Var = dyn_cast<llvm::GlobalVariable>(
460 Object.getPointer()->stripPointerCasts())) {
John McCall7f416cc2015-09-08 08:05:57 +0000461 Object = Address(llvm::ConstantExpr::getBitCast(
Yaxun Liucbf647c2017-07-08 13:24:52 +0000462 cast<llvm::Constant>(Object.getPointer()),
463 ConvertTypeForMem(E->getType())->getPointerTo()),
John McCall7f416cc2015-09-08 08:05:57 +0000464 Object.getAlignment());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000465 // If the temporary is a global and has a constant initializer or is a
466 // constant temporary that we promoted to a global, we may have already
467 // initialized it.
Richard Smitha509f2f2013-06-14 03:07:01 +0000468 if (!Var->hasInitializer()) {
469 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
470 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
471 }
472 } else {
Tim Shen421119f2016-07-01 21:08:47 +0000473 switch (M->getStorageDuration()) {
474 case SD_Automatic:
475 case SD_FullExpression:
476 if (auto *Size = EmitLifetimeStart(
477 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
478 Object.getPointer())) {
479 if (M->getStorageDuration() == SD_Automatic)
480 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
481 Object, Size);
482 else
483 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
484 Size);
485 }
486 break;
487 default:
488 break;
489 }
Richard Smitha509f2f2013-06-14 03:07:01 +0000490 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
491 }
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000492 pushTemporaryCleanup(*this, M, E, Object);
Jordan Roseb1312a52013-04-11 00:58:58 +0000493
Richard Smith736a9472013-06-12 20:42:33 +0000494 // Perform derived-to-base casts and/or field accesses, to get from the
495 // temporary object we created (and, potentially, for which we extended
496 // the lifetime) to the subobject we're binding the reference to.
497 for (unsigned I = Adjustments.size(); I != 0; --I) {
498 SubobjectAdjustment &Adjustment = Adjustments[I-1];
499 switch (Adjustment.Kind) {
500 case SubobjectAdjustment::DerivedToBaseAdjustment:
501 Object =
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000502 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
503 Adjustment.DerivedToBase.BasePath->path_begin(),
504 Adjustment.DerivedToBase.BasePath->path_end(),
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000505 /*NullCheckValue=*/ false, E->getExprLoc());
Richard Smith736a9472013-06-12 20:42:33 +0000506 break;
Richard Smithf3fabd22013-06-03 00:17:11 +0000507
Richard Smith736a9472013-06-12 20:42:33 +0000508 case SubobjectAdjustment::FieldAdjustment: {
John McCall7f416cc2015-09-08 08:05:57 +0000509 LValue LV = MakeAddrLValue(Object, E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000510 LValueBaseInfo(AlignmentSource::Decl, false));
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000511 LV = EmitLValueForField(LV, Adjustment.Field);
Richard Smith736a9472013-06-12 20:42:33 +0000512 assert(LV.isSimple() &&
513 "materialized temporary field is not a simple lvalue");
514 Object = LV.getAddress();
515 break;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000516 }
517
Richard Smith736a9472013-06-12 20:42:33 +0000518 case SubobjectAdjustment::MemberPointerAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000519 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
John McCall7f416cc2015-09-08 08:05:57 +0000520 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
521 Adjustment.Ptr.MPT);
Richard Smith736a9472013-06-12 20:42:33 +0000522 break;
523 }
524 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000525 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000526
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000527 return MakeAddrLValue(Object, M->getType(),
528 LValueBaseInfo(AlignmentSource::Decl, false));
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000529}
530
531RValue
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000532CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
533 // Emit the expression as an lvalue.
534 LValue LV = EmitLValue(E);
535 assert(LV.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000536 llvm::Value *Value = LV.getPointer();
Richard Smith736a9472013-06-12 20:42:33 +0000537
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000538 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000539 // C++11 [dcl.ref]p5 (as amended by core issue 453):
540 // If a glvalue to which a reference is directly bound designates neither
541 // an existing object or function of an appropriate type nor a region of
542 // storage of suitable size and alignment to contain an object of the
543 // reference's type, the behavior is undefined.
544 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000545 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000546 }
John McCall8680f872010-07-21 06:29:51 +0000547
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000548 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000549}
550
551
Mike Stump4a3999f2009-09-09 13:00:44 +0000552/// getAccessedFieldNo - Given an encoded value and a result number, return the
553/// input field number being accessed.
554unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000555 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000556 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
557 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000558}
559
Richard Smith4d3110a2012-10-25 02:14:12 +0000560/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
561static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
562 llvm::Value *High) {
563 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
564 llvm::Value *K47 = Builder.getInt64(47);
565 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
566 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
567 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
568 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
569 return Builder.CreateMul(B1, KMul);
570}
571
Vedant Kumar24792e32017-10-03 01:27:25 +0000572bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) {
573 return TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
574 TCK == TCK_UpcastToVirtualBase;
575}
576
577bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) {
578 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
579 return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
580 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
581 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
582 TCK == TCK_UpcastToVirtualBase);
583}
584
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000585bool CodeGenFunction::sanitizePerformTypeCheck() const {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000586 return SanOpts.has(SanitizerKind::Null) |
587 SanOpts.has(SanitizerKind::Alignment) |
588 SanOpts.has(SanitizerKind::ObjectSize) |
589 SanOpts.has(SanitizerKind::Vptr);
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000590}
591
Richard Smithe30752c2012-10-09 19:52:38 +0000592void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +0000593 llvm::Value *Ptr, QualType Ty,
Vedant Kumar18348ea2017-02-17 23:22:55 +0000594 CharUnits Alignment,
595 SanitizerSet SkippedChecks) {
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000596 if (!sanitizePerformTypeCheck())
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000597 return;
598
Richard Smith2d8b2942012-11-01 07:22:08 +0000599 // Don't check pointers outside the default address space. The null check
600 // isn't correct, the object-size check isn't supported by LLVM, and we can't
601 // communicate the addresses to the runtime handler for the vptr check.
John McCall7f416cc2015-09-08 08:05:57 +0000602 if (Ptr->getType()->getPointerAddressSpace())
Richard Smith2d8b2942012-11-01 07:22:08 +0000603 return;
604
Vedant Kumarc420d142017-06-16 03:27:36 +0000605 // Don't check pointers to volatile data. The behavior here is implementation-
606 // defined.
607 if (Ty.isVolatileQualified())
608 return;
609
Alexey Samsonov24cad992014-07-17 18:46:27 +0000610 SanitizerScope SanScope(this);
611
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000612 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
Craig Topper8a13c412014-05-21 05:09:00 +0000613 llvm::BasicBlock *Done = nullptr;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000614
Vedant Kumare859ebb2017-04-26 02:17:21 +0000615 // Quickly determine whether we have a pointer to an alloca. It's possible
616 // to skip null checks, and some alignment checks, for these pointers. This
617 // can reduce compile-time significantly.
618 auto PtrToAlloca =
619 dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCastsNoFollowAliases());
620
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000621 llvm::Value *IsNonNull = nullptr;
622 bool IsGuaranteedNonNull =
623 SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
Vedant Kumar24792e32017-10-03 01:27:25 +0000624 bool AllowNullPointers = isNullPointerAllowed(TCK);
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000625 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000626 !IsGuaranteedNonNull) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000627 // The glvalue must not be an empty glvalue.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000628 IsNonNull = Builder.CreateIsNotNull(Ptr);
Richard Smith2c5868c2013-02-13 21:18:23 +0000629
Vedant Kumardbbdda42017-04-17 22:26:10 +0000630 // The IR builder can constant-fold the null check if the pointer points to
631 // a constant.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000632 IsGuaranteedNonNull =
Vedant Kumardbbdda42017-04-17 22:26:10 +0000633 IsNonNull == llvm::ConstantInt::getTrue(getLLVMContext());
634
635 // Skip the null check if the pointer is known to be non-null.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000636 if (!IsGuaranteedNonNull) {
Vedant Kumardbbdda42017-04-17 22:26:10 +0000637 if (AllowNullPointers) {
638 // When performing pointer casts, it's OK if the value is null.
639 // Skip the remaining checks in that case.
640 Done = createBasicBlock("null");
641 llvm::BasicBlock *Rest = createBasicBlock("not.null");
642 Builder.CreateCondBr(IsNonNull, Rest, Done);
643 EmitBlock(Rest);
644 } else {
645 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
646 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000647 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000648 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000649
Vedant Kumar18348ea2017-02-17 23:22:55 +0000650 if (SanOpts.has(SanitizerKind::ObjectSize) &&
651 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
652 !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000653 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000654
Richard Smith69d0d262012-08-24 00:54:33 +0000655 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000656 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000657 // to check this.
Matt Arsenault2f152632013-10-07 19:00:18 +0000658 // FIXME: Get object address space
659 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
660 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smith69d0d262012-08-24 00:54:33 +0000661 llvm::Value *Min = Builder.getFalse();
George Burgess IVa63f9152017-03-21 20:09:35 +0000662 llvm::Value *NullIsUnknown = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +0000663 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
George Burgess IVa63f9152017-03-21 20:09:35 +0000664 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
665 Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}),
666 llvm::ConstantInt::get(IntPtrTy, Size));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000667 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
Richard Smithe30752c2012-10-09 19:52:38 +0000668 }
Richard Smith69d0d262012-08-24 00:54:33 +0000669
Richard Smithb1b0ab42012-11-05 22:21:05 +0000670 uint64_t AlignVal = 0;
Vedant Kumar8a715332017-10-03 01:27:24 +0000671 llvm::Value *PtrAsInt = nullptr;
Richard Smithb1b0ab42012-11-05 22:21:05 +0000672
Vedant Kumar18348ea2017-02-17 23:22:55 +0000673 if (SanOpts.has(SanitizerKind::Alignment) &&
674 !SkippedChecks.has(SanitizerKind::Alignment)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000675 AlignVal = Alignment.getQuantity();
676 if (!Ty->isIncompleteType() && !AlignVal)
677 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
678
Richard Smith69d0d262012-08-24 00:54:33 +0000679 // The glvalue must be suitably aligned.
Vedant Kumare859ebb2017-04-26 02:17:21 +0000680 if (AlignVal > 1 &&
681 (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
Vedant Kumar8a715332017-10-03 01:27:24 +0000682 PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
683 llvm::Value *Align = Builder.CreateAnd(
684 PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000685 llvm::Value *Aligned =
Vedant Kumar8a715332017-10-03 01:27:24 +0000686 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000687 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000688 }
Richard Smith69d0d262012-08-24 00:54:33 +0000689 }
690
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000691 if (Checks.size() > 0) {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000692 // Make sure we're not losing information. Alignment needs to be a power of
693 // 2
694 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
Richard Smithe30752c2012-10-09 19:52:38 +0000695 llvm::Constant *StaticData[] = {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000696 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
697 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
698 llvm::ConstantInt::get(Int8Ty, TCK)};
Vedant Kumar8a715332017-10-03 01:27:24 +0000699 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData,
700 PtrAsInt ? PtrAsInt : Ptr);
Richard Smithe30752c2012-10-09 19:52:38 +0000701 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000702
Richard Smithb1b0ab42012-11-05 22:21:05 +0000703 // If possible, check that the vptr indicates that there is a subobject of
704 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000705 //
706 // C++11 [basic.life]p5,6:
707 // [For storage which does not refer to an object within its lifetime]
708 // The program has undefined behavior if:
709 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000710 // or call a non-static member function
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000711 if (SanOpts.has(SanitizerKind::Vptr) &&
Vedant Kumar24792e32017-10-03 01:27:25 +0000712 !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000713 // Ensure that the pointer is non-null before loading it. If there is no
Vedant Kumara0c36712017-08-02 18:10:31 +0000714 // compile-time guarantee, reuse the run-time null check or emit a new one.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000715 if (!IsGuaranteedNonNull) {
Vedant Kumara0c36712017-08-02 18:10:31 +0000716 if (!IsNonNull)
717 IsNonNull = Builder.CreateIsNotNull(Ptr);
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000718 if (!Done)
719 Done = createBasicBlock("vptr.null");
720 llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
721 Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
722 EmitBlock(VptrNotNull);
723 }
724
Richard Smith4d3110a2012-10-25 02:14:12 +0000725 // Compute a hash of the mangled name of the type.
726 //
727 // FIXME: This is not guaranteed to be deterministic! Move to a
728 // fingerprinting mechanism once LLVM provides one. For the time
729 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000730 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000731 llvm::raw_svector_ostream Out(MangledName);
732 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
733 Out);
Richard Smith4d3110a2012-10-25 02:14:12 +0000734
Alexey Samsonov84856012014-07-10 22:34:19 +0000735 // Blacklist based on the mangled type.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000736 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +0000737 SanitizerKind::Vptr, Out.str())) {
Alexey Samsonov84856012014-07-10 22:34:19 +0000738 llvm::hash_code TypeHash = hash_value(Out.str());
Richard Smith4d3110a2012-10-25 02:14:12 +0000739
Alexey Samsonov84856012014-07-10 22:34:19 +0000740 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
741 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
742 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
John McCall7f416cc2015-09-08 08:05:57 +0000743 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000744 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
745 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
Richard Smith4d3110a2012-10-25 02:14:12 +0000746
Alexey Samsonov84856012014-07-10 22:34:19 +0000747 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
748 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
Richard Smith4d3110a2012-10-25 02:14:12 +0000749
Alexey Samsonov84856012014-07-10 22:34:19 +0000750 // Look the hash up in our cache.
751 const int CacheSize = 128;
752 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
753 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
754 "__ubsan_vptr_type_cache");
755 llvm::Value *Slot = Builder.CreateAnd(Hash,
756 llvm::ConstantInt::get(IntPtrTy,
757 CacheSize-1));
758 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
759 llvm::Value *CacheVal =
John McCall7f416cc2015-09-08 08:05:57 +0000760 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
761 getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000762
763 // If the hash isn't in the cache, call a runtime handler to perform the
764 // hard work of checking whether the vptr is for an object of the right
765 // type. This will either fill in the cache and return, or produce a
766 // diagnostic.
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000767 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
Alexey Samsonov84856012014-07-10 22:34:19 +0000768 llvm::Constant *StaticData[] = {
769 EmitCheckSourceLocation(Loc),
770 EmitCheckTypeDescriptor(Ty),
771 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
772 llvm::ConstantInt::get(Int8Ty, TCK)
773 };
John McCall7f416cc2015-09-08 08:05:57 +0000774 llvm::Value *DynamicData[] = { Ptr, Hash };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000775 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000776 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
777 DynamicData);
Alexey Samsonov84856012014-07-10 22:34:19 +0000778 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000779 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000780
781 if (Done) {
782 Builder.CreateBr(Done);
783 EmitBlock(Done);
784 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000785}
Chris Lattner4647a212007-08-31 22:49:20 +0000786
Richard Smith539e4a72013-02-23 02:53:19 +0000787/// Determine whether this expression refers to a flexible array member in a
788/// struct. We disable array bounds checks for such members.
789static bool isFlexibleArrayMemberExpr(const Expr *E) {
790 // For compatibility with existing code, we treat arrays of length 0 or
791 // 1 as flexible array members.
792 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000793 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000794 if (CAT->getSize().ugt(1))
795 return false;
796 } else if (!isa<IncompleteArrayType>(AT))
797 return false;
798
799 E = E->IgnoreParens();
800
801 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000802 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000803 // FIXME: If the base type of the member expr is not FD->getParent(),
804 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000805 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith539e4a72013-02-23 02:53:19 +0000806 RecordDecl::field_iterator FI(
807 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
808 return ++FI == FD->getParent()->field_end();
809 }
Vedant Kumare356f1a2016-10-04 20:36:04 +0000810 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
811 return IRE->getDecl()->getNextIvar() == nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000812 }
813
814 return false;
815}
816
817/// If Base is known to point to the start of an array, return the length of
818/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000819static llvm::Value *getArrayIndexingBound(
820 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000821 // For the vector indexing extension, the bound is the number of elements.
822 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
823 IndexedType = Base->getType();
824 return CGF.Builder.getInt32(VT->getNumElements());
825 }
826
827 Base = Base->IgnoreParens();
828
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000829 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000830 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
831 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
832 IndexedType = CE->getSubExpr()->getType();
833 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000834 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000835 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000836 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000837 return CGF.getVLASize(VAT).first;
838 }
839 }
840
Craig Topper8a13c412014-05-21 05:09:00 +0000841 return nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000842}
843
844void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
845 llvm::Value *Index, QualType IndexType,
846 bool Accessed) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000847 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
Richard Smith6b53e222013-10-22 22:51:04 +0000848 "should not be called unless adding bounds checks");
Alexey Samsonov24cad992014-07-17 18:46:27 +0000849 SanitizerScope SanScope(this);
Richard Smith2847b222013-02-24 01:56:24 +0000850
Richard Smith539e4a72013-02-23 02:53:19 +0000851 QualType IndexedType;
852 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
853 if (!Bound)
854 return;
855
856 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
857 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
858 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
859
860 llvm::Constant *StaticData[] = {
861 EmitCheckSourceLocation(E->getExprLoc()),
862 EmitCheckTypeDescriptor(IndexedType),
863 EmitCheckTypeDescriptor(IndexType)
864 };
865 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
866 : Builder.CreateICmpULE(IndexVal, BoundVal);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000867 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
868 SanitizerHandler::OutOfBounds, StaticData, Index);
Richard Smith539e4a72013-02-23 02:53:19 +0000869}
870
Chris Lattner116ce8f2010-01-09 21:40:03 +0000871
Chris Lattner116ce8f2010-01-09 21:40:03 +0000872CodeGenFunction::ComplexPairTy CodeGenFunction::
873EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
874 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000875 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +0000876
Chris Lattner116ce8f2010-01-09 21:40:03 +0000877 llvm::Value *NextVal;
878 if (isa<llvm::IntegerType>(InVal.first->getType())) {
879 uint64_t AmountVal = isInc ? 1 : -1;
880 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +0000881
Chris Lattner116ce8f2010-01-09 21:40:03 +0000882 // Add the inc/dec to the real part.
883 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
884 } else {
885 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
886 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
887 if (!isInc)
888 FVal.changeSign();
889 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
Craig Topper99e79272013-07-26 05:59:26 +0000890
Chris Lattner116ce8f2010-01-09 21:40:03 +0000891 // Add the inc/dec to the real part.
892 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
893 }
Craig Topper99e79272013-07-26 05:59:26 +0000894
Chris Lattner116ce8f2010-01-09 21:40:03 +0000895 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +0000896
Chris Lattner116ce8f2010-01-09 21:40:03 +0000897 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +0000898 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Craig Topper99e79272013-07-26 05:59:26 +0000899
Chris Lattner116ce8f2010-01-09 21:40:03 +0000900 // If this is a postinc, return the value read from memory, otherwise use the
901 // updated value.
902 return isPre ? IncVal : InVal;
903}
904
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000905void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
906 CodeGenFunction *CGF) {
907 // Bind VLAs in the cast type.
908 if (CGF && E->getType()->isVariablyModifiedType())
909 CGF->EmitVariablyModifiedType(E->getType());
910
911 if (CGDebugInfo *DI = getModuleDebugInfo())
912 DI->EmitExplicitCastType(E->getType());
913}
914
Chris Lattnera45c5af2007-06-02 19:47:04 +0000915//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000916// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000917//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000918
John McCall7f416cc2015-09-08 08:05:57 +0000919/// EmitPointerWithAlignment - Given an expression of pointer type, try to
920/// derive a more accurate bound on the alignment of the pointer.
921Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000922 LValueBaseInfo *BaseInfo) {
John McCall7f416cc2015-09-08 08:05:57 +0000923 // We allow this with ObjC object pointers because of fragile ABIs.
924 assert(E->getType()->isPointerType() ||
925 E->getType()->isObjCObjectPointerType());
926 E = E->IgnoreParens();
927
928 // Casts:
929 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000930 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
931 CGM.EmitExplicitCastExprType(ECE, this);
John McCall7f416cc2015-09-08 08:05:57 +0000932
933 switch (CE->getCastKind()) {
934 // Non-converting casts (but not C's implicit conversion from void*).
935 case CK_BitCast:
936 case CK_NoOp:
Anastasia Stulova0a72ed42017-09-27 14:37:00 +0000937 case CK_AddressSpaceConversion:
John McCall7f416cc2015-09-08 08:05:57 +0000938 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
939 if (PtrTy->getPointeeType()->isVoidType())
940 break;
941
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000942 LValueBaseInfo InnerInfo;
943 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerInfo);
944 if (BaseInfo) *BaseInfo = InnerInfo;
John McCall7f416cc2015-09-08 08:05:57 +0000945
946 // If this is an explicit bitcast, and the source l-value is
947 // opaque, honor the alignment of the casted-to type.
948 if (isa<ExplicitCastExpr>(CE) &&
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000949 InnerInfo.getAlignmentSource() != AlignmentSource::Decl) {
950 LValueBaseInfo ExpInfo;
951 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(),
952 &ExpInfo);
953 if (BaseInfo)
954 BaseInfo->mergeForCast(ExpInfo);
955 Addr = Address(Addr.getPointer(), Align);
John McCall7f416cc2015-09-08 08:05:57 +0000956 }
957
Peter Collingbourne574975e2016-01-14 02:49:48 +0000958 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
959 CE->getCastKind() == CK_BitCast) {
Peter Collingbourneee381ff2015-09-09 00:01:31 +0000960 if (auto PT = E->getType()->getAs<PointerType>())
961 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
962 /*MayBeNull=*/true,
963 CodeGenFunction::CFITCK_UnrelatedCast,
964 CE->getLocStart());
965 }
Anastasia Stulova0a72ed42017-09-27 14:37:00 +0000966 return CE->getCastKind() != CK_AddressSpaceConversion
967 ? Builder.CreateBitCast(Addr, ConvertType(E->getType()))
968 : Builder.CreateAddrSpaceCast(Addr,
969 ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +0000970 }
971 break;
972
973 // Array-to-pointer decay.
974 case CK_ArrayToPointerDecay:
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000975 return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000976
977 // Derived-to-base conversions.
978 case CK_UncheckedDerivedToBase:
979 case CK_DerivedToBase: {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000980 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000981 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
982 return GetAddressOfBaseClass(Addr, Derived,
983 CE->path_begin(), CE->path_end(),
984 ShouldNullCheckClassCastValue(CE),
985 CE->getExprLoc());
986 }
987
988 // TODO: Is there any reason to treat base-to-derived conversions
989 // specially?
990 default:
991 break;
992 }
993 }
994
995 // Unary &.
996 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
997 if (UO->getOpcode() == UO_AddrOf) {
998 LValue LV = EmitLValue(UO->getSubExpr());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000999 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
John McCall7f416cc2015-09-08 08:05:57 +00001000 return LV.getAddress();
1001 }
1002 }
1003
1004 // TODO: conditional operators, comma.
1005
1006 // Otherwise, use the alignment of the type.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001007 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +00001008 return Address(EmitScalarExpr(E), Align);
1009}
1010
Daniel Dunbarc79407f2009-02-05 07:09:07 +00001011RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001012 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001013 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +00001014
1015 switch (getEvaluationKind(Ty)) {
1016 case TEK_Complex: {
1017 llvm::Type *EltTy =
1018 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +00001019 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +00001020 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001021 }
Craig Topper99e79272013-07-26 05:59:26 +00001022
Chris Lattner65526f02010-08-23 05:26:13 +00001023 // If this is a use of an undefined aggregate type, the aggregate must have an
1024 // identifiable address. Just because the contents of the value are undefined
1025 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +00001026 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00001027 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +00001028 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +00001029 }
John McCall47fb9502013-03-07 21:37:08 +00001030
1031 case TEK_Scalar:
1032 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1033 }
1034 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +00001035}
1036
Daniel Dunbarc79407f2009-02-05 07:09:07 +00001037RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
1038 const char *Name) {
1039 ErrorUnsupported(E, Name);
1040 return GetUndefRValue(E->getType());
1041}
1042
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001043LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
1044 const char *Name) {
1045 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001046 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00001047 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
1048 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001049}
1050
Vedant Kumarffd7c882017-04-14 22:03:34 +00001051bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001052 const Expr *Base = Obj;
1053 while (!isa<CXXThisExpr>(Base)) {
1054 // The result of a dynamic_cast can be null.
1055 if (isa<CXXDynamicCastExpr>(Base))
1056 return false;
1057
1058 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1059 Base = CE->getSubExpr();
1060 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
1061 Base = PE->getSubExpr();
1062 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1063 if (UO->getOpcode() == UO_Extension)
1064 Base = UO->getSubExpr();
1065 else
1066 return false;
1067 } else {
1068 return false;
1069 }
1070 }
1071 return true;
1072}
1073
Richard Smith4d1458e2012-09-08 02:08:36 +00001074LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +00001075 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001076 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +00001077 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1078 else
1079 LV = EmitLValue(E);
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001080 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1081 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00001082 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1083 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1084 if (IsBaseCXXThis)
1085 SkippedChecks.set(SanitizerKind::Alignment, true);
1086 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001087 SkippedChecks.set(SanitizerKind::Null, true);
Vedant Kumarffd7c882017-04-14 22:03:34 +00001088 }
John McCall7f416cc2015-09-08 08:05:57 +00001089 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001090 E->getType(), LV.getAlignment(), SkippedChecks);
1091 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +00001092 return LV;
1093}
1094
Chris Lattner8394d792007-06-05 20:53:16 +00001095/// EmitLValue - Emit code to compute a designator that specifies the location
1096/// of the expression.
1097///
Mike Stump4a3999f2009-09-09 13:00:44 +00001098/// This can return one of two things: a simple address or a bitfield reference.
1099/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1100/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +00001101///
Mike Stump4a3999f2009-09-09 13:00:44 +00001102/// If this returns a bitfield reference, nothing about the pointee type of the
1103/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +00001104///
Mike Stump4a3999f2009-09-09 13:00:44 +00001105/// If this returns a normal address, and if the lvalue's C type is fixed size,
1106/// this method guarantees that the returned pointer type will point to an LLVM
1107/// type of the same size of the lvalue's type. If the lvalue has a variable
1108/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +00001109///
Chris Lattnerd7f58862007-06-02 05:24:33 +00001110LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +00001111 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +00001112 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001113 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +00001114
John McCallc109a252011-11-07 03:59:57 +00001115 case Expr::ObjCPropertyRefExprClass:
1116 llvm_unreachable("cannot emit a property reference directly");
1117
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00001118 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +00001119 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00001120 case Expr::ObjCIsaExprClass:
1121 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001122 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00001123 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001124 case Expr::CompoundAssignOperatorClass: {
1125 QualType Ty = E->getType();
1126 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1127 Ty = AT->getValueType();
1128 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +00001129 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1130 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001131 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001132 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +00001133 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001134 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001135 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001136 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00001137 case Expr::VAArgExprClass:
1138 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001139 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001140 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +00001141 case Expr::ParenExprClass:
1142 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +00001143 case Expr::GenericSelectionExprClass:
1144 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +00001145 case Expr::PredefinedExprClass:
1146 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +00001147 case Expr::StringLiteralClass:
1148 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001149 case Expr::ObjCEncodeExprClass:
1150 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +00001151 case Expr::PseudoObjectExprClass:
1152 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001153 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +00001154 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +00001155 case Expr::CXXTemporaryObjectExprClass:
1156 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001157 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1158 case Expr::CXXBindTemporaryExprClass:
1159 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +00001160 case Expr::CXXUuidofExprClass:
1161 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +00001162 case Expr::LambdaExprClass:
1163 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +00001164
1165 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001166 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +00001167 enterFullExpression(cleanups);
1168 RunCleanupsScope Scope(*this);
Reid Kleckner092d0652017-03-06 22:18:34 +00001169 LValue LV = EmitLValue(cleanups->getSubExpr());
1170 if (LV.isSimple()) {
1171 // Defend against branches out of gnu statement expressions surrounded by
1172 // cleanups.
1173 llvm::Value *V = LV.getPointer();
1174 Scope.ForceCleanup({&V});
1175 return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001176 getContext(), LV.getBaseInfo(),
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00001177 LV.getTBAAAccessType());
Reid Kleckner092d0652017-03-06 22:18:34 +00001178 }
1179 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1180 // bitfield lvalue or some other non-simple lvalue?
1181 return LV;
John McCall08ef4662011-11-10 08:15:53 +00001182 }
1183
Anders Carlsson52ce3bb2009-11-14 01:51:50 +00001184 case Expr::CXXDefaultArgExprClass:
1185 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001186 case Expr::CXXDefaultInitExprClass: {
1187 CXXDefaultInitExprScope Scope(*this);
1188 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1189 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001190 case Expr::CXXTypeidExprClass:
1191 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001192
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001193 case Expr::ObjCMessageExprClass:
1194 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001195 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001196 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001197 case Expr::StmtExprClass:
1198 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001199 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001200 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001201 case Expr::ArraySubscriptExprClass:
1202 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001203 case Expr::OMPArraySectionExprClass:
1204 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001205 case Expr::ExtVectorElementExprClass:
1206 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001207 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001208 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001209 case Expr::CompoundLiteralExprClass:
1210 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001211 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001212 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001213 case Expr::BinaryConditionalOperatorClass:
1214 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001215 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001216 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001217 case Expr::OpaqueValueExprClass:
1218 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001219 case Expr::SubstNonTypeTemplateParmExprClass:
1220 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001221 case Expr::ImplicitCastExprClass:
1222 case Expr::CStyleCastExprClass:
1223 case Expr::CXXFunctionalCastExprClass:
1224 case Expr::CXXStaticCastExprClass:
1225 case Expr::CXXDynamicCastExprClass:
1226 case Expr::CXXReinterpretCastExprClass:
1227 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001228 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001229 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001230
Douglas Gregorfe314812011-06-21 17:03:29 +00001231 case Expr::MaterializeTemporaryExprClass:
1232 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Eric Fiseliercddaf872017-06-15 19:43:36 +00001233
1234 case Expr::CoawaitExprClass:
1235 return EmitCoawaitLValue(cast<CoawaitExpr>(E));
1236 case Expr::CoyieldExprClass:
1237 return EmitCoyieldLValue(cast<CoyieldExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001238 }
1239}
1240
John McCall71335052012-03-10 03:05:10 +00001241/// Given an object of the given canonical type, can we safely copy a
1242/// value out of it based on its initializer?
1243static bool isConstantEmittableObjectType(QualType type) {
1244 assert(type.isCanonical());
1245 assert(!type->isReferenceType());
1246
1247 // Must be const-qualified but non-volatile.
1248 Qualifiers qs = type.getLocalQualifiers();
1249 if (!qs.hasConst() || qs.hasVolatile()) return false;
1250
1251 // Otherwise, all object types satisfy this except C++ classes with
1252 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001253 if (const auto *RT = dyn_cast<RecordType>(type))
1254 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001255 if (RD->hasMutableFields() || !RD->isTrivial())
1256 return false;
1257
1258 return true;
1259}
1260
1261/// Can we constant-emit a load of a reference to a variable of the
1262/// given type? This is different from predicates like
1263/// Decl::isUsableInConstantExpressions because we do want it to apply
1264/// in situations that don't necessarily satisfy the language's rules
1265/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1266/// to do this with const float variables even if those variables
1267/// aren't marked 'constexpr'.
1268enum ConstantEmissionKind {
1269 CEK_None,
1270 CEK_AsReferenceOnly,
1271 CEK_AsValueOrReference,
1272 CEK_AsValueOnly
1273};
1274static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1275 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001276 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001277 if (isConstantEmittableObjectType(ref->getPointeeType()))
1278 return CEK_AsValueOrReference;
1279 return CEK_AsReferenceOnly;
1280 }
1281 if (isConstantEmittableObjectType(type))
1282 return CEK_AsValueOnly;
1283 return CEK_None;
1284}
1285
1286/// Try to emit a reference to the given value without producing it as
1287/// an l-value. This is actually more than an optimization: we can't
1288/// produce an l-value for variables that we never actually captured
1289/// in a block or lambda, which means const int variables or constexpr
1290/// literals or similar.
1291CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001292CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1293 ValueDecl *value = refExpr->getDecl();
1294
John McCall71335052012-03-10 03:05:10 +00001295 // The value needs to be an enum constant or a constant variable.
1296 ConstantEmissionKind CEK;
1297 if (isa<ParmVarDecl>(value)) {
1298 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001299 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001300 CEK = checkVarTypeForConstantEmission(var->getType());
1301 } else if (isa<EnumConstantDecl>(value)) {
1302 CEK = CEK_AsValueOnly;
1303 } else {
1304 CEK = CEK_None;
1305 }
1306 if (CEK == CEK_None) return ConstantEmission();
1307
John McCall71335052012-03-10 03:05:10 +00001308 Expr::EvalResult result;
1309 bool resultIsReference;
1310 QualType resultType;
1311
1312 // It's best to evaluate all the way as an r-value if that's permitted.
1313 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001314 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001315 resultIsReference = false;
1316 resultType = refExpr->getType();
1317
1318 // Otherwise, try to evaluate as an l-value.
1319 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001320 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001321 resultIsReference = true;
1322 resultType = value->getType();
1323
1324 // Failure.
1325 } else {
1326 return ConstantEmission();
1327 }
1328
1329 // In any case, if the initializer has side-effects, abandon ship.
1330 if (result.HasSideEffects)
1331 return ConstantEmission();
1332
1333 // Emit as a constant.
John McCallde0fe072017-08-15 21:42:52 +00001334 auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
1335 result.Val, resultType);
John McCall71335052012-03-10 03:05:10 +00001336
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001337 // Make sure we emit a debug reference to the global variable.
1338 // This should probably fire even for
1339 if (isa<VarDecl>(value)) {
1340 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001341 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001342 } else {
1343 assert(isa<EnumConstantDecl>(value));
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001344 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001345 }
John McCall71335052012-03-10 03:05:10 +00001346
1347 // If we emitted a reference constant, we need to dereference that.
1348 if (resultIsReference)
1349 return ConstantEmission::forReference(C);
1350
1351 return ConstantEmission::forValue(C);
1352}
1353
Alex Lorenz6cc83172017-08-25 10:07:00 +00001354static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
1355 const MemberExpr *ME) {
1356 if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
1357 // Try to emit static variable member expressions as DREs.
1358 return DeclRefExpr::Create(
1359 CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD,
1360 /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
1361 ME->getType(), ME->getValueKind());
1362 }
1363 return nullptr;
1364}
1365
1366CodeGenFunction::ConstantEmission
1367CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
1368 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
1369 return tryEmitAsConstant(DRE);
1370 return ConstantEmission();
1371}
1372
Nick Lewycky2d84e842013-10-02 02:29:49 +00001373llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1374 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +00001375 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001376 lvalue.getType(), Loc, lvalue.getBaseInfo(),
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00001377 lvalue.getTBAAAccessType(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001378 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1379 lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001380}
1381
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001382static bool hasBooleanRepresentation(QualType Ty) {
1383 if (Ty->isBooleanType())
1384 return true;
1385
1386 if (const EnumType *ET = Ty->getAs<EnumType>())
1387 return ET->getDecl()->getIntegerType()->isBooleanType();
1388
Douglas Gregor298f43d2012-04-12 20:42:30 +00001389 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1390 return hasBooleanRepresentation(AT->getValueType());
1391
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001392 return false;
1393}
1394
Richard Smith1629da92012-12-13 07:11:50 +00001395static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1396 llvm::APInt &Min, llvm::APInt &End,
Vedant Kumar4593a462016-12-09 23:48:18 +00001397 bool StrictEnums, bool IsBool) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001398 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001399 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1400 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001401 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001402 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001403
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001404 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001405 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1406 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001407 } else {
1408 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001409 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001410 unsigned Bitwidth = LTy->getScalarSizeInBits();
1411 unsigned NumNegativeBits = ED->getNumNegativeBits();
1412 unsigned NumPositiveBits = ED->getNumPositiveBits();
1413
1414 if (NumNegativeBits) {
1415 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1416 assert(NumBits <= Bitwidth);
1417 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1418 Min = -End;
1419 } else {
1420 assert(NumPositiveBits <= Bitwidth);
1421 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1422 Min = llvm::APInt(Bitwidth, 0);
1423 }
1424 }
Richard Smith1629da92012-12-13 07:11:50 +00001425 return true;
1426}
1427
1428llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1429 llvm::APInt Min, End;
Vedant Kumar4593a462016-12-09 23:48:18 +00001430 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1431 hasBooleanRepresentation(Ty)))
Craig Topper8a13c412014-05-21 05:09:00 +00001432 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001433
Duncan Sandsc720e782012-04-15 18:04:54 +00001434 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001435 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001436}
1437
Vedant Kumar5a972652017-02-27 19:46:19 +00001438bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1439 SourceLocation Loc) {
1440 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1441 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1442 if (!HasBoolCheck && !HasEnumCheck)
1443 return false;
1444
1445 bool IsBool = hasBooleanRepresentation(Ty) ||
1446 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1447 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1448 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1449 if (!NeedsBoolCheck && !NeedsEnumCheck)
1450 return false;
1451
Vedant Kumar129edab2017-03-09 16:06:27 +00001452 // Single-bit booleans don't need to be checked. Special-case this to avoid
1453 // a bit width mismatch when handling bitfield values. This is handled by
1454 // EmitFromMemory for the non-bitfield case.
1455 if (IsBool &&
1456 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1457 return false;
1458
Vedant Kumar5a972652017-02-27 19:46:19 +00001459 llvm::APInt Min, End;
1460 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1461 return true;
1462
Vedant Kumar791f7012017-10-03 01:27:26 +00001463 auto &Ctx = getLLVMContext();
Vedant Kumar5a972652017-02-27 19:46:19 +00001464 SanitizerScope SanScope(this);
1465 llvm::Value *Check;
1466 --End;
1467 if (!Min) {
Vedant Kumar791f7012017-10-03 01:27:26 +00001468 Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
Vedant Kumar5a972652017-02-27 19:46:19 +00001469 } else {
Vedant Kumar791f7012017-10-03 01:27:26 +00001470 llvm::Value *Upper =
1471 Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
1472 llvm::Value *Lower =
1473 Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
Vedant Kumar5a972652017-02-27 19:46:19 +00001474 Check = Builder.CreateAnd(Upper, Lower);
1475 }
1476 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1477 EmitCheckTypeDescriptor(Ty)};
1478 SanitizerMask Kind =
1479 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1480 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1481 StaticArgs, EmitCheckValue(Value));
1482 return true;
1483}
1484
John McCall7f416cc2015-09-08 08:05:57 +00001485llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1486 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001487 SourceLocation Loc,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001488 LValueBaseInfo BaseInfo,
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00001489 llvm::MDNode *TBAAAccessType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001490 QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001491 uint64_t TBAAOffset,
1492 bool isNontemporal) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001493 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1494 // For better performance, handle vector loads differently.
1495 if (Ty->isVectorType()) {
1496 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001497
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001498 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001499
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001500 // Handle vectors of size 3 like size 4 for better performance.
1501 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001502
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001503 // Bitcast to vec4 type.
1504 llvm::VectorType *vec4Ty =
1505 llvm::VectorType::get(VTy->getElementType(), 4);
1506 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1507 // Now load value.
1508 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001509
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001510 // Shuffle vector to get vec3.
1511 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1512 {0, 1, 2}, "extractVec");
1513 return EmitFromMemory(V, Ty);
1514 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001515 }
1516 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001517
1518 // Atomic operations have to be done on integral types.
David Majnemera38c9f12016-05-24 16:09:25 +00001519 LValue AtomicLValue =
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00001520 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAAccessType);
David Majnemera38c9f12016-05-24 16:09:25 +00001521 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1522 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001523 }
Craig Topper99e79272013-07-26 05:59:26 +00001524
John McCall7f416cc2015-09-08 08:05:57 +00001525 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001526 if (isNontemporal) {
1527 llvm::MDNode *Node = llvm::MDNode::get(
1528 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1529 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1530 }
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00001531 if (TBAAAccessType) {
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00001532 bool MayAlias = BaseInfo.getMayAlias();
1533 llvm::MDNode *TBAA = MayAlias
Ivan A. Kosarev5c8e7592017-10-02 11:10:04 +00001534 ? CGM.getTBAAMayAliasTypeInfo()
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00001535 : CGM.getTBAAStructTagInfo(TBAABaseType, TBAAAccessType, TBAAOffset);
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00001536 if (TBAA)
1537 CGM.DecorateInstructionWithTBAA(Load, TBAA, MayAlias);
Manman Renc451e572013-04-04 21:53:22 +00001538 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001539
Vedant Kumar5a972652017-02-27 19:46:19 +00001540 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1541 // In order to prevent the optimizer from throwing away the check, don't
1542 // attach range metadata to the load.
Richard Smith1629da92012-12-13 07:11:50 +00001543 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001544 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1545 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001546
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001547 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001548}
1549
John McCall3a7f6922010-10-27 20:58:56 +00001550llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1551 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001552 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001553 // This should really always be an i1, but sometimes it's already
1554 // an i8, and it's awkward to track those cases down.
1555 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001556 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1557 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1558 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001559 }
1560
1561 return Value;
1562}
1563
1564llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1565 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001566 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001567 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1568 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001569 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1570 }
1571
1572 return Value;
1573}
1574
John McCall7f416cc2015-09-08 08:05:57 +00001575void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1576 bool Volatile, QualType Ty,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001577 LValueBaseInfo BaseInfo,
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00001578 llvm::MDNode *TBAAAccessType,
Manman Renc451e572013-04-04 21:53:22 +00001579 bool isInit, QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001580 uint64_t TBAAOffset,
1581 bool isNontemporal) {
Craig Topper99e79272013-07-26 05:59:26 +00001582
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001583 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1584 // Handle vectors differently to get better performance.
1585 if (Ty->isVectorType()) {
1586 llvm::Type *SrcTy = Value->getType();
Simon Pilgrima5dbbc62017-06-01 20:13:34 +00001587 auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001588 // Handle vec3 special.
Simon Pilgrima5dbbc62017-06-01 20:13:34 +00001589 if (VecTy && VecTy->getNumElements() == 3) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001590 // Our source is a vec3, do a shuffle vector to make it a vec4.
1591 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1592 Builder.getInt32(2),
1593 llvm::UndefValue::get(Builder.getInt32Ty())};
1594 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1595 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
1596 MaskV, "extractVec");
1597 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1598 }
1599 if (Addr.getElementType() != SrcTy) {
1600 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1601 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001602 }
1603 }
Craig Topper99e79272013-07-26 05:59:26 +00001604
John McCall3a7f6922010-10-27 20:58:56 +00001605 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001606
David Majnemera38c9f12016-05-24 16:09:25 +00001607 LValue AtomicLValue =
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00001608 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAAccessType);
David Majnemera5b195a2015-02-14 01:35:12 +00001609 if (Ty->isAtomicType() ||
David Majnemera38c9f12016-05-24 16:09:25 +00001610 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1611 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
John McCalla8ec7eb2013-03-07 21:37:17 +00001612 return;
1613 }
1614
Daniel Dunbar03816342010-08-21 02:24:36 +00001615 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001616 if (isNontemporal) {
1617 llvm::MDNode *Node =
1618 llvm::MDNode::get(Store->getContext(),
1619 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1620 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1621 }
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00001622 if (TBAAAccessType) {
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00001623 bool MayAlias = BaseInfo.getMayAlias();
1624 llvm::MDNode *TBAA = MayAlias
Ivan A. Kosarev5c8e7592017-10-02 11:10:04 +00001625 ? CGM.getTBAAMayAliasTypeInfo()
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00001626 : CGM.getTBAAStructTagInfo(TBAABaseType, TBAAAccessType, TBAAOffset);
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00001627 if (TBAA)
1628 CGM.DecorateInstructionWithTBAA(Store, TBAA, MayAlias);
Manman Renc451e572013-04-04 21:53:22 +00001629 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001630}
1631
David Chisnallfa35df62012-01-16 17:27:18 +00001632void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001633 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001634 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001635 lvalue.getType(), lvalue.getBaseInfo(),
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00001636 lvalue.getTBAAAccessType(), isInit,
1637 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1638 lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001639}
1640
Mike Stump4a3999f2009-09-09 13:00:44 +00001641/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1642/// method emits the address of the lvalue, then loads the result as an rvalue,
1643/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001644RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001645 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001646 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001647 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001648 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1649 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001650 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001651 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001652 // In MRC mode, we do a load+autorelease.
1653 if (!getLangOpts().ObjCAutoRefCount) {
1654 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1655 }
1656
1657 // In ARC mode, we load retained and then consume the value.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001658 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1659 Object = EmitObjCConsumeObject(LV.getType(), Object);
1660 return RValue::get(Object);
1661 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001662
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001663 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001664 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001665
John McCalla1dee5302010-08-22 10:59:02 +00001666 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001667 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001668 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001669
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001670 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001671 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001672 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001673 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001674 "vecext"));
1675 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001676
1677 // If this is a reference to a subset of the elements of a vector, either
1678 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001679 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001680 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001681
Renato Golin230c5eb2014-05-19 18:15:42 +00001682 // Global Register variables always invoke intrinsics
1683 if (LV.isGlobalReg())
1684 return EmitLoadOfGlobalRegLValue(LV);
1685
John McCallc109a252011-11-07 03:59:57 +00001686 assert(LV.isBitField() && "Unknown LValue type!");
Vedant Kumar129edab2017-03-09 16:06:27 +00001687 return EmitLoadOfBitfieldLValue(LV, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +00001688}
1689
Vedant Kumar129edab2017-03-09 16:06:27 +00001690RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1691 SourceLocation Loc) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001692 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001693
Daniel Dunbar3447a022010-04-13 23:34:15 +00001694 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001695 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001696
John McCall7f416cc2015-09-08 08:05:57 +00001697 Address Ptr = LV.getBitFieldAddress();
1698 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001699
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001700 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001701 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001702 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1703 if (HighBits)
1704 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1705 if (Info.Offset + HighBits)
1706 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1707 } else {
1708 if (Info.Offset)
1709 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001710 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001711 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1712 Info.Size),
1713 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001714 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001715 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Vedant Kumar129edab2017-03-09 16:06:27 +00001716 EmitScalarRangeCheck(Val, LV.getType(), Loc);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001717 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001718}
1719
Nate Begemanb699c9b2009-01-18 06:42:49 +00001720// If this is a reference to a subset of the elements of a vector, create an
1721// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001722RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001723 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1724 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001725
Nate Begemanf322eab2008-05-09 06:41:27 +00001726 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001727
1728 // If the result of the expression is a non-vector type, we must be extracting
1729 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001730 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001731 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001732 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001733 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001734 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001735 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001736
1737 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001738 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001739
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001740 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001741 for (unsigned i = 0; i != NumResultElts; ++i)
1742 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001743
Chris Lattner91c08ad2011-02-15 00:14:06 +00001744 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1745 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001746 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001747 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001748}
1749
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001750/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001751Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1752 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001753 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1754 QualType EQT = ExprVT->getElementType();
1755 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001756
John McCall7f416cc2015-09-08 08:05:57 +00001757 Address CastToPointerElement =
1758 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1759 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001760
1761 const llvm::Constant *Elts = LV.getExtVectorElts();
1762 unsigned ix = getAccessedFieldNo(0, Elts);
1763
John McCall7f416cc2015-09-08 08:05:57 +00001764 Address VectorBasePtrPlusIx =
1765 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1766 getContext().getTypeSizeInChars(EQT),
1767 "vector.elt");
1768
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001769 return VectorBasePtrPlusIx;
1770}
1771
Renato Golin230c5eb2014-05-19 18:15:42 +00001772/// @brief Load of global gamed gegisters are always calls to intrinsics.
1773RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001774 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1775 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001776 llvm::MDNode *RegName = cast<llvm::MDNode>(
1777 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001778
1779 // We accept integer and pointer types only
1780 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1781 llvm::Type *Ty = OrigTy;
1782 if (OrigTy->isPointerTy())
1783 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1784 llvm::Type *Types[] = { Ty };
1785
Renato Golin230c5eb2014-05-19 18:15:42 +00001786 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001787 llvm::Value *Call = Builder.CreateCall(
1788 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001789 if (OrigTy->isPointerTy())
1790 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001791 return RValue::get(Call);
1792}
Chris Lattner40ff7012007-08-03 16:18:34 +00001793
Chris Lattner9369a562007-06-29 16:31:29 +00001794
Chris Lattner8394d792007-06-05 20:53:16 +00001795/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1796/// lvalue, where both are guaranteed to the have the same type, and that type
1797/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001798void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001799 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001800 if (!Dst.isSimple()) {
1801 if (Dst.isVectorElt()) {
1802 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001803 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1804 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001805 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001806 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001807 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1808 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001809 return;
1810 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001811
Nate Begemance4d7fc2008-04-18 23:10:10 +00001812 // If this is an update of extended vector elements, insert them as
1813 // appropriate.
1814 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001815 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001816
Renato Golin230c5eb2014-05-19 18:15:42 +00001817 if (Dst.isGlobalReg())
1818 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1819
John McCallc109a252011-11-07 03:59:57 +00001820 assert(Dst.isBitField() && "Unknown LValue type");
1821 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001822 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001823
John McCall31168b02011-06-15 23:02:42 +00001824 // There's special magic for assigning into an ARC-qualified l-value.
1825 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1826 switch (Lifetime) {
1827 case Qualifiers::OCL_None:
1828 llvm_unreachable("present but none");
1829
1830 case Qualifiers::OCL_ExplicitNone:
1831 // nothing special
1832 break;
1833
1834 case Qualifiers::OCL_Strong:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001835 if (isInit) {
1836 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1837 break;
1838 }
John McCall55e1fbc2011-06-25 02:11:03 +00001839 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001840 return;
1841
1842 case Qualifiers::OCL_Weak:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001843 if (isInit)
1844 // Initialize and then skip the primitive store.
1845 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1846 else
1847 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001848 return;
1849
1850 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001851 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1852 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001853 // fall into the normal path
1854 break;
1855 }
1856 }
1857
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001858 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001859 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001860 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001861 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001862 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001863 return;
1864 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001865
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001866 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001867 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001868 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001869 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001870 if (Dst.isObjCIvar()) {
1871 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001872 llvm::Type *ResultType = IntPtrTy;
1873 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1874 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001875 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001876 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001877 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1878 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001879 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001880 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001881 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001882 } else if (Dst.isGlobalObjCRef()) {
1883 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1884 Dst.isThreadLocalRef());
1885 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001886 else
1887 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001888 return;
1889 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001890
Chris Lattner6278e6a2007-08-11 00:04:45 +00001891 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001892 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001893}
1894
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001895void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001896 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001897 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001898 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001899 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001900
Daniel Dunbar67aba792010-04-15 03:47:33 +00001901 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001902 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001903
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001904 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001905 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001906 /*IsSigned=*/false);
1907 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001908
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001909 // See if there are other bits in the bitfield's storage we'll need to load
1910 // and mask together with source before storing.
1911 if (Info.StorageSize != Info.Size) {
1912 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001913 llvm::Value *Val =
1914 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001915
1916 // Mask the source value as needed.
1917 if (!hasBooleanRepresentation(Dst.getType()))
1918 SrcVal = Builder.CreateAnd(SrcVal,
1919 llvm::APInt::getLowBitsSet(Info.StorageSize,
1920 Info.Size),
1921 "bf.value");
1922 MaskedVal = SrcVal;
1923 if (Info.Offset)
1924 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1925
1926 // Mask out the original value.
1927 Val = Builder.CreateAnd(Val,
1928 ~llvm::APInt::getBitsSet(Info.StorageSize,
1929 Info.Offset,
1930 Info.Offset + Info.Size),
1931 "bf.clear");
1932
1933 // Or together the unchanged values and the source value.
1934 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1935 } else {
1936 assert(Info.Offset == 0);
1937 }
1938
1939 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001940 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001941
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001942 // Return the new value of the bit-field, if requested.
1943 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001944 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001945
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001946 // Sign extend the value if needed.
1947 if (Info.IsSigned) {
1948 assert(Info.Size <= Info.StorageSize);
1949 unsigned HighBits = Info.StorageSize - Info.Size;
1950 if (HighBits) {
1951 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1952 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1953 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001954 }
1955
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001956 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1957 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001958 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001959 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001960}
1961
Nate Begemance4d7fc2008-04-18 23:10:10 +00001962void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001963 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001964 // This access turns into a read/modify/write of the vector. Load the input
1965 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001966 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1967 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001968 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001969
Chris Lattner4647a212007-08-31 22:49:20 +00001970 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001971
John McCall55e1fbc2011-06-25 02:11:03 +00001972 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001973 unsigned NumSrcElts = VTy->getNumElements();
Craig Topperf2f1a092016-07-08 02:17:35 +00001974 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001975 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001976 // Use shuffle vector is the src and destination are the same number of
1977 // elements and restore the vector mask since it is on the side it will be
1978 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001979 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001980 for (unsigned i = 0; i != NumSrcElts; ++i)
1981 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001982
Chris Lattner91c08ad2011-02-15 00:14:06 +00001983 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001984 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001985 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001986 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001987 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001988 // Extended the source vector to the same length and then shuffle it
1989 // into the destination.
1990 // FIXME: since we're shuffling with undef, can we just use the indices
1991 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001992 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001993 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001994 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001995 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001996 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001997 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001998 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001999 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002000 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00002001 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002002 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002003 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002004 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002005
Joey Goulycf4143b2013-11-21 17:09:05 +00002006 // When the vector size is odd and .odd or .hi is used, the last element
2007 // of the Elts constant array will be one past the size of the vector.
2008 // Ignore the last element here, if it is greater than the mask size.
2009 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
2010 NumSrcElts--;
2011
Nate Begemanb699c9b2009-01-18 06:42:49 +00002012 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002013 for (unsigned i = 0; i != NumSrcElts; ++i)
2014 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00002015 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002016 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00002017 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00002018 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00002019 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00002020 }
2021 } else {
2022 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00002023 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00002024 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002025 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00002026 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002027
John McCall7f416cc2015-09-08 08:05:57 +00002028 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
2029 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00002030}
2031
Renato Golin230c5eb2014-05-19 18:15:42 +00002032/// @brief Store of global named registers are always calls to intrinsics.
2033void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00002034 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
2035 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002036 llvm::MDNode *RegName = cast<llvm::MDNode>(
2037 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00002038 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00002039
2040 // We accept integer and pointer types only
2041 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
2042 llvm::Type *Ty = OrigTy;
2043 if (OrigTy->isPointerTy())
2044 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2045 llvm::Type *Types[] = { Ty };
2046
Renato Golin230c5eb2014-05-19 18:15:42 +00002047 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
2048 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00002049 if (OrigTy->isPointerTy())
2050 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00002051 Builder.CreateCall(
2052 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00002053}
2054
Eric Christopherc9e2a682014-05-20 17:10:39 +00002055// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002056// generating write-barries API. It is currently a global, ivar,
2057// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002058static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002059 LValue &LV,
2060 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002061 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002062 return;
Craig Topper99e79272013-07-26 05:59:26 +00002063
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002064 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002065 QualType ExpTy = E->getType();
2066 if (IsMemberAccess && ExpTy->isPointerType()) {
2067 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00002068 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002069 // writer-barrier conservatively.
2070 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2071 if (ExpTy->isRecordType()) {
2072 LV.setObjCIvar(false);
2073 return;
2074 }
2075 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002076 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002077 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002078 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002079 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002080 return;
2081 }
Craig Topper99e79272013-07-26 05:59:26 +00002082
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002083 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
2084 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00002085 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002086 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00002087 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002088 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002089 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002090 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002091 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002092 }
Craig Topper99e79272013-07-26 05:59:26 +00002093
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002094 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002095 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002096 return;
2097 }
Craig Topper99e79272013-07-26 05:59:26 +00002098
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002099 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002100 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002101 if (LV.isObjCIvar()) {
2102 // If cast is to a structure pointer, follow gcc's behavior and make it
2103 // a non-ivar write-barrier.
2104 QualType ExpTy = E->getType();
2105 if (ExpTy->isPointerType())
2106 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2107 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00002108 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002109 }
2110 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002111 }
Peter Collingbourne91147592011-04-15 00:35:48 +00002112
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002113 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00002114 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2115 return;
2116 }
2117
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002118 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002119 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002120 return;
2121 }
Craig Topper99e79272013-07-26 05:59:26 +00002122
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002123 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002124 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002125 return;
2126 }
John McCall31168b02011-06-15 23:02:42 +00002127
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002128 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002129 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00002130 return;
2131 }
2132
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002133 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002134 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00002135 if (LV.isObjCIvar() && !LV.isObjCArray())
2136 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002137 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00002138 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002139 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00002140 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002141 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002142 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002143 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002144 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002145
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002146 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002147 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002148 // We don't know if member is an 'ivar', but this flag is looked at
2149 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002150 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002151 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002152 }
2153}
2154
Chris Lattner3f32d692011-07-12 06:52:18 +00002155static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00002156EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00002157 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002158 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00002159 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00002160 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00002161}
2162
Alexey Bataev97720002014-11-11 04:05:39 +00002163static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00002164 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2165 llvm::Type *RealVarTy, SourceLocation Loc) {
2166 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2167 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002168 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2169 return CGF.MakeAddrLValue(Addr, T, BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +00002170}
2171
2172Address CodeGenFunction::EmitLoadOfReference(Address Addr,
2173 const ReferenceType *RefTy,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002174 LValueBaseInfo *BaseInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002175 llvm::Value *Ptr = Builder.CreateLoad(Addr);
2176 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002177 BaseInfo, /*forPointee*/ true));
John McCall7f416cc2015-09-08 08:05:57 +00002178}
2179
2180LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
2181 const ReferenceType *RefTy) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002182 LValueBaseInfo BaseInfo;
2183 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &BaseInfo);
2184 return MakeAddrLValue(Addr, RefTy->getPointeeType(), BaseInfo);
Alexey Bataev97720002014-11-11 04:05:39 +00002185}
2186
Alexey Bataev31300ed2016-02-04 11:27:03 +00002187Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2188 const PointerType *PtrTy,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002189 LValueBaseInfo *BaseInfo) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00002190 llvm::Value *Addr = Builder.CreateLoad(Ptr);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002191 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(),
2192 BaseInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00002193 /*forPointeeType=*/true));
2194}
2195
2196LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2197 const PointerType *PtrTy) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002198 LValueBaseInfo BaseInfo;
2199 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo);
2200 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00002201}
2202
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002203static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2204 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00002205 QualType T = E->getType();
2206
2207 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00002208 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2209 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00002210 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2211
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002212 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002213 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2214 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00002215 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00002216 Address Addr(V, Alignment);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002217 LValue LV;
Alexey Bataev97720002014-11-11 04:05:39 +00002218 // Emit reference to the private copy of the variable if it is an OpenMP
2219 // threadprivate variable.
2220 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00002221 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002222 E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00002223 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2224 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002225 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002226 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2227 LV = CGF.MakeAddrLValue(Addr, T, BaseInfo);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002228 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002229 setObjCGCLValueClass(CGF.getContext(), E, LV);
2230 return LV;
2231}
2232
John McCallb92ab1a2016-10-26 23:46:34 +00002233static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2234 const FunctionDecl *FD) {
2235 if (FD->hasAttr<WeakRefAttr>()) {
2236 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2237 return aliasee.getPointer();
2238 }
2239
2240 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002241 if (!FD->hasPrototype()) {
2242 if (const FunctionProtoType *Proto =
2243 FD->getType()->getAs<FunctionProtoType>()) {
2244 // Ugly case: for a K&R-style definition, the type of the definition
2245 // isn't the same as the type of a use. Correct for this with a
2246 // bitcast.
2247 QualType NoProtoType =
John McCallb92ab1a2016-10-26 23:46:34 +00002248 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2249 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2250 V = llvm::ConstantExpr::getBitCast(V,
2251 CGM.getTypes().ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002252 }
2253 }
John McCallb92ab1a2016-10-26 23:46:34 +00002254 return V;
2255}
2256
2257static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2258 const Expr *E, const FunctionDecl *FD) {
2259 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
Eli Friedmana0544d62011-12-03 04:14:32 +00002260 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002261 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2262 return CGF.MakeAddrLValue(V, E->getType(), Alignment, BaseInfo);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002263}
2264
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00002265static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2266 llvm::Value *ThisValue) {
2267 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2268 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2269 return CGF.EmitLValueForField(LV, FD);
2270}
2271
Renato Golin230c5eb2014-05-19 18:15:42 +00002272/// Named Registers are named metadata pointing to the register name
2273/// which will be read from/written to as an argument to the intrinsic
2274/// @llvm.read/write_register.
2275/// So far, only the name is being passed down, but other options such as
2276/// register type, allocation type or even optimization options could be
2277/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002278static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002279 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002280 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002281 assert(Asm->getLabel().size() < 64-Name.size() &&
2282 "Register name too big");
2283 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002284 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002285 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002286 if (M->getNumOperands() == 0) {
2287 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2288 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002289 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002290 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2291 }
John McCall7f416cc2015-09-08 08:05:57 +00002292
2293 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2294
2295 llvm::Value *Ptr =
2296 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2297 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002298}
2299
Chris Lattnerd7f58862007-06-02 05:24:33 +00002300LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002301 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002302 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002303
Renato Goline7b3d5d2014-05-27 16:46:27 +00002304 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2305 // Global Named registers access via intrinsics only
2306 if (VD->getStorageClass() == SC_Register &&
2307 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002308 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002309
Renato Goline7b3d5d2014-05-27 16:46:27 +00002310 // A DeclRefExpr for a reference initialized by a constant expression can
2311 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002312 const Expr *Init = VD->getAnyInitializer(VD);
2313 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2314 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002315 VD->checkInitIsICE() &&
2316 // Do not emit if it is private OpenMP variable.
2317 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2318 LocalDeclMap.count(VD))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002319 llvm::Constant *Val =
John McCallde0fe072017-08-15 21:42:52 +00002320 ConstantEmitter(*this).emitAbstract(E->getLocation(),
2321 *VD->evaluateValue(),
2322 VD->getType());
Richard Smith5a1104b2012-10-20 01:38:33 +00002323 assert(Val && "failed to emit reference constant expression");
2324 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002325
2326 // Should we be using the alignment of the constant pointer we emitted?
2327 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2328 /*pointee*/ true);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002329 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2330 return MakeAddrLValue(Address(Val, Alignment), T, BaseInfo);
Richard Smith5a1104b2012-10-20 01:38:33 +00002331 }
David Majnemer602cfe72015-01-01 09:49:44 +00002332
2333 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002334 if (E->refersToEnclosingVariableOrCapture()) {
Alexey Bataev6a71f362017-08-22 17:54:52 +00002335 VD = VD->getCanonicalDecl();
David Majnemer602cfe72015-01-01 09:49:44 +00002336 if (auto *FD = LambdaCaptureFields.lookup(VD))
2337 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2338 else if (CapturedStmtInfo) {
Alexey Bataevac5eabb2016-11-07 11:16:04 +00002339 auto I = LocalDeclMap.find(VD);
2340 if (I != LocalDeclMap.end()) {
2341 if (auto RefTy = VD->getType()->getAs<ReferenceType>())
2342 return EmitLoadOfReferenceLValue(I->second, RefTy);
2343 return MakeAddrLValue(I->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002344 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002345 LValue CapLVal =
2346 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2347 CapturedStmtInfo->getContextValue());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002348 bool MayAlias = CapLVal.getBaseInfo().getMayAlias();
Alexey Bataevc71a4092015-09-11 10:29:41 +00002349 return MakeAddrLValue(
2350 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002351 CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl, MayAlias));
David Majnemer602cfe72015-01-01 09:49:44 +00002352 }
John McCall7f416cc2015-09-08 08:05:57 +00002353
David Majnemer602cfe72015-01-01 09:49:44 +00002354 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002355 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002356 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2357 return MakeAddrLValue(addr, T, BaseInfo);
David Majnemer602cfe72015-01-01 09:49:44 +00002358 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002359 }
2360
Eli Friedman5720e342012-01-21 04:52:58 +00002361 // FIXME: We should be able to assert this for FunctionDecls as well!
2362 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2363 // those with a valid source location.
2364 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2365 !E->getLocation().isValid()) &&
2366 "Should not use decl without marking it used!");
2367
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002368 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002369 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002370 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002371 return MakeAddrLValue(Aliasee, T,
2372 LValueBaseInfo(AlignmentSource::Decl, false));
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002373 }
2374
Renato Goline7b3d5d2014-05-27 16:46:27 +00002375 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002376 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002377 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002378 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002379
John McCall7f416cc2015-09-08 08:05:57 +00002380 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002381
John McCall7f416cc2015-09-08 08:05:57 +00002382 // The variable should generally be present in the local decl map.
2383 auto iter = LocalDeclMap.find(VD);
2384 if (iter != LocalDeclMap.end()) {
2385 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002386
John McCall7f416cc2015-09-08 08:05:57 +00002387 // Otherwise, it might be static local we haven't emitted yet for
2388 // some reason; most likely, because it's in an outer function.
2389 } else if (VD->isStaticLocal()) {
2390 addr = Address(CGM.getOrCreateStaticVarDecl(
2391 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2392 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002393
John McCall7f416cc2015-09-08 08:05:57 +00002394 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002395 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002396 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2397 }
2398
2399
2400 // Check for OpenMP threadprivate variables.
2401 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2402 return EmitThreadPrivateVarDeclLValue(
2403 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2404 E->getExprLoc());
2405 }
2406
2407 // Drill into block byref variables.
2408 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2409 if (isBlockByref) {
2410 addr = emitBlockByrefAddress(addr, VD);
2411 }
2412
2413 // Drill into reference types.
2414 LValue LV;
2415 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2416 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2417 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002418 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2419 LV = MakeAddrLValue(addr, T, BaseInfo);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002420 }
Chris Lattner3f32d692011-07-12 06:52:18 +00002421
John McCallcdda29c2013-03-13 03:10:54 +00002422 bool isLocalStorage = VD->hasLocalStorage();
2423
2424 bool NonGCable = isLocalStorage &&
2425 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002426 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002427 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002428 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002429 LV.setNonGC(true);
2430 }
John McCallcdda29c2013-03-13 03:10:54 +00002431
2432 bool isImpreciseLifetime =
2433 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2434 if (isImpreciseLifetime)
2435 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002436 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002437 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002438 }
John McCallf3a88602011-02-03 08:15:49 +00002439
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002440 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002441 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002442
Richard Smithda383632016-08-15 01:33:41 +00002443 // FIXME: While we're emitting a binding from an enclosing scope, all other
2444 // DeclRefExprs we see should be implicitly treated as if they also refer to
2445 // an enclosing scope.
2446 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2447 return EmitLValue(BD->getBinding());
2448
David Blaikie83d382b2011-09-23 05:06:16 +00002449 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002450}
Chris Lattnere47e4402007-06-01 18:02:12 +00002451
Chris Lattner8394d792007-06-05 20:53:16 +00002452LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2453 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002454 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002455 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002456
Chris Lattner0f398c42008-07-26 22:37:01 +00002457 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002458 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002459 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002460 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002461 QualType T = E->getSubExpr()->getType()->getPointeeType();
2462 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002463
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002464 LValueBaseInfo BaseInfo;
2465 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo);
2466 LValue LV = MakeAddrLValue(Addr, T, BaseInfo);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002467 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002468
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002469 // We should not generate __weak write barrier on indirect reference
2470 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2471 // But, we continue to generate __strong write barrier on indirect write
2472 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002473 if (getLangOpts().ObjC1 &&
2474 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002475 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002476 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002477 return LV;
2478 }
John McCalle3027922010-08-25 11:45:40 +00002479 case UO_Real:
2480 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002481 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002482 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002483
Richard Smith0b6b8e42012-02-18 20:53:32 +00002484 // __real is valid on scalars. This is a faster way of testing that.
2485 // __imag can only produce an rvalue on scalars.
2486 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002487 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002488 assert(E->getSubExpr()->getType()->isArithmeticType());
2489 return LV;
2490 }
2491
Alexey Bataev611b0a12016-11-07 18:15:02 +00002492 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
John McCalla2342eb2010-12-05 02:00:02 +00002493
John McCall7f416cc2015-09-08 08:05:57 +00002494 Address Component =
2495 (E->getOpcode() == UO_Real
2496 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2497 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002498 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo());
Alexey Bataev611b0a12016-11-07 18:15:02 +00002499 ElemLV.getQuals().addQualifiers(LV.getQuals());
2500 return ElemLV;
Chris Lattner595db862007-10-30 22:53:42 +00002501 }
John McCalle3027922010-08-25 11:45:40 +00002502 case UO_PreInc:
2503 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002504 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002505 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002506
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002507 if (E->getType()->isAnyComplexType())
2508 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2509 else
2510 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2511 return LV;
2512 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002513 }
Chris Lattner8394d792007-06-05 20:53:16 +00002514}
2515
Chris Lattner4347e3692007-06-06 04:54:52 +00002516LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002517 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002518 E->getType(),
2519 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattner4347e3692007-06-06 04:54:52 +00002520}
2521
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002522LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002523 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002524 E->getType(),
2525 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002526}
2527
Mike Stump4a3999f2009-09-09 13:00:44 +00002528LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002529 auto SL = E->getFunctionName();
2530 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2531 StringRef FnName = CurFn->getName();
2532 if (FnName.startswith("\01"))
2533 FnName = FnName.substr(1);
2534 StringRef NameItems[] = {
2535 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2536 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002537 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002538 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2539 std::string Name = SL->getString();
2540 if (!Name.empty()) {
2541 unsigned Discriminator =
2542 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2543 if (Discriminator)
2544 Name += "_" + Twine(Discriminator + 1).str();
2545 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002546 return MakeAddrLValue(C, E->getType(), BaseInfo);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002547 } else {
2548 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002549 return MakeAddrLValue(C, E->getType(), BaseInfo);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002550 }
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002551 }
Alexey Bataevec474782014-10-09 08:45:04 +00002552 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002553 return MakeAddrLValue(C, E->getType(), BaseInfo);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002554}
2555
Richard Smithe30752c2012-10-09 19:52:38 +00002556/// Emit a type description suitable for use by a runtime sanitizer library. The
2557/// format of a type descriptor is
2558///
2559/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002560/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002561/// \endcode
2562///
Richard Smith683398a2012-10-09 23:55:19 +00002563/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2564/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002565llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002566 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002567 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002568 return C;
2569
Richard Smithe30752c2012-10-09 19:52:38 +00002570 uint16_t TypeKind = -1;
2571 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002572
Richard Smithe30752c2012-10-09 19:52:38 +00002573 if (T->isIntegerType()) {
2574 TypeKind = 0;
2575 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002576 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002577 } else if (T->isFloatingType()) {
2578 TypeKind = 1;
2579 TypeInfo = getContext().getTypeSize(T);
2580 }
2581
2582 // Format the type name as if for a diagnostic, including quotes and
2583 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002584 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002585 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2586 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002587 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002588 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002589
2590 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002591 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2592 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002593 };
2594 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2595
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002596 auto *GV = new llvm::GlobalVariable(
2597 CGM.getModule(), Descriptor->getType(),
2598 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002599 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002600 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002601
2602 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002603 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002604
Richard Smithe30752c2012-10-09 19:52:38 +00002605 return GV;
2606}
2607
2608llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2609 llvm::Type *TargetTy = IntPtrTy;
2610
Vedant Kumar8a715332017-10-03 01:27:24 +00002611 if (V->getType() == TargetTy)
2612 return V;
2613
Richard Smith48366f72013-03-22 00:47:07 +00002614 // Floating-point types which fit into intptr_t are bitcast to integers
2615 // and then passed directly (after zero-extension, if necessary).
2616 if (V->getType()->isFloatingPointTy()) {
2617 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2618 if (Bits <= TargetTy->getIntegerBitWidth())
2619 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2620 Bits));
2621 }
2622
Richard Smithe30752c2012-10-09 19:52:38 +00002623 // Integers which fit in intptr_t are zero-extended and passed directly.
2624 if (V->getType()->isIntegerTy() &&
2625 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2626 return Builder.CreateZExt(V, TargetTy);
2627
2628 // Pointers are passed directly, everything else is passed by address.
2629 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002630 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002631 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002632 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002633 }
2634 return Builder.CreatePtrToInt(V, TargetTy);
2635}
2636
2637/// \brief Emit a representation of a SourceLocation for passing to a handler
2638/// in a sanitizer runtime library. The format for this data is:
2639/// \code
2640/// struct SourceLocation {
2641/// const char *Filename;
2642/// int32_t Line, Column;
2643/// };
2644/// \endcode
2645/// For an invalid SourceLocation, the Filename pointer is null.
2646llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002647 llvm::Constant *Filename;
2648 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002649
Alexey Samsonov6c124142014-07-18 17:50:06 +00002650 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2651 if (PLoc.isValid()) {
Filipe Cabecinhasab731f72016-05-12 16:51:36 +00002652 StringRef FilenameString = PLoc.getFilename();
2653
2654 int PathComponentsToStrip =
2655 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2656 if (PathComponentsToStrip < 0) {
2657 assert(PathComponentsToStrip != INT_MIN);
2658 int PathComponentsToKeep = -PathComponentsToStrip;
2659 auto I = llvm::sys::path::rbegin(FilenameString);
2660 auto E = llvm::sys::path::rend(FilenameString);
2661 while (I != E && --PathComponentsToKeep)
2662 ++I;
2663
2664 FilenameString = FilenameString.substr(I - E);
2665 } else if (PathComponentsToStrip > 0) {
2666 auto I = llvm::sys::path::begin(FilenameString);
2667 auto E = llvm::sys::path::end(FilenameString);
2668 while (I != E && PathComponentsToStrip--)
2669 ++I;
2670
2671 if (I != E)
2672 FilenameString =
2673 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2674 else
2675 FilenameString = llvm::sys::path::filename(FilenameString);
2676 }
2677
2678 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002679 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2680 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2681 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002682 Line = PLoc.getLine();
2683 Column = PLoc.getColumn();
2684 } else {
2685 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2686 Line = Column = 0;
2687 }
2688
2689 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2690 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002691
2692 return llvm::ConstantStruct::getAnon(Data);
2693}
2694
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002695namespace {
2696/// \brief Specify under what conditions this check can be recovered
2697enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002698 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002699 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002700 /// Check supports recovering, runtime has both fatal (noreturn) and
2701 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002702 Recoverable,
2703 /// Runtime conditionally aborts, always need to support recovery.
2704 AlwaysRecoverable
2705};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002706}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002707
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002708static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2709 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002710 switch (Kind) {
2711 case SanitizerKind::Vptr:
2712 return CheckRecoverableKind::AlwaysRecoverable;
2713 case SanitizerKind::Return:
2714 case SanitizerKind::Unreachable:
2715 return CheckRecoverableKind::Unrecoverable;
2716 default:
2717 return CheckRecoverableKind::Recoverable;
2718 }
2719}
2720
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002721namespace {
2722struct SanitizerHandlerInfo {
2723 char const *const Name;
2724 unsigned Version;
2725};
Saleem Abdulrasoolca6e2b42016-12-13 03:27:35 +00002726}
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002727
2728const SanitizerHandlerInfo SanitizerHandlers[] = {
2729#define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2730 LIST_SANITIZER_CHECKS
2731#undef SANITIZER_CHECK
2732};
2733
Alexey Samsonov88459522015-01-12 22:39:12 +00002734static void emitCheckHandlerCall(CodeGenFunction &CGF,
2735 llvm::FunctionType *FnType,
2736 ArrayRef<llvm::Value *> FnArgs,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002737 SanitizerHandler CheckHandler,
Alexey Samsonov88459522015-01-12 22:39:12 +00002738 CheckRecoverableKind RecoverKind, bool IsFatal,
2739 llvm::BasicBlock *ContBB) {
2740 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2741 bool NeedsAbortSuffix =
2742 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002743 bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002744 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2745 const StringRef CheckName = CheckInfo.Name;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002746 std::string FnName = "__ubsan_handle_" + CheckName.str();
2747 if (CheckInfo.Version && !MinimalRuntime)
2748 FnName += "_v" + llvm::utostr(CheckInfo.Version);
2749 if (MinimalRuntime)
2750 FnName += "_minimal";
2751 if (NeedsAbortSuffix)
2752 FnName += "_abort";
Alexey Samsonov88459522015-01-12 22:39:12 +00002753 bool MayReturn =
2754 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2755
2756 llvm::AttrBuilder B;
2757 if (!MayReturn) {
2758 B.addAttribute(llvm::Attribute::NoReturn)
2759 .addAttribute(llvm::Attribute::NoUnwind);
2760 }
2761 B.addAttribute(llvm::Attribute::UWTable);
2762
2763 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2764 FnType, FnName,
Reid Klecknerde864822017-03-21 16:57:30 +00002765 llvm::AttributeList::get(CGF.getLLVMContext(),
2766 llvm::AttributeList::FunctionIndex, B),
Saleem Abdulrasool05b8fde2016-12-15 16:30:20 +00002767 /*Local=*/true);
Alexey Samsonov88459522015-01-12 22:39:12 +00002768 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2769 if (!MayReturn) {
2770 HandlerCall->setDoesNotReturn();
2771 CGF.Builder.CreateUnreachable();
2772 } else {
2773 CGF.Builder.CreateBr(ContBB);
2774 }
2775}
2776
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002777void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002778 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002779 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002780 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002781 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002782 assert(Checked.size() > 0);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002783 assert(CheckHandler >= 0 &&
2784 CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers));
2785 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
Alexey Samsonov88459522015-01-12 22:39:12 +00002786
2787 llvm::Value *FatalCond = nullptr;
2788 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002789 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002790 for (int i = 0, n = Checked.size(); i < n; ++i) {
2791 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002792 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002793 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002794 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2795 ? TrapCond
2796 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2797 ? RecoverableCond
2798 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002799 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2800 }
2801
Peter Collingbourne9881b782015-06-18 23:59:22 +00002802 if (TrapCond)
2803 EmitTrapCheck(TrapCond);
2804 if (!FatalCond && !RecoverableCond)
2805 return;
2806
Alexey Samsonov88459522015-01-12 22:39:12 +00002807 llvm::Value *JointCond;
2808 if (FatalCond && RecoverableCond)
2809 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2810 else
2811 JointCond = FatalCond ? FatalCond : RecoverableCond;
2812 assert(JointCond);
2813
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002814 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002815 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002816#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002817 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002818 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002819 "All recoverable kinds in a single check must be same!");
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002820 assert(SanOpts.has(Checked[i].second));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002821 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002822#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002823
Richard Smith4d1458e2012-09-08 02:08:36 +00002824 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002825 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2826 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002827 // Give hint that we very much don't expect to execute the handler
2828 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2829 llvm::MDBuilder MDHelper(getLLVMContext());
2830 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2831 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002832 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002833
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002834 // Handler functions take an i8* pointing to the (handler-specific) static
2835 // information block, followed by a sequence of intptr_t arguments
2836 // representing operand values.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002837 SmallVector<llvm::Value *, 4> Args;
2838 SmallVector<llvm::Type *, 4> ArgTypes;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002839 if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
2840 Args.reserve(DynamicArgs.size() + 1);
2841 ArgTypes.reserve(DynamicArgs.size() + 1);
Richard Smithe30752c2012-10-09 19:52:38 +00002842
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002843 // Emit handler arguments and create handler function type.
2844 if (!StaticArgs.empty()) {
2845 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2846 auto *InfoPtr =
2847 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2848 llvm::GlobalVariable::PrivateLinkage, Info);
2849 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2850 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2851 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2852 ArgTypes.push_back(Int8PtrTy);
2853 }
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002854
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002855 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2856 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2857 ArgTypes.push_back(IntPtrTy);
2858 }
Richard Smithe30752c2012-10-09 19:52:38 +00002859 }
2860
2861 llvm::FunctionType *FnType =
2862 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002863
Alexey Samsonov88459522015-01-12 22:39:12 +00002864 if (!FatalCond || !RecoverableCond) {
2865 // Simple case: we need to generate a single handler call, either
2866 // fatal, or non-fatal.
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002867 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
Alexey Samsonov88459522015-01-12 22:39:12 +00002868 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002869 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002870 // Emit two handler calls: first one for set of unrecoverable checks,
2871 // another one for recoverable.
2872 llvm::BasicBlock *NonFatalHandlerBB =
2873 createBasicBlock("non_fatal." + CheckName);
2874 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2875 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2876 EmitBlock(FatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002877 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
Alexey Samsonov88459522015-01-12 22:39:12 +00002878 NonFatalHandlerBB);
2879 EmitBlock(NonFatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002880 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
Alexey Samsonov88459522015-01-12 22:39:12 +00002881 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002882 }
Richard Smithe30752c2012-10-09 19:52:38 +00002883
Richard Smith4d1458e2012-09-08 02:08:36 +00002884 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002885}
2886
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002887void CodeGenFunction::EmitCfiSlowPathCheck(
2888 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2889 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002890 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2891
2892 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2893 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2894
2895 llvm::MDBuilder MDHelper(getLLVMContext());
2896 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2897 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2898
2899 EmitBlock(CheckBB);
2900
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002901 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2902
2903 llvm::CallInst *CheckCall;
2904 if (WithDiag) {
2905 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2906 auto *InfoPtr =
2907 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2908 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002909 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002910 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2911
2912 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2913 "__cfi_slowpath_diag",
2914 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2915 false));
2916 CheckCall = Builder.CreateCall(
2917 SlowPathDiagFn,
2918 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2919 } else {
2920 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2921 "__cfi_slowpath",
2922 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2923 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2924 }
2925
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002926 CheckCall->setDoesNotThrow();
2927
2928 EmitBlock(Cont);
2929}
2930
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +00002931// Emit a stub for __cfi_check function so that the linker knows about this
2932// symbol in LTO mode.
2933void CodeGenFunction::EmitCfiCheckStub() {
2934 llvm::Module *M = &CGM.getModule();
2935 auto &Ctx = M->getContext();
2936 llvm::Function *F = llvm::Function::Create(
2937 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
2938 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
2939 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
2940 // FIXME: consider emitting an intrinsic call like
2941 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
2942 // which can be lowered in CrossDSOCFI pass to the actual contents of
2943 // __cfi_check. This would allow inlining of __cfi_check calls.
2944 llvm::CallInst::Create(
2945 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
2946 llvm::ReturnInst::Create(Ctx, nullptr, BB);
2947}
2948
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002949// This function is basically a switch over the CFI failure kind, which is
2950// extracted from CFICheckFailData (1st function argument). Each case is either
2951// llvm.trap or a call to one of the two runtime handlers, based on
2952// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2953// failure kind) traps, but this should really never happen. CFICheckFailData
2954// can be nullptr if the calling module has -fsanitize-trap behavior for this
2955// check kind; in this case __cfi_check_fail traps as well.
2956void CodeGenFunction::EmitCfiCheckFail() {
2957 SanitizerScope SanScope(this);
2958 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002959 ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
2960 ImplicitParamDecl::Other);
2961 ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
2962 ImplicitParamDecl::Other);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002963 Args.push_back(&ArgData);
2964 Args.push_back(&ArgAddr);
2965
John McCallc56a8b32016-03-11 04:30:31 +00002966 const CGFunctionInfo &FI =
2967 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002968
2969 llvm::Function *F = llvm::Function::Create(
2970 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2971 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2972 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2973
2974 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2975 SourceLocation());
2976
2977 llvm::Value *Data =
2978 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2979 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2980 llvm::Value *Addr =
2981 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2982 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2983
2984 // Data == nullptr means the calling module has trap behaviour for this check.
2985 llvm::Value *DataIsNotNullPtr =
2986 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2987 EmitTrapCheck(DataIsNotNullPtr);
2988
2989 llvm::StructType *SourceLocationTy =
Serge Guelton1d993272017-05-09 19:31:30 +00002990 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002991 llvm::StructType *CfiCheckFailDataTy =
Serge Guelton1d993272017-05-09 19:31:30 +00002992 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002993
2994 llvm::Value *V = Builder.CreateConstGEP2_32(
2995 CfiCheckFailDataTy,
2996 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2997 0);
2998 Address CheckKindAddr(V, getIntAlign());
2999 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
3000
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00003001 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
3002 CGM.getLLVMContext(),
3003 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
3004 llvm::Value *ValidVtable = Builder.CreateZExt(
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00003005 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00003006 {Addr, AllVtables}),
3007 IntPtrTy);
3008
Evgeniy Stepanov4d3b0872016-01-25 23:45:37 +00003009 const std::pair<int, SanitizerMask> CheckKinds[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003010 {CFITCK_VCall, SanitizerKind::CFIVCall},
3011 {CFITCK_NVCall, SanitizerKind::CFINVCall},
3012 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
3013 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
3014 {CFITCK_ICall, SanitizerKind::CFIICall}};
3015
3016 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
3017 for (auto CheckKindMaskPair : CheckKinds) {
3018 int Kind = CheckKindMaskPair.first;
3019 SanitizerMask Mask = CheckKindMaskPair.second;
3020 llvm::Value *Cond =
3021 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00003022 if (CGM.getLangOpts().Sanitize.has(Mask))
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00003023 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00003024 {Data, Addr, ValidVtable});
3025 else
3026 EmitTrapCheck(Cond);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003027 }
3028
3029 FinishFunction();
3030 // The only reference to this function will be created during LTO link.
3031 // Make sure it survives until then.
3032 CGM.addUsedGlobal(F);
3033}
3034
Chad Rosierae229d52013-01-29 23:31:22 +00003035void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00003036 llvm::BasicBlock *Cont = createBasicBlock("cont");
3037
3038 // If we're optimizing, collapse all calls to trap down to just one per
3039 // function to save on code size.
3040 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
3041 TrapBB = createBasicBlock("trap");
3042 Builder.CreateCondBr(Checked, Cont, TrapBB);
3043 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003044 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00003045 TrapCall->setDoesNotReturn();
3046 TrapCall->setDoesNotThrow();
3047 Builder.CreateUnreachable();
3048 } else {
3049 Builder.CreateCondBr(Checked, Cont, TrapBB);
3050 }
3051
3052 EmitBlock(Cont);
3053}
3054
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003055llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00003056 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003057
Amaury Sechet21f51b32016-09-09 04:42:49 +00003058 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3059 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3060 CGM.getCodeGenOpts().TrapFuncName);
Reid Klecknerde864822017-03-21 16:57:30 +00003061 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
Amaury Sechet21f51b32016-09-09 04:42:49 +00003062 }
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003063
3064 return TrapCall;
3065}
3066
John McCall7f416cc2015-09-08 08:05:57 +00003067Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003068 LValueBaseInfo *BaseInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00003069 assert(E->getType()->isArrayType() &&
3070 "Array to pointer decay must have array source type!");
3071
3072 // Expressions of array type can't be bitfields or vector elements.
3073 LValue LV = EmitLValue(E);
3074 Address Addr = LV.getAddress();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003075 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
John McCall7f416cc2015-09-08 08:05:57 +00003076
3077 // If the array type was an incomplete type, we need to make sure
3078 // the decay ends up being the right type.
3079 llvm::Type *NewTy = ConvertType(E->getType());
3080 Addr = Builder.CreateElementBitCast(Addr, NewTy);
3081
3082 // Note that VLA pointers are always decayed, so we don't need to do
3083 // anything here.
3084 if (!E->getType()->isVariableArrayType()) {
3085 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3086 "Expected pointer to array");
3087 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
3088 }
3089
3090 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
3091 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
3092}
3093
Chris Lattner6c5abe82010-06-26 23:03:20 +00003094/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
3095/// array to pointer, return the array subexpression.
3096static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
3097 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003098 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00003099 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00003100 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00003101
Chris Lattner6c5abe82010-06-26 23:03:20 +00003102 // If this is a decay from variable width array, bail out.
3103 const Expr *SubExpr = CE->getSubExpr();
3104 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00003105 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00003106
Chris Lattner6c5abe82010-06-26 23:03:20 +00003107 return SubExpr;
3108}
3109
John McCall7f416cc2015-09-08 08:05:57 +00003110static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3111 llvm::Value *ptr,
3112 ArrayRef<llvm::Value*> indices,
3113 bool inbounds,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003114 bool signedIndices,
Vedant Kumara125eb52017-06-01 19:22:18 +00003115 SourceLocation loc,
John McCall7f416cc2015-09-08 08:05:57 +00003116 const llvm::Twine &name = "arrayidx") {
3117 if (inbounds) {
Vedant Kumar175b6d12017-07-13 20:55:26 +00003118 return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices,
3119 CodeGenFunction::NotSubtraction, loc,
3120 name);
John McCall7f416cc2015-09-08 08:05:57 +00003121 } else {
3122 return CGF.Builder.CreateGEP(ptr, indices, name);
3123 }
3124}
3125
3126static CharUnits getArrayElementAlign(CharUnits arrayAlign,
3127 llvm::Value *idx,
3128 CharUnits eltSize) {
3129 // If we have a constant index, we can use the exact offset of the
3130 // element we're accessing.
3131 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3132 CharUnits offset = constantIdx->getZExtValue() * eltSize;
3133 return arrayAlign.alignmentAtOffset(offset);
3134
3135 // Otherwise, use the worst-case alignment for any element.
3136 } else {
3137 return arrayAlign.alignmentOfArrayElement(eltSize);
3138 }
3139}
3140
3141static QualType getFixedSizeElementType(const ASTContext &ctx,
3142 const VariableArrayType *vla) {
3143 QualType eltType;
3144 do {
3145 eltType = vla->getElementType();
3146 } while ((vla = ctx.getAsVariableArrayType(eltType)));
3147 return eltType;
3148}
3149
3150static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
Vedant Kumara125eb52017-06-01 19:22:18 +00003151 ArrayRef<llvm::Value *> indices,
John McCall7f416cc2015-09-08 08:05:57 +00003152 QualType eltType, bool inbounds,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003153 bool signedIndices, SourceLocation loc,
John McCall7f416cc2015-09-08 08:05:57 +00003154 const llvm::Twine &name = "arrayidx") {
3155 // All the indices except that last must be zero.
3156#ifndef NDEBUG
3157 for (auto idx : indices.drop_back())
3158 assert(isa<llvm::ConstantInt>(idx) &&
3159 cast<llvm::ConstantInt>(idx)->isZero());
3160#endif
3161
3162 // Determine the element size of the statically-sized base. This is
3163 // the thing that the indices are expressed in terms of.
3164 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3165 eltType = getFixedSizeElementType(CGF.getContext(), vla);
3166 }
3167
3168 // We can use that to compute the best alignment of the element.
3169 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3170 CharUnits eltAlign =
3171 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3172
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003173 llvm::Value *eltPtr = emitArraySubscriptGEP(
3174 CGF, addr.getPointer(), indices, inbounds, signedIndices, loc, name);
John McCall7f416cc2015-09-08 08:05:57 +00003175 return Address(eltPtr, eltAlign);
3176}
3177
Richard Smith539e4a72013-02-23 02:53:19 +00003178LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3179 bool Accessed) {
Richard Smith9e67b992016-09-26 23:49:47 +00003180 // The index must always be an integer, which is not an aggregate. Emit it
3181 // in lexical order (this complexity is, sadly, required by C++17).
3182 llvm::Value *IdxPre =
3183 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003184 bool SignedIndices = false;
Richard Smith40885712016-09-27 00:53:24 +00003185 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
Richard Smith9e67b992016-09-26 23:49:47 +00003186 auto *Idx = IdxPre;
3187 if (E->getLHS() != E->getIdx()) {
3188 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3189 Idx = EmitScalarExpr(E->getIdx());
3190 }
Eli Friedman07bbeca2009-06-06 19:09:26 +00003191
Richard Smith9e67b992016-09-26 23:49:47 +00003192 QualType IdxTy = E->getIdx()->getType();
3193 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003194 SignedIndices |= IdxSigned;
Richard Smith9e67b992016-09-26 23:49:47 +00003195
3196 if (SanOpts.has(SanitizerKind::ArrayBounds))
3197 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3198
3199 // Extend or truncate the index type to 32 or 64-bits.
3200 if (Promote && Idx->getType() != IntPtrTy)
3201 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3202
3203 return Idx;
3204 };
3205 IdxPre = nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +00003206
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003207 // If the base is a vector type, then we are forming a vector element lvalue
3208 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003209 if (E->getBase()->getType()->isVectorType() &&
3210 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003211 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00003212 LValue LHS = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003213 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
Ted Kremenekc81614d2007-08-20 16:18:38 +00003214 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Eli Friedman327944b2008-06-13 23:01:12 +00003215 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
John McCall7f416cc2015-09-08 08:05:57 +00003216 E->getBase()->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003217 LHS.getBaseInfo());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003218 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003219
John McCall7f416cc2015-09-08 08:05:57 +00003220 // All the other cases basically behave like simple offsetting.
3221
John McCall7f416cc2015-09-08 08:05:57 +00003222 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003223 if (isa<ExtVectorElementExpr>(E->getBase())) {
3224 LValue LV = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003225 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003226 Address Addr = EmitExtVectorElementLValue(LV);
3227
3228 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
Vedant Kumara125eb52017-06-01 19:22:18 +00003229 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003230 SignedIndices, E->getExprLoc());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003231 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo());
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003232 }
John McCall7f416cc2015-09-08 08:05:57 +00003233
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003234 LValueBaseInfo BaseInfo;
John McCall7f416cc2015-09-08 08:05:57 +00003235 Address Addr = Address::invalid();
3236 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003237 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00003238 // The base must be a pointer, which is not an aggregate. Emit
3239 // it. It needs to be emitted first in case it's what captures
3240 // the VLA bounds.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003241 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003242 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Mike Stump4a3999f2009-09-09 13:00:44 +00003243
John McCall23c29fe2011-06-24 21:55:10 +00003244 // The element count here is the total number of non-VLA elements.
3245 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00003246
John McCall77527a82011-06-25 01:32:37 +00003247 // Effectively, the multiply by the VLA size is part of the GEP.
3248 // GEP indexes are signed, and scaling an index isn't permitted to
3249 // signed-overflow, so we use the same semantics for our explicit
3250 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003251 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00003252 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003253 } else {
3254 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003255 }
John McCall7f416cc2015-09-08 08:05:57 +00003256
3257 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003258 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003259 SignedIndices, E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00003260
Chris Lattner6c5abe82010-06-26 23:03:20 +00003261 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3262 // Indexing over an interface, as in "NSString *P; P[4];"
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003263
John McCall7f416cc2015-09-08 08:05:57 +00003264 // Emit the base pointer.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003265 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003266 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3267
3268 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3269 llvm::Value *InterfaceSizeVal =
3270 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3271
3272 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
John McCall7f416cc2015-09-08 08:05:57 +00003273
3274 // We don't necessarily build correct LLVM struct types for ObjC
3275 // interfaces, so we can't rely on GEP to do this scaling
3276 // correctly, so we need to cast to i8*. FIXME: is this actually
3277 // true? A lot of other things in the fragile ABI would break...
3278 llvm::Type *OrigBaseTy = Addr.getType();
3279 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3280
3281 // Do the GEP.
3282 CharUnits EltAlign =
3283 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003284 llvm::Value *EltPtr =
3285 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false,
3286 SignedIndices, E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00003287 Addr = Address(EltPtr, EltAlign);
3288
3289 // Cast back.
3290 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00003291 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3292 // If this is A[i] where A is an array, the frontend will have decayed the
3293 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3294 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3295 // "gep x, i" here. Emit one "gep A, 0, i".
3296 assert(Array->getType()->isArrayType() &&
3297 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00003298 LValue ArrayLV;
3299 // For simple multidimensional array indexing, set the 'accessed' flag for
3300 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003301 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00003302 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3303 else
3304 ArrayLV = EmitLValue(Array);
Richard Smith9e67b992016-09-26 23:49:47 +00003305 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Craig Topper99e79272013-07-26 05:59:26 +00003306
Daniel Dunbar82634272011-04-01 00:49:43 +00003307 // Propagate the alignment from the array itself to the result.
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003308 Addr = emitArraySubscriptGEP(
3309 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3310 E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3311 E->getExprLoc());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003312 BaseInfo = ArrayLV.getBaseInfo();
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003313 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003314 // The base must be a pointer; emit it with an estimate of its alignment.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003315 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003316 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003317 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003318 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003319 SignedIndices, E->getExprLoc());
Anders Carlsson3d312f82008-12-21 00:11:23 +00003320 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003321
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003322 LValue LV = MakeAddrLValue(Addr, E->getType(), BaseInfo);
Mike Stump4a3999f2009-09-09 13:00:44 +00003323
John McCall7f416cc2015-09-08 08:05:57 +00003324 // TODO: Preserve/extend path TBAA metadata?
John McCall8ccfcb52009-09-24 19:53:00 +00003325
Richard Smith9c6890a2012-11-01 22:30:59 +00003326 if (getLangOpts().ObjC1 &&
3327 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00003328 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00003329 setObjCGCLValueClass(getContext(), E, LV);
3330 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00003331 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00003332}
3333
Alexey Bataev31300ed2016-02-04 11:27:03 +00003334static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003335 LValueBaseInfo &BaseInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003336 QualType BaseTy, QualType ElTy,
3337 bool IsLowerBound) {
3338 LValue BaseLVal;
3339 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3340 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3341 if (BaseTy->isArrayType()) {
3342 Address Addr = BaseLVal.getAddress();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003343 BaseInfo = BaseLVal.getBaseInfo();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003344
3345 // If the array type was an incomplete type, we need to make sure
3346 // the decay ends up being the right type.
3347 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3348 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3349
3350 // Note that VLA pointers are always decayed, so we don't need to do
3351 // anything here.
3352 if (!BaseTy->isVariableArrayType()) {
3353 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3354 "Expected pointer to array");
3355 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3356 "arraydecay");
3357 }
3358
3359 return CGF.Builder.CreateElementBitCast(Addr,
3360 CGF.ConvertTypeForMem(ElTy));
3361 }
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003362 LValueBaseInfo TypeInfo;
3363 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &TypeInfo);
3364 BaseInfo.mergeForCast(TypeInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003365 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3366 }
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003367 return CGF.EmitPointerWithAlignment(Base, &BaseInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003368}
3369
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003370LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3371 bool IsLowerBound) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003372 QualType BaseTy;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003373 if (auto *ASE =
3374 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
Alexey Bataev31300ed2016-02-04 11:27:03 +00003375 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003376 else
Alexey Bataev31300ed2016-02-04 11:27:03 +00003377 BaseTy = E->getBase()->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003378 QualType ResultExprTy;
3379 if (auto *AT = getContext().getAsArrayType(BaseTy))
3380 ResultExprTy = AT->getElementType();
3381 else
3382 ResultExprTy = BaseTy->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003383 llvm::Value *Idx = nullptr;
Benjamin Kramer5ff67472016-04-11 08:26:13 +00003384 if (IsLowerBound || E->getColonLoc().isInvalid()) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003385 // Requesting lower bound or upper bound, but without provided length and
3386 // without ':' symbol for the default length -> length = 1.
3387 // Idx = LowerBound ?: 0;
3388 if (auto *LowerBound = E->getLowerBound()) {
3389 Idx = Builder.CreateIntCast(
3390 EmitScalarExpr(LowerBound), IntPtrTy,
3391 LowerBound->getType()->hasSignedIntegerRepresentation());
3392 } else
3393 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3394 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003395 // Try to emit length or lower bound as constant. If this is possible, 1
3396 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3397 // IR (LB + Len) - 1.
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003398 auto &C = CGM.getContext();
3399 auto *Length = E->getLength();
3400 llvm::APSInt ConstLength;
3401 if (Length) {
3402 // Idx = LowerBound + Length - 1;
3403 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3404 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3405 Length = nullptr;
3406 }
3407 auto *LowerBound = E->getLowerBound();
3408 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3409 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3410 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3411 LowerBound = nullptr;
3412 }
3413 if (!Length)
3414 --ConstLength;
3415 else if (!LowerBound)
3416 --ConstLowerBound;
3417
3418 if (Length || LowerBound) {
3419 auto *LowerBoundVal =
3420 LowerBound
3421 ? Builder.CreateIntCast(
3422 EmitScalarExpr(LowerBound), IntPtrTy,
3423 LowerBound->getType()->hasSignedIntegerRepresentation())
3424 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3425 auto *LengthVal =
3426 Length
3427 ? Builder.CreateIntCast(
3428 EmitScalarExpr(Length), IntPtrTy,
3429 Length->getType()->hasSignedIntegerRepresentation())
3430 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3431 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3432 /*HasNUW=*/false,
3433 !getLangOpts().isSignedOverflowDefined());
3434 if (Length && LowerBound) {
3435 Idx = Builder.CreateSub(
3436 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3437 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3438 }
3439 } else
3440 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3441 } else {
3442 // Idx = ArraySize - 1;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003443 QualType ArrayTy = BaseTy->isPointerType()
3444 ? E->getBase()->IgnoreParenImpCasts()->getType()
3445 : BaseTy;
3446 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003447 Length = VAT->getSizeExpr();
3448 if (Length->isIntegerConstantExpr(ConstLength, C))
3449 Length = nullptr;
3450 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003451 auto *CAT = C.getAsConstantArrayType(ArrayTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003452 ConstLength = CAT->getSize();
3453 }
3454 if (Length) {
3455 auto *LengthVal = Builder.CreateIntCast(
3456 EmitScalarExpr(Length), IntPtrTy,
3457 Length->getType()->hasSignedIntegerRepresentation());
3458 Idx = Builder.CreateSub(
3459 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3460 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3461 } else {
3462 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3463 --ConstLength;
3464 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3465 }
3466 }
3467 }
3468 assert(Idx);
3469
Alexey Bataev31300ed2016-02-04 11:27:03 +00003470 Address EltPtr = Address::invalid();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003471 LValueBaseInfo BaseInfo;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003472 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003473 // The base must be a pointer, which is not an aggregate. Emit
3474 // it. It needs to be emitted first in case it's what captures
3475 // the VLA bounds.
3476 Address Base =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003477 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, BaseTy,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003478 VLA->getElementType(), IsLowerBound);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003479 // The element count here is the total number of non-VLA elements.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003480 llvm::Value *NumElements = getVLASize(VLA).first;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003481
3482 // Effectively, the multiply by the VLA size is part of the GEP.
3483 // GEP indexes are signed, and scaling an index isn't permitted to
3484 // signed-overflow, so we use the same semantics for our explicit
3485 // multiply. We suppress this if overflow is not undefined behavior.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003486 if (getLangOpts().isSignedOverflowDefined())
3487 Idx = Builder.CreateMul(Idx, NumElements);
3488 else
3489 Idx = Builder.CreateNSWMul(Idx, NumElements);
3490 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003491 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003492 /*SignedIndices=*/false, E->getExprLoc());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003493 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3494 // If this is A[i] where A is an array, the frontend will have decayed the
3495 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3496 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3497 // "gep x, i" here. Emit one "gep A, 0, i".
3498 assert(Array->getType()->isArrayType() &&
3499 "Array to pointer decay must have array source type!");
3500 LValue ArrayLV;
3501 // For simple multidimensional array indexing, set the 'accessed' flag for
3502 // better bounds-checking of the base expression.
3503 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3504 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3505 else
3506 ArrayLV = EmitLValue(Array);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003507
Alexey Bataev31300ed2016-02-04 11:27:03 +00003508 // Propagate the alignment from the array itself to the result.
3509 EltPtr = emitArraySubscriptGEP(
3510 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
Vedant Kumara125eb52017-06-01 19:22:18 +00003511 ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003512 /*SignedIndices=*/false, E->getExprLoc());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003513 BaseInfo = ArrayLV.getBaseInfo();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003514 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003515 Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003516 BaseTy, ResultExprTy, IsLowerBound);
3517 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
Vedant Kumara125eb52017-06-01 19:22:18 +00003518 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003519 /*SignedIndices=*/false, E->getExprLoc());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003520 }
3521
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003522 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003523}
3524
Chris Lattner9e751ca2007-08-02 23:37:31 +00003525LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00003526EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00003527 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003528 LValue Base;
3529
3530 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00003531 if (E->isArrow()) {
3532 // If it is a pointer to a vector, emit the address and form an lvalue with
3533 // it.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003534 LValueBaseInfo BaseInfo;
3535 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003536 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003537 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo);
Daniel Dunbarf166a522010-08-21 03:44:13 +00003538 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00003539 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00003540 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3541 // emit the base as an lvalue.
3542 assert(E->getBase()->getType()->isVectorType());
3543 Base = EmitLValue(E->getBase());
3544 } else {
3545 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00003546 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00003547 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00003548 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00003549
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00003550 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00003551 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00003552 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00003553 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003554 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattner4e1a3232009-12-23 21:31:11 +00003555 }
John McCall1553b192011-06-16 04:16:24 +00003556
3557 QualType type =
3558 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00003559
Nate Begemand3862152008-05-13 21:03:02 +00003560 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00003561 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00003562 E->getEncodedElementAccess(Indices);
3563
3564 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00003565 llvm::Constant *CV =
3566 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00003567 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003568 Base.getBaseInfo());
Nate Begemand3862152008-05-13 21:03:02 +00003569 }
3570 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3571
3572 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003573 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00003574
Chris Lattner595ba3a2012-01-30 06:20:36 +00003575 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3576 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00003577 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00003578 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003579 Base.getBaseInfo());
Chris Lattner9e751ca2007-08-02 23:37:31 +00003580}
3581
Devang Patel30efa2e2007-10-23 20:28:39 +00003582LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Alex Lorenz6cc83172017-08-25 10:07:00 +00003583 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
3584 EmitIgnoredExpr(E->getBase());
3585 return EmitDeclRefLValue(DRE);
3586 }
3587
Devang Pateld68df202007-10-24 22:26:28 +00003588 Expr *BaseExpr = E->getBase();
Chris Lattner4e4186b2007-12-02 18:52:07 +00003589 // 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 +00003590 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00003591 if (E->isArrow()) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003592 LValueBaseInfo BaseInfo;
3593 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo);
Richard Smith69d0d262012-08-24 00:54:33 +00003594 QualType PtrTy = BaseExpr->getType()->getPointeeType();
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003595 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00003596 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
3597 if (IsBaseCXXThis)
3598 SkippedChecks.set(SanitizerKind::Alignment, true);
3599 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003600 SkippedChecks.set(SanitizerKind::Null, true);
3601 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
3602 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003603 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo);
Richard Smith69d0d262012-08-24 00:54:33 +00003604 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003605 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003606
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003607 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003608 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003609 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003610 setObjCGCLValueClass(getContext(), E, LV);
3611 return LV;
3612 }
Craig Topper99e79272013-07-26 05:59:26 +00003613
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003614 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003615 return EmitFunctionDeclLValue(*this, E, FD);
3616
David Blaikie83d382b2011-09-23 05:06:16 +00003617 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003618}
Devang Patel30efa2e2007-10-23 20:28:39 +00003619
John McCalldec348f72013-05-03 07:33:41 +00003620/// Given that we are currently emitting a lambda, emit an l-value for
3621/// one of its members.
3622LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3623 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3624 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3625 QualType LambdaTagType =
3626 getContext().getTagDeclType(Field->getParent());
3627 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3628 return EmitLValueForField(LambdaLV, Field);
3629}
3630
John McCall7f416cc2015-09-08 08:05:57 +00003631/// Drill down to the storage of a field without walking into
3632/// reference types.
3633///
3634/// The resulting address doesn't necessarily have the right type.
3635static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3636 const FieldDecl *field) {
3637 const RecordDecl *rec = field->getParent();
3638
3639 unsigned idx =
3640 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3641
3642 CharUnits offset;
3643 // Adjust the alignment down to the given offset.
3644 // As a special case, if the LLVM field index is 0, we know that this
3645 // is zero.
3646 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3647 .getFieldOffset(field->getFieldIndex()) == 0) &&
3648 "LLVM field at index zero had non-zero offset?");
3649 if (idx != 0) {
3650 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3651 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3652 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3653 }
3654
3655 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3656}
3657
Piotr Padlewskic1d26062017-06-01 18:39:34 +00003658static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
3659 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
3660 if (!RD)
3661 return false;
3662
3663 if (RD->isDynamicClass())
3664 return true;
3665
3666 for (const auto &Base : RD->bases())
3667 if (hasAnyVptr(Base.getType(), Context))
3668 return true;
3669
3670 for (const FieldDecl *Field : RD->fields())
3671 if (hasAnyVptr(Field->getType(), Context))
3672 return true;
3673
3674 return false;
3675}
3676
Eli Friedman7f1ff602012-04-16 03:54:45 +00003677LValue CodeGenFunction::EmitLValueForField(LValue base,
3678 const FieldDecl *field) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003679 LValueBaseInfo BaseInfo = base.getBaseInfo();
John McCall7f416cc2015-09-08 08:05:57 +00003680 AlignmentSource fieldAlignSource =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003681 getFieldAlignmentSource(BaseInfo.getAlignmentSource());
3682 LValueBaseInfo FieldBaseInfo(fieldAlignSource, BaseInfo.getMayAlias());
John McCall7f416cc2015-09-08 08:05:57 +00003683
Hal Finkelc9fac9e2017-09-03 17:18:25 +00003684 QualType type = field->getType();
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00003685 const RecordDecl *rec = field->getParent();
Hal Finkelc9fac9e2017-09-03 17:18:25 +00003686 if (rec->isUnion() || rec->hasAttr<MayAliasAttr>() || type->isVectorType())
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00003687 FieldBaseInfo.setMayAlias(true);
3688 bool mayAlias = FieldBaseInfo.getMayAlias();
3689
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003690 if (field->isBitField()) {
3691 const CGRecordLayout &RL =
3692 CGM.getTypes().getCGRecordLayout(field->getParent());
3693 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003694 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003695 unsigned Idx = RL.getLLVMFieldNo(field);
3696 if (Idx != 0)
3697 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003698 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3699 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003700 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003701 llvm::Type *FieldIntTy =
3702 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3703 if (Addr.getElementType() != FieldIntTy)
3704 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003705
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003706 QualType fieldType =
3707 field->getType().withCVRQualifiers(base.getVRQualifiers());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003708 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo);
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003709 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003710
John McCall7f416cc2015-09-08 08:05:57 +00003711 Address addr = base.getAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003712 unsigned cvr = base.getVRQualifiers();
Manman Renc451e572013-04-04 21:53:22 +00003713 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
John McCall53fcbd22011-02-26 08:07:02 +00003714 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003715 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00003716 assert(!type->isReferenceType() && "union has reference member");
Manman Renc451e572013-04-04 21:53:22 +00003717 // TODO: handle path-aware TBAA for union.
3718 TBAAPath = false;
Piotr Padlewskic1d26062017-06-01 18:39:34 +00003719
3720 const auto FieldType = field->getType();
3721 if (CGM.getCodeGenOpts().StrictVTablePointers &&
3722 hasAnyVptr(FieldType, getContext()))
3723 // Because unions can easily skip invariant.barriers, we need to add
3724 // a barrier every time CXXRecord field with vptr is referenced.
3725 addr = Address(Builder.CreateInvariantGroupBarrier(addr.getPointer()),
3726 addr.getAlignment());
John McCall53fcbd22011-02-26 08:07:02 +00003727 } else {
3728 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003729 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003730
3731 // If this is a reference field, load the reference right now.
3732 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3733 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3734 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3735
Manman Renc451e572013-04-04 21:53:22 +00003736 // Loading the reference will disable path-aware TBAA.
3737 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003738 if (CGM.shouldUseTBAA()) {
Ivan A. Kosarev5c8e7592017-10-02 11:10:04 +00003739 llvm::MDNode *tbaa = mayAlias ? CGM.getTBAAMayAliasTypeInfo() :
3740 CGM.getTBAATypeInfo(type);
Manman Ren4f755de2013-10-08 00:08:49 +00003741 if (tbaa)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00003742 CGM.DecorateInstructionWithTBAA(load, tbaa);
John McCall53fcbd22011-02-26 08:07:02 +00003743 }
3744
John McCall53fcbd22011-02-26 08:07:02 +00003745 mayAlias = false;
3746 type = refType->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003747
3748 CharUnits alignment =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003749 getNaturalTypeAlignment(type, &FieldBaseInfo, /*pointee*/ true);
3750 FieldBaseInfo.setMayAlias(false);
John McCall7f416cc2015-09-08 08:05:57 +00003751 addr = Address(load, alignment);
3752
3753 // Qualifiers on the struct don't apply to the referencee, and
3754 // we'll pick up CVR from the actual type later, so reset these
3755 // additional qualifiers now.
3756 cvr = 0;
John McCall53fcbd22011-02-26 08:07:02 +00003757 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003758 }
Craig Topper99e79272013-07-26 05:59:26 +00003759
Chris Lattner13ee4f42011-07-10 05:34:54 +00003760 // Make sure that the address is pointing to the right type. This is critical
3761 // for both unions and structs. A union needs a bitcast, a struct element
3762 // will need a bitcast if the LLVM type laid out doesn't match the desired
3763 // type.
John McCall7f416cc2015-09-08 08:05:57 +00003764 addr = Builder.CreateElementBitCast(addr,
3765 CGM.getTypes().ConvertTypeForMem(type),
3766 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003767
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003768 if (field->hasAttr<AnnotateAttr>())
3769 addr = EmitFieldAnnotations(field, addr);
3770
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003771 LValue LV = MakeAddrLValue(addr, type, FieldBaseInfo);
John McCall53fcbd22011-02-26 08:07:02 +00003772 LV.getQuals().addCVRQualifiers(cvr);
Manman Renc451e572013-04-04 21:53:22 +00003773 if (TBAAPath) {
3774 const ASTRecordLayout &Layout =
3775 getContext().getASTRecordLayout(field->getParent());
3776 // Set the base type to be the base type of the base LValue and
3777 // update offset to be relative to the base type.
Manman Ren0e521662013-04-27 00:39:37 +00003778 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3779 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
Manman Renc451e572013-04-04 21:53:22 +00003780 Layout.getFieldOffset(field->getFieldIndex()) /
3781 getContext().getCharWidth());
3782 }
Daniel Dunbarf166a522010-08-21 03:44:13 +00003783
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003784 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003785 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3786 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003787
3788 // Fields of may_alias structs act like 'char' for TBAA purposes.
3789 // FIXME: this should get propagated down through anonymous structs
3790 // and unions.
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00003791 if (mayAlias && LV.getTBAAAccessType())
Ivan A. Kosarev5c8e7592017-10-02 11:10:04 +00003792 LV.setTBAAAccessType(CGM.getTBAAMayAliasTypeInfo());
John McCall53fcbd22011-02-26 08:07:02 +00003793
Daniel Dunbarf166a522010-08-21 03:44:13 +00003794 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003795}
3796
Craig Topper99e79272013-07-26 05:59:26 +00003797LValue
3798CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003799 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003800 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003801
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003802 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003803 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003804
John McCall7f416cc2015-09-08 08:05:57 +00003805 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003806
John McCall7f416cc2015-09-08 08:05:57 +00003807 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003808 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003809 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003810
John McCall7f416cc2015-09-08 08:05:57 +00003811 // TODO: access-path TBAA?
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003812 LValueBaseInfo BaseInfo = Base.getBaseInfo();
3813 LValueBaseInfo FieldBaseInfo(
3814 getFieldAlignmentSource(BaseInfo.getAlignmentSource()),
3815 BaseInfo.getMayAlias());
3816 return MakeAddrLValue(V, FieldType, FieldBaseInfo);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003817}
3818
Chris Lattnerf53c0962010-09-06 00:11:41 +00003819LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003820 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
Richard Smith2d988f02011-11-22 22:48:32 +00003821 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003822 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003823 return MakeAddrLValue(GlobalPtr, E->getType(), BaseInfo);
Richard Smith2d988f02011-11-22 22:48:32 +00003824 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003825 if (E->getType()->isVariablyModifiedType())
3826 // make sure to emit the VLA size.
3827 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003828
John McCall7f416cc2015-09-08 08:05:57 +00003829 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003830 const Expr *InitExpr = E->getInitializer();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003831 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), BaseInfo);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003832
Chad Rosier615ed1a2012-03-29 17:37:10 +00003833 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3834 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003835
3836 return Result;
3837}
3838
Richard Smithbb653bd2012-05-14 21:57:21 +00003839LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3840 if (!E->isGLValue())
3841 // Initializing an aggregate temporary in C++11: T{...}.
3842 return EmitAggExprToLValue(E);
3843
3844 // An lvalue initializer list must be initializing a reference.
Richard Smith122f88d2016-12-06 23:52:28 +00003845 assert(E->isTransparent() && "non-transparent glvalue init list");
Richard Smithbb653bd2012-05-14 21:57:21 +00003846 return EmitLValue(E->getInit(0));
3847}
3848
Richard Smithf3076ff2014-06-20 18:43:47 +00003849/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3850/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3851/// LValue is returned and the current block has been terminated.
3852static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3853 const Expr *Operand) {
3854 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3855 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3856 return None;
3857 }
3858
3859 return CGF.EmitLValue(Operand);
3860}
3861
John McCallc07a0c72011-02-17 10:25:35 +00003862LValue CodeGenFunction::
3863EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3864 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003865 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003866 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003867 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003868 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003869 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003870
Eli Friedman59954892012-01-25 05:04:17 +00003871 OpaqueValueMapping binding(*this, expr);
3872
John McCallc07a0c72011-02-17 10:25:35 +00003873 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003874 bool CondExprBool;
3875 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003876 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003877 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003878
Justin Bogneref512b92014-01-06 22:27:43 +00003879 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003880 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003881 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003882 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003883 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003884 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003885 }
3886
John McCallc07a0c72011-02-17 10:25:35 +00003887 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3888 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3889 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003890
3891 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003892 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003893
John McCall0a6bf2e2011-01-26 19:21:13 +00003894 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003895 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003896 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003897 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003898 Optional<LValue> lhs =
3899 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003900 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003901
Richard Smithf3076ff2014-06-20 18:43:47 +00003902 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003903 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003904
John McCallc07a0c72011-02-17 10:25:35 +00003905 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003906 if (lhs)
3907 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003908
John McCall0a6bf2e2011-01-26 19:21:13 +00003909 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003910 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003911 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003912 Optional<LValue> rhs =
3913 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003914 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003915 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003916 return EmitUnsupportedLValue(expr, "conditional operator");
3917 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003918
John McCallc07a0c72011-02-17 10:25:35 +00003919 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003920
Richard Smithf3076ff2014-06-20 18:43:47 +00003921 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003922 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003923 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003924 phi->addIncoming(lhs->getPointer(), lhsBlock);
3925 phi->addIncoming(rhs->getPointer(), rhsBlock);
3926 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3927 AlignmentSource alignSource =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003928 std::max(lhs->getBaseInfo().getAlignmentSource(),
3929 rhs->getBaseInfo().getAlignmentSource());
3930 bool MayAlias = lhs->getBaseInfo().getMayAlias() ||
3931 rhs->getBaseInfo().getMayAlias();
3932 return MakeAddrLValue(result, expr->getType(),
3933 LValueBaseInfo(alignSource, MayAlias));
Richard Smithf3076ff2014-06-20 18:43:47 +00003934 } else {
3935 assert((lhs || rhs) &&
3936 "both operands of glvalue conditional are throw-expressions?");
3937 return lhs ? *lhs : *rhs;
3938 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003939}
3940
Richard Smithbb653bd2012-05-14 21:57:21 +00003941/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3942/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003943/// otherwise if a cast is needed by the code generator in an lvalue context,
3944/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003945/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003946/// are permitted with aggregate result, including noop aggregate casts, and
3947/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003948LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003949 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003950 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003951 case CK_BitCast:
3952 case CK_ArrayToPointerDecay:
3953 case CK_FunctionToPointerDecay:
3954 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003955 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003956 case CK_IntegralToPointer:
3957 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003958 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003959 case CK_VectorSplat:
3960 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00003961 case CK_BooleanToSignedIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003962 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003963 case CK_IntegralToFloating:
3964 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003965 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003966 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003967 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003968 case CK_FloatingComplexToReal:
3969 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003970 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003971 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003972 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003973 case CK_IntegralComplexToReal:
3974 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003975 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003976 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003977 case CK_DerivedToBaseMemberPointer:
3978 case CK_BaseToDerivedMemberPointer:
3979 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003980 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003981 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003982 case CK_ARCProduceObject:
3983 case CK_ARCConsumeObject:
3984 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003985 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003986 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003987 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003988 case CK_IntToOCLSampler:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003989 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3990
3991 case CK_Dependent:
3992 llvm_unreachable("dependent cast kind in IR gen!");
3993
3994 case CK_BuiltinFnToFnPtr:
3995 llvm_unreachable("builtin functions are handled elsewhere");
3996
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003997 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003998 case CK_NonAtomicToAtomic:
3999 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00004000 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00004001
Anders Carlsson8a01a752011-04-11 02:03:26 +00004002 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00004003 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004004 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004005 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00004006 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00004007 }
4008
John McCalle3027922010-08-25 11:45:40 +00004009 case CK_ConstructorConversion:
4010 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00004011 case CK_CPointerToObjCPointerCast:
4012 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00004013 case CK_NoOp:
4014 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00004015 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00004016
John McCalle3027922010-08-25 11:45:40 +00004017 case CK_UncheckedDerivedToBase:
4018 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00004019 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00004020 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004021 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00004022
Anders Carlssond95f9602009-09-12 16:16:49 +00004023 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004024 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00004025
Anders Carlssond95f9602009-09-12 16:16:49 +00004026 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00004027 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00004028 This, DerivedClassDecl, E->path_begin(), E->path_end(),
4029 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00004030
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004031 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo());
Anders Carlssond95f9602009-09-12 16:16:49 +00004032 }
John McCalle3027922010-08-25 11:45:40 +00004033 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00004034 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00004035 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00004036 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004037 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00004038
Anders Carlsson8c793172009-11-23 17:57:54 +00004039 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00004040
Anders Carlsson8c793172009-11-23 17:57:54 +00004041 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00004042 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00004043 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00004044 E->path_begin(), E->path_end(),
4045 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00004046
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004047 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
4048 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00004049 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004050 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00004051 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004052
Peter Collingbourned2926c92015-03-14 02:42:25 +00004053 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00004054 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
4055 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00004056 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00004057
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004058 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo());
Eli Friedman8c98dff2009-11-16 05:48:01 +00004059 }
John McCalle3027922010-08-25 11:45:40 +00004060 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00004061 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004062 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00004063
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00004064 CGM.EmitExplicitCastExprType(CE, this);
Anders Carlsson50cb3212009-11-14 21:21:42 +00004065 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004066 Address V = Builder.CreateBitCast(LV.getAddress(),
4067 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00004068
4069 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00004070 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
4071 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00004072 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00004073
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004074 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo());
Anders Carlsson50cb3212009-11-14 21:21:42 +00004075 }
John McCalle3027922010-08-25 11:45:40 +00004076 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004077 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004078 Address V = Builder.CreateElementBitCast(LV.getAddress(),
4079 ConvertType(E->getType()));
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004080 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004081 }
Egor Churaev89831422016-12-23 14:55:49 +00004082 case CK_ZeroToOCLQueue:
4083 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004084 case CK_ZeroToOCLEvent:
4085 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00004086 }
Craig Topper99e79272013-07-26 05:59:26 +00004087
Douglas Gregorcdb466e2010-07-15 18:58:16 +00004088 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00004089}
4090
John McCall1bf58462011-02-16 08:02:54 +00004091LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00004092 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00004093 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00004094}
4095
Eli Friedman7f1ff602012-04-16 03:54:45 +00004096RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004097 const FieldDecl *FD,
4098 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004099 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00004100 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00004101 switch (getEvaluationKind(FT)) {
4102 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004103 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00004104 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00004105 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00004106 case TEK_Scalar:
Reid Kleckner9d031092016-05-02 22:42:34 +00004107 // This routine is used to load fields one-by-one to perform a copy, so
4108 // don't load reference fields.
4109 if (FD->getType()->isReferenceType())
4110 return RValue::get(FieldLV.getPointer());
Nick Lewycky2d84e842013-10-02 02:29:49 +00004111 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00004112 }
4113 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004114}
Douglas Gregorfe314812011-06-21 17:03:29 +00004115
Chris Lattnere47e4402007-06-01 18:02:12 +00004116//===--------------------------------------------------------------------===//
4117// Expression Emission
4118//===--------------------------------------------------------------------===//
4119
Craig Topper99e79272013-07-26 05:59:26 +00004120RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00004121 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00004122 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00004123 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00004124 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00004125
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004126 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00004127 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00004128
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004129 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00004130 return EmitCUDAKernelCallExpr(CE, ReturnValue);
4131
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004132 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
John McCallb92ab1a2016-10-26 23:46:34 +00004133 if (const CXXMethodDecl *MD =
4134 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
Anders Carlssonbfb36712009-12-24 21:13:40 +00004135 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00004136
John McCallb92ab1a2016-10-26 23:46:34 +00004137 CGCallee callee = EmitCallee(E->getCallee());
Craig Topper99e79272013-07-26 05:59:26 +00004138
John McCallb92ab1a2016-10-26 23:46:34 +00004139 if (callee.isBuiltin()) {
4140 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
4141 E, ReturnValue);
Douglas Gregorad8a3362009-09-04 17:36:40 +00004142 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004143
John McCallb92ab1a2016-10-26 23:46:34 +00004144 if (callee.isPseudoDestructor()) {
4145 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
4146 }
4147
4148 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
4149}
4150
4151/// Emit a CallExpr without considering whether it might be a subclass.
4152RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
4153 ReturnValueSlot ReturnValue) {
4154 CGCallee Callee = EmitCallee(E->getCallee());
4155 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
4156}
4157
4158static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
4159 if (auto builtinID = FD->getBuiltinID()) {
4160 return CGCallee::forBuiltin(builtinID, FD);
4161 }
4162
4163 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
4164 return CGCallee::forDirect(calleePtr, FD);
4165}
4166
4167CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
4168 E = E->IgnoreParens();
4169
4170 // Look through function-to-pointer decay.
4171 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
4172 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
4173 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
4174 return EmitCallee(ICE->getSubExpr());
4175 }
4176
4177 // Resolve direct calls.
4178 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
4179 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
4180 return EmitDirectCallee(*this, FD);
4181 }
4182 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
4183 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
4184 EmitIgnoredExpr(ME->getBase());
4185 return EmitDirectCallee(*this, FD);
4186 }
4187
4188 // Look through template substitutions.
4189 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4190 return EmitCallee(NTTP->getReplacement());
4191
4192 // Treat pseudo-destructor calls differently.
4193 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4194 return CGCallee::forPseudoDestructor(PDE);
4195 }
4196
4197 // Otherwise, we have an indirect reference.
4198 llvm::Value *calleePtr;
4199 QualType functionType;
4200 if (auto ptrType = E->getType()->getAs<PointerType>()) {
4201 calleePtr = EmitScalarExpr(E);
4202 functionType = ptrType->getPointeeType();
4203 } else {
4204 functionType = E->getType();
4205 calleePtr = EmitLValue(E).getPointer();
4206 }
4207 assert(functionType->isFunctionType());
4208 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
4209 E->getReferencedDeclOfCallee());
4210 CGCallee callee(calleeInfo, calleePtr);
4211 return callee;
Chris Lattner9e47ead2007-08-31 04:44:06 +00004212}
4213
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004214LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00004215 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00004216 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00004217 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00004218 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00004219 return EmitLValue(E->getRHS());
4220 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004221
John McCalle3027922010-08-25 11:45:40 +00004222 if (E->getOpcode() == BO_PtrMemD ||
4223 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004224 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004225
John McCalla2342eb2010-12-05 02:00:02 +00004226 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00004227
4228 // Note that in all of these cases, __block variables need the RHS
4229 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00004230
4231 switch (getEvaluationKind(E->getType())) {
4232 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00004233 switch (E->getLHS()->getType().getObjCLifetime()) {
4234 case Qualifiers::OCL_Strong:
4235 return EmitARCStoreStrong(E, /*ignored*/ false).first;
4236
4237 case Qualifiers::OCL_Autoreleasing:
4238 return EmitARCStoreAutoreleasing(E).first;
4239
4240 // No reason to do any of these differently.
4241 case Qualifiers::OCL_None:
4242 case Qualifiers::OCL_ExplicitNone:
4243 case Qualifiers::OCL_Weak:
4244 break;
4245 }
4246
John McCalld0a30012010-12-06 06:10:02 +00004247 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00004248 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
Vedant Kumar6b22dda2017-04-26 21:55:17 +00004249 if (RV.isScalar())
4250 EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
John McCall55e1fbc2011-06-25 02:11:03 +00004251 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00004252 return LV;
4253 }
John McCall4f29b492010-11-16 23:07:28 +00004254
John McCall47fb9502013-03-07 21:37:08 +00004255 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00004256 return EmitComplexAssignmentLValue(E);
4257
John McCall47fb9502013-03-07 21:37:08 +00004258 case TEK_Aggregate:
4259 return EmitAggExprToLValue(E);
4260 }
4261 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004262}
4263
Christopher Lambd91c3d42007-12-29 05:02:41 +00004264LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00004265 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00004266
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004267 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004268 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004269 LValueBaseInfo(AlignmentSource::Decl, false));
Craig Topper99e79272013-07-26 05:59:26 +00004270
David Majnemerced8bdf2015-02-25 17:36:15 +00004271 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004272 "Can't have a scalar return unless the return type is a "
4273 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00004274
John McCall7f416cc2015-09-08 08:05:57 +00004275 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00004276}
4277
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004278LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4279 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00004280 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004281}
4282
Anders Carlsson3be22e22009-05-30 23:23:33 +00004283LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004284 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
4285 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004286 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00004287 EmitCXXConstructExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004288 return MakeAddrLValue(Slot.getAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004289 LValueBaseInfo(AlignmentSource::Decl, false));
Anders Carlsson3be22e22009-05-30 23:23:33 +00004290}
4291
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004292LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00004293CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004294 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00004295}
4296
John McCall7f416cc2015-09-08 08:05:57 +00004297Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
4298 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4299 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00004300}
4301
4302LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004303 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004304 LValueBaseInfo(AlignmentSource::Decl, false));
Nico Webercf4ff5862012-10-11 10:13:44 +00004305}
4306
Mike Stumpc9b231c2009-11-15 08:09:41 +00004307LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004308CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004309 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00004310 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00004311 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004312 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
4313 return MakeAddrLValue(Slot.getAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004314 LValueBaseInfo(AlignmentSource::Decl, false));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004315}
4316
Eli Friedman5bc17122012-02-08 05:34:55 +00004317LValue
4318CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00004319 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00004320 EmitLambdaExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004321 return MakeAddrLValue(Slot.getAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004322 LValueBaseInfo(AlignmentSource::Decl, false));
Eli Friedman5bc17122012-02-08 05:34:55 +00004323}
4324
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004325LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004326 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00004327
Anders Carlsson280e61f12010-06-21 20:59:55 +00004328 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004329 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004330 LValueBaseInfo(AlignmentSource::Decl, false));
Craig Topper99e79272013-07-26 05:59:26 +00004331
Alp Toker314cc812014-01-25 16:55:45 +00004332 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00004333 "Can't have a scalar return unless the return type is a "
4334 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00004335
John McCall7f416cc2015-09-08 08:05:57 +00004336 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004337}
4338
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004339LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004340 Address V =
4341 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004342 return MakeAddrLValue(V, E->getType(),
4343 LValueBaseInfo(AlignmentSource::Decl, false));
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004344}
4345
Daniel Dunbar722f4242009-04-22 05:08:15 +00004346llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004347 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004348 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004349}
4350
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004351LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4352 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004353 const ObjCIvarDecl *Ivar,
4354 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00004355 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00004356 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004357}
4358
4359LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004360 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00004361 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004362 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00004363 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004364 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004365 if (E->isArrow()) {
4366 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004367 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00004368 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004369 } else {
4370 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00004371 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004372 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00004373 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004374 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004375
Craig Topper99e79272013-07-26 05:59:26 +00004376 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00004377 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4378 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00004379 setObjCGCLValueClass(getContext(), E, LV);
4380 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00004381}
4382
Chris Lattnera4185c52009-04-25 19:35:26 +00004383LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00004384 // Can only get l-value for message expression returning aggregate type
4385 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00004386 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004387 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattnera4185c52009-04-25 19:35:26 +00004388}
4389
John McCallb92ab1a2016-10-26 23:46:34 +00004390RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004391 const CallExpr *E, ReturnValueSlot ReturnValue,
John McCallb92ab1a2016-10-26 23:46:34 +00004392 llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00004393 // Get the actual function type. The callee type will always be a pointer to
4394 // function type or a block pointer type.
4395 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00004396 "Call must have function pointer type!");
4397
John McCallb92ab1a2016-10-26 23:46:34 +00004398 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
Samuel Antao798f11c2015-11-23 22:04:44 +00004399
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004400 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
Eric Christopher39db7262015-11-14 01:56:04 +00004401 // We can only guarantee that a function is called from the correct
4402 // context/function based on the appropriate target attributes,
4403 // so only check in the case where we have both always_inline and target
4404 // since otherwise we could be making a conditional call after a check for
4405 // the proper cpu features (and it won't cause code generation issues due to
4406 // function based code generation).
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004407 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4408 TargetDecl->hasAttr<TargetAttr>())
4409 checkTargetFeatures(E, FD);
4410
John McCall6fd4c232009-10-23 08:22:42 +00004411 CalleeType = getContext().getCanonicalType(CalleeType);
4412
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004413 const auto *FnType =
4414 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00004415
John McCallb92ab1a2016-10-26 23:46:34 +00004416 CGCallee Callee = OrigCallee;
4417
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004418 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004419 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4420 if (llvm::Constant *PrefixSig =
4421 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00004422 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004423 llvm::Constant *FTRTTIConst =
4424 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
Vedant Kumarbb5d4852017-09-13 00:04:35 +00004425 llvm::Type *PrefixStructTyElems[] = {PrefixSig->getType(), Int32Ty};
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004426 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4427 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4428
John McCallb92ab1a2016-10-26 23:46:34 +00004429 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4430
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004431 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
John McCallb92ab1a2016-10-26 23:46:34 +00004432 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004433 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004434 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00004435 llvm::Value *CalleeSig =
4436 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004437 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4438
4439 llvm::BasicBlock *Cont = createBasicBlock("cont");
4440 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4441 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4442
4443 EmitBlock(TypeCheck);
4444 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004445 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
Vedant Kumarbb5d4852017-09-13 00:04:35 +00004446 llvm::Value *CalleeRTTIEncoded =
John McCall7f416cc2015-09-08 08:05:57 +00004447 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Vedant Kumarbb5d4852017-09-13 00:04:35 +00004448 llvm::Value *CalleeRTTI =
4449 DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004450 llvm::Value *CalleeRTTIMatch =
4451 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4452 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004453 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004454 EmitCheckTypeDescriptor(CalleeType)
4455 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00004456 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004457 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004458
4459 Builder.CreateBr(Cont);
4460 EmitBlock(Cont);
4461 }
4462 }
4463
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004464 // If we are checking indirect calls and this call is indirect, check that the
4465 // function pointer is a member of the bit set for the function type.
4466 if (SanOpts.has(SanitizerKind::CFIICall) &&
4467 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4468 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00004469 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004470
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004471 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004472 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004473
John McCallb92ab1a2016-10-26 23:46:34 +00004474 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4475 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004476 llvm::Value *TypeTest = Builder.CreateCall(
4477 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004478
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004479 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004480 llvm::Constant *StaticData[] = {
4481 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4482 EmitCheckSourceLocation(E->getLocStart()),
4483 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4484 };
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004485 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4486 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004487 CastedCallee, StaticData);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004488 } else {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004489 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004490 SanitizerHandler::CFICheckFail, StaticData,
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004491 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004492 }
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004493 }
4494
Daniel Dunbarc722b852008-08-30 03:02:31 +00004495 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00004496 if (Chain)
4497 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4498 CGM.getContext().VoidPtrTy);
Richard Smith762672a2016-09-28 19:09:10 +00004499
4500 // C++17 requires that we evaluate arguments to a call using assignment syntax
Richard Smitha560ccf2016-09-29 21:30:12 +00004501 // right-to-left, and that we evaluate arguments to certain other operators
4502 // left-to-right. Note that we allow this to override the order dictated by
4503 // the calling convention on the MS ABI, which means that parameter
4504 // destruction order is not necessarily reverse construction order.
4505 // FIXME: Revisit this based on C++ committee response to unimplementability.
4506 EvaluationOrder Order = EvaluationOrder::Default;
4507 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4508 if (OCE->isAssignmentOp())
4509 Order = EvaluationOrder::ForceRightToLeft;
4510 else {
4511 switch (OCE->getOperator()) {
4512 case OO_LessLess:
4513 case OO_GreaterGreater:
4514 case OO_AmpAmp:
4515 case OO_PipePipe:
4516 case OO_Comma:
4517 case OO_ArrowStar:
4518 Order = EvaluationOrder::ForceLeftToRight;
4519 break;
4520 default:
4521 break;
4522 }
4523 }
4524 }
Richard Smith762672a2016-09-28 19:09:10 +00004525
David Blaikief05779e2015-07-21 18:37:18 +00004526 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
Richard Smitha560ccf2016-09-29 21:30:12 +00004527 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
Daniel Dunbarc722b852008-08-30 03:02:31 +00004528
Peter Collingbournef7706832014-12-12 23:41:25 +00004529 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4530 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00004531
4532 // C99 6.5.2.2p6:
4533 // If the expression that denotes the called function has a type
4534 // that does not include a prototype, [the default argument
4535 // promotions are performed]. If the number of arguments does not
4536 // equal the number of parameters, the behavior is undefined. If
4537 // the function is defined with a type that includes a prototype,
4538 // and either the prototype ends with an ellipsis (, ...) or the
4539 // types of the arguments after promotion are not compatible with
4540 // the types of the parameters, the behavior is undefined. If the
4541 // function is defined with a type that does not include a
4542 // prototype, and the types of the arguments after promotion are
4543 // not compatible with those of the parameters after promotion,
4544 // the behavior is undefined [except in some trivial cases].
4545 // That is, in the general case, we should assume that a call
4546 // through an unprototyped function type works like a *non-variadic*
4547 // call. The way we make this work is to cast to the exact type
4548 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00004549 //
4550 // Chain calls use this same code path to add the invisible chain parameter
4551 // to the function type.
4552 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00004553 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00004554 CalleeTy = CalleeTy->getPointerTo();
John McCallb92ab1a2016-10-26 23:46:34 +00004555
4556 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4557 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4558 Callee.setFunctionPointer(CalleePtr);
John McCallcbc038a2011-09-21 08:08:30 +00004559 }
4560
John McCallb92ab1a2016-10-26 23:46:34 +00004561 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00004562}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004563
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004564LValue CodeGenFunction::
4565EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004566 Address BaseAddr = Address::invalid();
4567 if (E->getOpcode() == BO_PtrMemI) {
4568 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4569 } else {
4570 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4571 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004572
John McCallc134eb52010-08-31 21:07:20 +00004573 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4574
4575 const MemberPointerType *MPT
4576 = E->getRHS()->getType()->getAs<MemberPointerType>();
4577
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004578 LValueBaseInfo BaseInfo;
John McCall7f416cc2015-09-08 08:05:57 +00004579 Address MemberAddr =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004580 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo);
John McCallc134eb52010-08-31 21:07:20 +00004581
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004582 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004583}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004584
John McCall47fb9502013-03-07 21:37:08 +00004585/// Given the address of a temporary variable, produce an r-value of
4586/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00004587RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004588 QualType type,
4589 SourceLocation loc) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004590 LValue lvalue = MakeAddrLValue(addr, type,
4591 LValueBaseInfo(AlignmentSource::Decl, false));
John McCall47fb9502013-03-07 21:37:08 +00004592 switch (getEvaluationKind(type)) {
4593 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004594 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004595 case TEK_Aggregate:
4596 return lvalue.asAggregateRValue();
4597 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004598 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004599 }
4600 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004601}
4602
Duncan Sandse81111c2012-04-10 08:23:07 +00004603void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004604 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00004605 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004606 return;
4607
Duncan Sands65229ed2012-04-16 16:29:47 +00004608 llvm::MDBuilder MDHelper(getLLVMContext());
4609 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004610
Duncan Sands6fc46192012-04-14 12:37:26 +00004611 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004612}
John McCallfe96e0b2011-11-06 09:01:30 +00004613
4614namespace {
4615 struct LValueOrRValue {
4616 LValue LV;
4617 RValue RV;
4618 };
4619}
4620
4621static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4622 const PseudoObjectExpr *E,
4623 bool forLValue,
4624 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004625 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00004626
4627 // Find the result expression, if any.
4628 const Expr *resultExpr = E->getResultExpr();
4629 LValueOrRValue result;
4630
4631 for (PseudoObjectExpr::const_semantics_iterator
4632 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4633 const Expr *semantic = *i;
4634
4635 // If this semantic expression is an opaque value, bind it
4636 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004637 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00004638
4639 // If this is the result expression, we may need to evaluate
4640 // directly into the slot.
4641 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4642 OVMA opaqueData;
4643 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00004644 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00004645 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004646 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
John McCall7f416cc2015-09-08 08:05:57 +00004647 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004648 BaseInfo);
John McCallfe96e0b2011-11-06 09:01:30 +00004649 opaqueData = OVMA::bind(CGF, ov, LV);
4650 result.RV = slot.asRValue();
4651
4652 // Otherwise, emit as normal.
4653 } else {
4654 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4655
4656 // If this is the result, also evaluate the result now.
4657 if (ov == resultExpr) {
4658 if (forLValue)
4659 result.LV = CGF.EmitLValue(ov);
4660 else
4661 result.RV = CGF.EmitAnyExpr(ov, slot);
4662 }
4663 }
4664
4665 opaques.push_back(opaqueData);
4666
4667 // Otherwise, if the expression is the result, evaluate it
4668 // and remember the result.
4669 } else if (semantic == resultExpr) {
4670 if (forLValue)
4671 result.LV = CGF.EmitLValue(semantic);
4672 else
4673 result.RV = CGF.EmitAnyExpr(semantic, slot);
4674
4675 // Otherwise, evaluate the expression in an ignored context.
4676 } else {
4677 CGF.EmitIgnoredExpr(semantic);
4678 }
4679 }
4680
4681 // Unbind all the opaques now.
4682 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4683 opaques[i].unbind(CGF);
4684
4685 return result;
4686}
4687
4688RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4689 AggValueSlot slot) {
4690 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4691}
4692
4693LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4694 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4695}