blob: ba970b9bde19db429a7f9fea03c02ac421b2d4b2 [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
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000572bool CodeGenFunction::sanitizePerformTypeCheck() const {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000573 return SanOpts.has(SanitizerKind::Null) |
574 SanOpts.has(SanitizerKind::Alignment) |
575 SanOpts.has(SanitizerKind::ObjectSize) |
576 SanOpts.has(SanitizerKind::Vptr);
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000577}
578
Richard Smithe30752c2012-10-09 19:52:38 +0000579void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +0000580 llvm::Value *Ptr, QualType Ty,
Vedant Kumar18348ea2017-02-17 23:22:55 +0000581 CharUnits Alignment,
582 SanitizerSet SkippedChecks) {
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000583 if (!sanitizePerformTypeCheck())
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000584 return;
585
Richard Smith2d8b2942012-11-01 07:22:08 +0000586 // Don't check pointers outside the default address space. The null check
587 // isn't correct, the object-size check isn't supported by LLVM, and we can't
588 // communicate the addresses to the runtime handler for the vptr check.
John McCall7f416cc2015-09-08 08:05:57 +0000589 if (Ptr->getType()->getPointerAddressSpace())
Richard Smith2d8b2942012-11-01 07:22:08 +0000590 return;
591
Vedant Kumarc420d142017-06-16 03:27:36 +0000592 // Don't check pointers to volatile data. The behavior here is implementation-
593 // defined.
594 if (Ty.isVolatileQualified())
595 return;
596
Alexey Samsonov24cad992014-07-17 18:46:27 +0000597 SanitizerScope SanScope(this);
598
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000599 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
Craig Topper8a13c412014-05-21 05:09:00 +0000600 llvm::BasicBlock *Done = nullptr;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000601
Vedant Kumare859ebb2017-04-26 02:17:21 +0000602 // Quickly determine whether we have a pointer to an alloca. It's possible
603 // to skip null checks, and some alignment checks, for these pointers. This
604 // can reduce compile-time significantly.
605 auto PtrToAlloca =
606 dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCastsNoFollowAliases());
607
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000608 llvm::Value *IsNonNull = nullptr;
609 bool IsGuaranteedNonNull =
610 SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000611 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
612 TCK == TCK_UpcastToVirtualBase;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000613 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000614 !IsGuaranteedNonNull) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000615 // The glvalue must not be an empty glvalue.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000616 IsNonNull = Builder.CreateIsNotNull(Ptr);
Richard Smith2c5868c2013-02-13 21:18:23 +0000617
Vedant Kumardbbdda42017-04-17 22:26:10 +0000618 // The IR builder can constant-fold the null check if the pointer points to
619 // a constant.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000620 IsGuaranteedNonNull =
Vedant Kumardbbdda42017-04-17 22:26:10 +0000621 IsNonNull == llvm::ConstantInt::getTrue(getLLVMContext());
622
623 // Skip the null check if the pointer is known to be non-null.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000624 if (!IsGuaranteedNonNull) {
Vedant Kumardbbdda42017-04-17 22:26:10 +0000625 if (AllowNullPointers) {
626 // When performing pointer casts, it's OK if the value is null.
627 // Skip the remaining checks in that case.
628 Done = createBasicBlock("null");
629 llvm::BasicBlock *Rest = createBasicBlock("not.null");
630 Builder.CreateCondBr(IsNonNull, Rest, Done);
631 EmitBlock(Rest);
632 } else {
633 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
634 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000635 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000636 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000637
Vedant Kumar18348ea2017-02-17 23:22:55 +0000638 if (SanOpts.has(SanitizerKind::ObjectSize) &&
639 !SkippedChecks.has(SanitizerKind::ObjectSize) &&
640 !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000641 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000642
Richard Smith69d0d262012-08-24 00:54:33 +0000643 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000644 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000645 // to check this.
Matt Arsenault2f152632013-10-07 19:00:18 +0000646 // FIXME: Get object address space
647 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
648 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smith69d0d262012-08-24 00:54:33 +0000649 llvm::Value *Min = Builder.getFalse();
George Burgess IVa63f9152017-03-21 20:09:35 +0000650 llvm::Value *NullIsUnknown = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +0000651 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
George Burgess IVa63f9152017-03-21 20:09:35 +0000652 llvm::Value *LargeEnough = Builder.CreateICmpUGE(
653 Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown}),
654 llvm::ConstantInt::get(IntPtrTy, Size));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000655 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
Richard Smithe30752c2012-10-09 19:52:38 +0000656 }
Richard Smith69d0d262012-08-24 00:54:33 +0000657
Richard Smithb1b0ab42012-11-05 22:21:05 +0000658 uint64_t AlignVal = 0;
659
Vedant Kumar18348ea2017-02-17 23:22:55 +0000660 if (SanOpts.has(SanitizerKind::Alignment) &&
661 !SkippedChecks.has(SanitizerKind::Alignment)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000662 AlignVal = Alignment.getQuantity();
663 if (!Ty->isIncompleteType() && !AlignVal)
664 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
665
Richard Smith69d0d262012-08-24 00:54:33 +0000666 // The glvalue must be suitably aligned.
Vedant Kumare859ebb2017-04-26 02:17:21 +0000667 if (AlignVal > 1 &&
668 (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000669 llvm::Value *Align =
John McCall7f416cc2015-09-08 08:05:57 +0000670 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
Richard Smithb1b0ab42012-11-05 22:21:05 +0000671 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
672 llvm::Value *Aligned =
673 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000674 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000675 }
Richard Smith69d0d262012-08-24 00:54:33 +0000676 }
677
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000678 if (Checks.size() > 0) {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000679 // Make sure we're not losing information. Alignment needs to be a power of
680 // 2
681 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
Richard Smithe30752c2012-10-09 19:52:38 +0000682 llvm::Constant *StaticData[] = {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000683 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
684 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
685 llvm::ConstantInt::get(Int8Ty, TCK)};
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000686 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData, Ptr);
Richard Smithe30752c2012-10-09 19:52:38 +0000687 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000688
Richard Smithb1b0ab42012-11-05 22:21:05 +0000689 // If possible, check that the vptr indicates that there is a subobject of
690 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000691 //
692 // C++11 [basic.life]p5,6:
693 // [For storage which does not refer to an object within its lifetime]
694 // The program has undefined behavior if:
695 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000696 // or call a non-static member function
Richard Smith4d3110a2012-10-25 02:14:12 +0000697 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000698 if (SanOpts.has(SanitizerKind::Vptr) &&
Vedant Kumara0c36712017-08-02 18:10:31 +0000699 !SkippedChecks.has(SanitizerKind::Vptr) &&
Richard Smith2c5868c2013-02-13 21:18:23 +0000700 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000701 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
702 TCK == TCK_UpcastToVirtualBase) &&
Richard Smith4d3110a2012-10-25 02:14:12 +0000703 RD && RD->hasDefinition() && RD->isDynamicClass()) {
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000704 // Ensure that the pointer is non-null before loading it. If there is no
Vedant Kumara0c36712017-08-02 18:10:31 +0000705 // compile-time guarantee, reuse the run-time null check or emit a new one.
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000706 if (!IsGuaranteedNonNull) {
Vedant Kumara0c36712017-08-02 18:10:31 +0000707 if (!IsNonNull)
708 IsNonNull = Builder.CreateIsNotNull(Ptr);
Vedant Kumarbbc953f2017-07-25 19:34:23 +0000709 if (!Done)
710 Done = createBasicBlock("vptr.null");
711 llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
712 Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
713 EmitBlock(VptrNotNull);
714 }
715
Richard Smith4d3110a2012-10-25 02:14:12 +0000716 // Compute a hash of the mangled name of the type.
717 //
718 // FIXME: This is not guaranteed to be deterministic! Move to a
719 // fingerprinting mechanism once LLVM provides one. For the time
720 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000721 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000722 llvm::raw_svector_ostream Out(MangledName);
723 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
724 Out);
Richard Smith4d3110a2012-10-25 02:14:12 +0000725
Alexey Samsonov84856012014-07-10 22:34:19 +0000726 // Blacklist based on the mangled type.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000727 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
Vlad Tsyrklevich2eccdab2017-09-25 22:11:12 +0000728 SanitizerKind::Vptr, Out.str())) {
Alexey Samsonov84856012014-07-10 22:34:19 +0000729 llvm::hash_code TypeHash = hash_value(Out.str());
Richard Smith4d3110a2012-10-25 02:14:12 +0000730
Alexey Samsonov84856012014-07-10 22:34:19 +0000731 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
732 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
733 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
John McCall7f416cc2015-09-08 08:05:57 +0000734 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000735 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
736 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
Richard Smith4d3110a2012-10-25 02:14:12 +0000737
Alexey Samsonov84856012014-07-10 22:34:19 +0000738 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
739 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
Richard Smith4d3110a2012-10-25 02:14:12 +0000740
Alexey Samsonov84856012014-07-10 22:34:19 +0000741 // Look the hash up in our cache.
742 const int CacheSize = 128;
743 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
744 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
745 "__ubsan_vptr_type_cache");
746 llvm::Value *Slot = Builder.CreateAnd(Hash,
747 llvm::ConstantInt::get(IntPtrTy,
748 CacheSize-1));
749 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
750 llvm::Value *CacheVal =
John McCall7f416cc2015-09-08 08:05:57 +0000751 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
752 getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000753
754 // If the hash isn't in the cache, call a runtime handler to perform the
755 // hard work of checking whether the vptr is for an object of the right
756 // type. This will either fill in the cache and return, or produce a
757 // diagnostic.
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000758 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
Alexey Samsonov84856012014-07-10 22:34:19 +0000759 llvm::Constant *StaticData[] = {
760 EmitCheckSourceLocation(Loc),
761 EmitCheckTypeDescriptor(Ty),
762 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
763 llvm::ConstantInt::get(Int8Ty, TCK)
764 };
John McCall7f416cc2015-09-08 08:05:57 +0000765 llvm::Value *DynamicData[] = { Ptr, Hash };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000766 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000767 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
768 DynamicData);
Alexey Samsonov84856012014-07-10 22:34:19 +0000769 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000770 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000771
772 if (Done) {
773 Builder.CreateBr(Done);
774 EmitBlock(Done);
775 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000776}
Chris Lattner4647a212007-08-31 22:49:20 +0000777
Richard Smith539e4a72013-02-23 02:53:19 +0000778/// Determine whether this expression refers to a flexible array member in a
779/// struct. We disable array bounds checks for such members.
780static bool isFlexibleArrayMemberExpr(const Expr *E) {
781 // For compatibility with existing code, we treat arrays of length 0 or
782 // 1 as flexible array members.
783 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000784 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000785 if (CAT->getSize().ugt(1))
786 return false;
787 } else if (!isa<IncompleteArrayType>(AT))
788 return false;
789
790 E = E->IgnoreParens();
791
792 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000793 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000794 // FIXME: If the base type of the member expr is not FD->getParent(),
795 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000796 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith539e4a72013-02-23 02:53:19 +0000797 RecordDecl::field_iterator FI(
798 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
799 return ++FI == FD->getParent()->field_end();
800 }
Vedant Kumare356f1a2016-10-04 20:36:04 +0000801 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
802 return IRE->getDecl()->getNextIvar() == nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000803 }
804
805 return false;
806}
807
808/// If Base is known to point to the start of an array, return the length of
809/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000810static llvm::Value *getArrayIndexingBound(
811 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000812 // For the vector indexing extension, the bound is the number of elements.
813 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
814 IndexedType = Base->getType();
815 return CGF.Builder.getInt32(VT->getNumElements());
816 }
817
818 Base = Base->IgnoreParens();
819
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000820 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000821 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
822 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
823 IndexedType = CE->getSubExpr()->getType();
824 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000825 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000826 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000827 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000828 return CGF.getVLASize(VAT).first;
829 }
830 }
831
Craig Topper8a13c412014-05-21 05:09:00 +0000832 return nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000833}
834
835void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
836 llvm::Value *Index, QualType IndexType,
837 bool Accessed) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000838 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
Richard Smith6b53e222013-10-22 22:51:04 +0000839 "should not be called unless adding bounds checks");
Alexey Samsonov24cad992014-07-17 18:46:27 +0000840 SanitizerScope SanScope(this);
Richard Smith2847b222013-02-24 01:56:24 +0000841
Richard Smith539e4a72013-02-23 02:53:19 +0000842 QualType IndexedType;
843 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
844 if (!Bound)
845 return;
846
847 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
848 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
849 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
850
851 llvm::Constant *StaticData[] = {
852 EmitCheckSourceLocation(E->getExprLoc()),
853 EmitCheckTypeDescriptor(IndexedType),
854 EmitCheckTypeDescriptor(IndexType)
855 };
856 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
857 : Builder.CreateICmpULE(IndexVal, BoundVal);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000858 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
859 SanitizerHandler::OutOfBounds, StaticData, Index);
Richard Smith539e4a72013-02-23 02:53:19 +0000860}
861
Chris Lattner116ce8f2010-01-09 21:40:03 +0000862
Chris Lattner116ce8f2010-01-09 21:40:03 +0000863CodeGenFunction::ComplexPairTy CodeGenFunction::
864EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
865 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000866 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +0000867
Chris Lattner116ce8f2010-01-09 21:40:03 +0000868 llvm::Value *NextVal;
869 if (isa<llvm::IntegerType>(InVal.first->getType())) {
870 uint64_t AmountVal = isInc ? 1 : -1;
871 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +0000872
Chris Lattner116ce8f2010-01-09 21:40:03 +0000873 // Add the inc/dec to the real part.
874 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
875 } else {
876 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
877 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
878 if (!isInc)
879 FVal.changeSign();
880 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
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.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
884 }
Craig Topper99e79272013-07-26 05:59:26 +0000885
Chris Lattner116ce8f2010-01-09 21:40:03 +0000886 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +0000887
Chris Lattner116ce8f2010-01-09 21:40:03 +0000888 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +0000889 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Craig Topper99e79272013-07-26 05:59:26 +0000890
Chris Lattner116ce8f2010-01-09 21:40:03 +0000891 // If this is a postinc, return the value read from memory, otherwise use the
892 // updated value.
893 return isPre ? IncVal : InVal;
894}
895
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000896void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
897 CodeGenFunction *CGF) {
898 // Bind VLAs in the cast type.
899 if (CGF && E->getType()->isVariablyModifiedType())
900 CGF->EmitVariablyModifiedType(E->getType());
901
902 if (CGDebugInfo *DI = getModuleDebugInfo())
903 DI->EmitExplicitCastType(E->getType());
904}
905
Chris Lattnera45c5af2007-06-02 19:47:04 +0000906//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000907// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000908//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000909
John McCall7f416cc2015-09-08 08:05:57 +0000910/// EmitPointerWithAlignment - Given an expression of pointer type, try to
911/// derive a more accurate bound on the alignment of the pointer.
912Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000913 LValueBaseInfo *BaseInfo) {
John McCall7f416cc2015-09-08 08:05:57 +0000914 // We allow this with ObjC object pointers because of fragile ABIs.
915 assert(E->getType()->isPointerType() ||
916 E->getType()->isObjCObjectPointerType());
917 E = E->IgnoreParens();
918
919 // Casts:
920 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000921 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
922 CGM.EmitExplicitCastExprType(ECE, this);
John McCall7f416cc2015-09-08 08:05:57 +0000923
924 switch (CE->getCastKind()) {
925 // Non-converting casts (but not C's implicit conversion from void*).
926 case CK_BitCast:
927 case CK_NoOp:
Anastasia Stulova0a72ed42017-09-27 14:37:00 +0000928 case CK_AddressSpaceConversion:
John McCall7f416cc2015-09-08 08:05:57 +0000929 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
930 if (PtrTy->getPointeeType()->isVoidType())
931 break;
932
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000933 LValueBaseInfo InnerInfo;
934 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerInfo);
935 if (BaseInfo) *BaseInfo = InnerInfo;
John McCall7f416cc2015-09-08 08:05:57 +0000936
937 // If this is an explicit bitcast, and the source l-value is
938 // opaque, honor the alignment of the casted-to type.
939 if (isa<ExplicitCastExpr>(CE) &&
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000940 InnerInfo.getAlignmentSource() != AlignmentSource::Decl) {
941 LValueBaseInfo ExpInfo;
942 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(),
943 &ExpInfo);
944 if (BaseInfo)
945 BaseInfo->mergeForCast(ExpInfo);
946 Addr = Address(Addr.getPointer(), Align);
John McCall7f416cc2015-09-08 08:05:57 +0000947 }
948
Peter Collingbourne574975e2016-01-14 02:49:48 +0000949 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
950 CE->getCastKind() == CK_BitCast) {
Peter Collingbourneee381ff2015-09-09 00:01:31 +0000951 if (auto PT = E->getType()->getAs<PointerType>())
952 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
953 /*MayBeNull=*/true,
954 CodeGenFunction::CFITCK_UnrelatedCast,
955 CE->getLocStart());
956 }
Anastasia Stulova0a72ed42017-09-27 14:37:00 +0000957 return CE->getCastKind() != CK_AddressSpaceConversion
958 ? Builder.CreateBitCast(Addr, ConvertType(E->getType()))
959 : Builder.CreateAddrSpaceCast(Addr,
960 ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +0000961 }
962 break;
963
964 // Array-to-pointer decay.
965 case CK_ArrayToPointerDecay:
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000966 return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000967
968 // Derived-to-base conversions.
969 case CK_UncheckedDerivedToBase:
970 case CK_DerivedToBase: {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000971 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000972 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
973 return GetAddressOfBaseClass(Addr, Derived,
974 CE->path_begin(), CE->path_end(),
975 ShouldNullCheckClassCastValue(CE),
976 CE->getExprLoc());
977 }
978
979 // TODO: Is there any reason to treat base-to-derived conversions
980 // specially?
981 default:
982 break;
983 }
984 }
985
986 // Unary &.
987 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
988 if (UO->getOpcode() == UO_AddrOf) {
989 LValue LV = EmitLValue(UO->getSubExpr());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000990 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
John McCall7f416cc2015-09-08 08:05:57 +0000991 return LV.getAddress();
992 }
993 }
994
995 // TODO: conditional operators, comma.
996
997 // Otherwise, use the alignment of the type.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +0000998 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +0000999 return Address(EmitScalarExpr(E), Align);
1000}
1001
Daniel Dunbarc79407f2009-02-05 07:09:07 +00001002RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001003 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001004 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +00001005
1006 switch (getEvaluationKind(Ty)) {
1007 case TEK_Complex: {
1008 llvm::Type *EltTy =
1009 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +00001010 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +00001011 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001012 }
Craig Topper99e79272013-07-26 05:59:26 +00001013
Chris Lattner65526f02010-08-23 05:26:13 +00001014 // If this is a use of an undefined aggregate type, the aggregate must have an
1015 // identifiable address. Just because the contents of the value are undefined
1016 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +00001017 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +00001018 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +00001019 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +00001020 }
John McCall47fb9502013-03-07 21:37:08 +00001021
1022 case TEK_Scalar:
1023 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1024 }
1025 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +00001026}
1027
Daniel Dunbarc79407f2009-02-05 07:09:07 +00001028RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
1029 const char *Name) {
1030 ErrorUnsupported(E, Name);
1031 return GetUndefRValue(E->getType());
1032}
1033
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001034LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
1035 const char *Name) {
1036 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001037 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +00001038 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
1039 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001040}
1041
Vedant Kumarffd7c882017-04-14 22:03:34 +00001042bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001043 const Expr *Base = Obj;
1044 while (!isa<CXXThisExpr>(Base)) {
1045 // The result of a dynamic_cast can be null.
1046 if (isa<CXXDynamicCastExpr>(Base))
1047 return false;
1048
1049 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1050 Base = CE->getSubExpr();
1051 } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
1052 Base = PE->getSubExpr();
1053 } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1054 if (UO->getOpcode() == UO_Extension)
1055 Base = UO->getSubExpr();
1056 else
1057 return false;
1058 } else {
1059 return false;
1060 }
1061 }
1062 return true;
1063}
1064
Richard Smith4d1458e2012-09-08 02:08:36 +00001065LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +00001066 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001067 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +00001068 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1069 else
1070 LV = EmitLValue(E);
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001071 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1072 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00001073 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1074 bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1075 if (IsBaseCXXThis)
1076 SkippedChecks.set(SanitizerKind::Alignment, true);
1077 if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001078 SkippedChecks.set(SanitizerKind::Null, true);
Vedant Kumarffd7c882017-04-14 22:03:34 +00001079 }
John McCall7f416cc2015-09-08 08:05:57 +00001080 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
Vedant Kumar34b1fd62017-02-17 23:22:59 +00001081 E->getType(), LV.getAlignment(), SkippedChecks);
1082 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +00001083 return LV;
1084}
1085
Chris Lattner8394d792007-06-05 20:53:16 +00001086/// EmitLValue - Emit code to compute a designator that specifies the location
1087/// of the expression.
1088///
Mike Stump4a3999f2009-09-09 13:00:44 +00001089/// This can return one of two things: a simple address or a bitfield reference.
1090/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1091/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +00001092///
Mike Stump4a3999f2009-09-09 13:00:44 +00001093/// If this returns a bitfield reference, nothing about the pointee type of the
1094/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +00001095///
Mike Stump4a3999f2009-09-09 13:00:44 +00001096/// If this returns a normal address, and if the lvalue's C type is fixed size,
1097/// this method guarantees that the returned pointer type will point to an LLVM
1098/// type of the same size of the lvalue's type. If the lvalue has a variable
1099/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +00001100///
Chris Lattnerd7f58862007-06-02 05:24:33 +00001101LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +00001102 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +00001103 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +00001104 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +00001105
John McCallc109a252011-11-07 03:59:57 +00001106 case Expr::ObjCPropertyRefExprClass:
1107 llvm_unreachable("cannot emit a property reference directly");
1108
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00001109 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +00001110 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00001111 case Expr::ObjCIsaExprClass:
1112 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001113 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00001114 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001115 case Expr::CompoundAssignOperatorClass: {
1116 QualType Ty = E->getType();
1117 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1118 Ty = AT->getValueType();
1119 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +00001120 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1121 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +00001122 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001123 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +00001124 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001125 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001126 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001127 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00001128 case Expr::VAArgExprClass:
1129 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001130 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001131 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +00001132 case Expr::ParenExprClass:
1133 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +00001134 case Expr::GenericSelectionExprClass:
1135 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +00001136 case Expr::PredefinedExprClass:
1137 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +00001138 case Expr::StringLiteralClass:
1139 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001140 case Expr::ObjCEncodeExprClass:
1141 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +00001142 case Expr::PseudoObjectExprClass:
1143 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001144 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +00001145 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +00001146 case Expr::CXXTemporaryObjectExprClass:
1147 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001148 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1149 case Expr::CXXBindTemporaryExprClass:
1150 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +00001151 case Expr::CXXUuidofExprClass:
1152 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +00001153 case Expr::LambdaExprClass:
1154 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +00001155
1156 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001157 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +00001158 enterFullExpression(cleanups);
1159 RunCleanupsScope Scope(*this);
Reid Kleckner092d0652017-03-06 22:18:34 +00001160 LValue LV = EmitLValue(cleanups->getSubExpr());
1161 if (LV.isSimple()) {
1162 // Defend against branches out of gnu statement expressions surrounded by
1163 // cleanups.
1164 llvm::Value *V = LV.getPointer();
1165 Scope.ForceCleanup({&V});
1166 return LValue::MakeAddr(Address(V, LV.getAlignment()), LV.getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001167 getContext(), LV.getBaseInfo(),
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00001168 LV.getTBAAAccessType());
Reid Kleckner092d0652017-03-06 22:18:34 +00001169 }
1170 // FIXME: Is it possible to create an ExprWithCleanups that produces a
1171 // bitfield lvalue or some other non-simple lvalue?
1172 return LV;
John McCall08ef4662011-11-10 08:15:53 +00001173 }
1174
Anders Carlsson52ce3bb2009-11-14 01:51:50 +00001175 case Expr::CXXDefaultArgExprClass:
1176 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001177 case Expr::CXXDefaultInitExprClass: {
1178 CXXDefaultInitExprScope Scope(*this);
1179 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1180 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001181 case Expr::CXXTypeidExprClass:
1182 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001183
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001184 case Expr::ObjCMessageExprClass:
1185 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001186 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001187 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001188 case Expr::StmtExprClass:
1189 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001190 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001191 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001192 case Expr::ArraySubscriptExprClass:
1193 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001194 case Expr::OMPArraySectionExprClass:
1195 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001196 case Expr::ExtVectorElementExprClass:
1197 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001198 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001199 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001200 case Expr::CompoundLiteralExprClass:
1201 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001202 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001203 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001204 case Expr::BinaryConditionalOperatorClass:
1205 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001206 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001207 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001208 case Expr::OpaqueValueExprClass:
1209 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001210 case Expr::SubstNonTypeTemplateParmExprClass:
1211 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001212 case Expr::ImplicitCastExprClass:
1213 case Expr::CStyleCastExprClass:
1214 case Expr::CXXFunctionalCastExprClass:
1215 case Expr::CXXStaticCastExprClass:
1216 case Expr::CXXDynamicCastExprClass:
1217 case Expr::CXXReinterpretCastExprClass:
1218 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001219 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001220 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001221
Douglas Gregorfe314812011-06-21 17:03:29 +00001222 case Expr::MaterializeTemporaryExprClass:
1223 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Eric Fiseliercddaf872017-06-15 19:43:36 +00001224
1225 case Expr::CoawaitExprClass:
1226 return EmitCoawaitLValue(cast<CoawaitExpr>(E));
1227 case Expr::CoyieldExprClass:
1228 return EmitCoyieldLValue(cast<CoyieldExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001229 }
1230}
1231
John McCall71335052012-03-10 03:05:10 +00001232/// Given an object of the given canonical type, can we safely copy a
1233/// value out of it based on its initializer?
1234static bool isConstantEmittableObjectType(QualType type) {
1235 assert(type.isCanonical());
1236 assert(!type->isReferenceType());
1237
1238 // Must be const-qualified but non-volatile.
1239 Qualifiers qs = type.getLocalQualifiers();
1240 if (!qs.hasConst() || qs.hasVolatile()) return false;
1241
1242 // Otherwise, all object types satisfy this except C++ classes with
1243 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001244 if (const auto *RT = dyn_cast<RecordType>(type))
1245 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001246 if (RD->hasMutableFields() || !RD->isTrivial())
1247 return false;
1248
1249 return true;
1250}
1251
1252/// Can we constant-emit a load of a reference to a variable of the
1253/// given type? This is different from predicates like
1254/// Decl::isUsableInConstantExpressions because we do want it to apply
1255/// in situations that don't necessarily satisfy the language's rules
1256/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1257/// to do this with const float variables even if those variables
1258/// aren't marked 'constexpr'.
1259enum ConstantEmissionKind {
1260 CEK_None,
1261 CEK_AsReferenceOnly,
1262 CEK_AsValueOrReference,
1263 CEK_AsValueOnly
1264};
1265static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1266 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001267 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001268 if (isConstantEmittableObjectType(ref->getPointeeType()))
1269 return CEK_AsValueOrReference;
1270 return CEK_AsReferenceOnly;
1271 }
1272 if (isConstantEmittableObjectType(type))
1273 return CEK_AsValueOnly;
1274 return CEK_None;
1275}
1276
1277/// Try to emit a reference to the given value without producing it as
1278/// an l-value. This is actually more than an optimization: we can't
1279/// produce an l-value for variables that we never actually captured
1280/// in a block or lambda, which means const int variables or constexpr
1281/// literals or similar.
1282CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001283CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1284 ValueDecl *value = refExpr->getDecl();
1285
John McCall71335052012-03-10 03:05:10 +00001286 // The value needs to be an enum constant or a constant variable.
1287 ConstantEmissionKind CEK;
1288 if (isa<ParmVarDecl>(value)) {
1289 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001290 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001291 CEK = checkVarTypeForConstantEmission(var->getType());
1292 } else if (isa<EnumConstantDecl>(value)) {
1293 CEK = CEK_AsValueOnly;
1294 } else {
1295 CEK = CEK_None;
1296 }
1297 if (CEK == CEK_None) return ConstantEmission();
1298
John McCall71335052012-03-10 03:05:10 +00001299 Expr::EvalResult result;
1300 bool resultIsReference;
1301 QualType resultType;
1302
1303 // It's best to evaluate all the way as an r-value if that's permitted.
1304 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001305 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001306 resultIsReference = false;
1307 resultType = refExpr->getType();
1308
1309 // Otherwise, try to evaluate as an l-value.
1310 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001311 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001312 resultIsReference = true;
1313 resultType = value->getType();
1314
1315 // Failure.
1316 } else {
1317 return ConstantEmission();
1318 }
1319
1320 // In any case, if the initializer has side-effects, abandon ship.
1321 if (result.HasSideEffects)
1322 return ConstantEmission();
1323
1324 // Emit as a constant.
John McCallde0fe072017-08-15 21:42:52 +00001325 auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
1326 result.Val, resultType);
John McCall71335052012-03-10 03:05:10 +00001327
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001328 // Make sure we emit a debug reference to the global variable.
1329 // This should probably fire even for
1330 if (isa<VarDecl>(value)) {
1331 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001332 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001333 } else {
1334 assert(isa<EnumConstantDecl>(value));
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001335 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001336 }
John McCall71335052012-03-10 03:05:10 +00001337
1338 // If we emitted a reference constant, we need to dereference that.
1339 if (resultIsReference)
1340 return ConstantEmission::forReference(C);
1341
1342 return ConstantEmission::forValue(C);
1343}
1344
Alex Lorenz6cc83172017-08-25 10:07:00 +00001345static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
1346 const MemberExpr *ME) {
1347 if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
1348 // Try to emit static variable member expressions as DREs.
1349 return DeclRefExpr::Create(
1350 CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD,
1351 /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
1352 ME->getType(), ME->getValueKind());
1353 }
1354 return nullptr;
1355}
1356
1357CodeGenFunction::ConstantEmission
1358CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
1359 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
1360 return tryEmitAsConstant(DRE);
1361 return ConstantEmission();
1362}
1363
Nick Lewycky2d84e842013-10-02 02:29:49 +00001364llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1365 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +00001366 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001367 lvalue.getType(), Loc, lvalue.getBaseInfo(),
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00001368 lvalue.getTBAAAccessType(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001369 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1370 lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001371}
1372
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001373static bool hasBooleanRepresentation(QualType Ty) {
1374 if (Ty->isBooleanType())
1375 return true;
1376
1377 if (const EnumType *ET = Ty->getAs<EnumType>())
1378 return ET->getDecl()->getIntegerType()->isBooleanType();
1379
Douglas Gregor298f43d2012-04-12 20:42:30 +00001380 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1381 return hasBooleanRepresentation(AT->getValueType());
1382
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001383 return false;
1384}
1385
Richard Smith1629da92012-12-13 07:11:50 +00001386static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1387 llvm::APInt &Min, llvm::APInt &End,
Vedant Kumar4593a462016-12-09 23:48:18 +00001388 bool StrictEnums, bool IsBool) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001389 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001390 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1391 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001392 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001393 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001394
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001395 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001396 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1397 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001398 } else {
1399 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001400 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001401 unsigned Bitwidth = LTy->getScalarSizeInBits();
1402 unsigned NumNegativeBits = ED->getNumNegativeBits();
1403 unsigned NumPositiveBits = ED->getNumPositiveBits();
1404
1405 if (NumNegativeBits) {
1406 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1407 assert(NumBits <= Bitwidth);
1408 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1409 Min = -End;
1410 } else {
1411 assert(NumPositiveBits <= Bitwidth);
1412 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1413 Min = llvm::APInt(Bitwidth, 0);
1414 }
1415 }
Richard Smith1629da92012-12-13 07:11:50 +00001416 return true;
1417}
1418
1419llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1420 llvm::APInt Min, End;
Vedant Kumar4593a462016-12-09 23:48:18 +00001421 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1422 hasBooleanRepresentation(Ty)))
Craig Topper8a13c412014-05-21 05:09:00 +00001423 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001424
Duncan Sandsc720e782012-04-15 18:04:54 +00001425 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001426 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001427}
1428
Vedant Kumar5a972652017-02-27 19:46:19 +00001429bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1430 SourceLocation Loc) {
1431 bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1432 bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1433 if (!HasBoolCheck && !HasEnumCheck)
1434 return false;
1435
1436 bool IsBool = hasBooleanRepresentation(Ty) ||
1437 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1438 bool NeedsBoolCheck = HasBoolCheck && IsBool;
1439 bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1440 if (!NeedsBoolCheck && !NeedsEnumCheck)
1441 return false;
1442
Vedant Kumar129edab2017-03-09 16:06:27 +00001443 // Single-bit booleans don't need to be checked. Special-case this to avoid
1444 // a bit width mismatch when handling bitfield values. This is handled by
1445 // EmitFromMemory for the non-bitfield case.
1446 if (IsBool &&
1447 cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1448 return false;
1449
Vedant Kumar5a972652017-02-27 19:46:19 +00001450 llvm::APInt Min, End;
1451 if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1452 return true;
1453
1454 SanitizerScope SanScope(this);
1455 llvm::Value *Check;
1456 --End;
1457 if (!Min) {
1458 Check = Builder.CreateICmpULE(
1459 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1460 } else {
1461 llvm::Value *Upper = Builder.CreateICmpSLE(
1462 Value, llvm::ConstantInt::get(getLLVMContext(), End));
1463 llvm::Value *Lower = Builder.CreateICmpSGE(
1464 Value, llvm::ConstantInt::get(getLLVMContext(), Min));
1465 Check = Builder.CreateAnd(Upper, Lower);
1466 }
1467 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1468 EmitCheckTypeDescriptor(Ty)};
1469 SanitizerMask Kind =
1470 NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1471 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1472 StaticArgs, EmitCheckValue(Value));
1473 return true;
1474}
1475
John McCall7f416cc2015-09-08 08:05:57 +00001476llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1477 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001478 SourceLocation Loc,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001479 LValueBaseInfo BaseInfo,
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00001480 llvm::MDNode *TBAAAccessType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001481 QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001482 uint64_t TBAAOffset,
1483 bool isNontemporal) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001484 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1485 // For better performance, handle vector loads differently.
1486 if (Ty->isVectorType()) {
1487 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001488
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001489 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001490
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001491 // Handle vectors of size 3 like size 4 for better performance.
1492 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001493
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001494 // Bitcast to vec4 type.
1495 llvm::VectorType *vec4Ty =
1496 llvm::VectorType::get(VTy->getElementType(), 4);
1497 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1498 // Now load value.
1499 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001500
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001501 // Shuffle vector to get vec3.
1502 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1503 {0, 1, 2}, "extractVec");
1504 return EmitFromMemory(V, Ty);
1505 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001506 }
1507 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001508
1509 // Atomic operations have to be done on integral types.
David Majnemera38c9f12016-05-24 16:09:25 +00001510 LValue AtomicLValue =
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00001511 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAAccessType);
David Majnemera38c9f12016-05-24 16:09:25 +00001512 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1513 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001514 }
Craig Topper99e79272013-07-26 05:59:26 +00001515
John McCall7f416cc2015-09-08 08:05:57 +00001516 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001517 if (isNontemporal) {
1518 llvm::MDNode *Node = llvm::MDNode::get(
1519 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1520 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1521 }
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00001522 if (TBAAAccessType) {
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00001523 bool MayAlias = BaseInfo.getMayAlias();
1524 llvm::MDNode *TBAA = MayAlias
Ivan A. Kosarev5c8e7592017-10-02 11:10:04 +00001525 ? CGM.getTBAAMayAliasTypeInfo()
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00001526 : CGM.getTBAAStructTagInfo(TBAABaseType, TBAAAccessType, TBAAOffset);
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00001527 if (TBAA)
1528 CGM.DecorateInstructionWithTBAA(Load, TBAA, MayAlias);
Manman Renc451e572013-04-04 21:53:22 +00001529 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001530
Vedant Kumar5a972652017-02-27 19:46:19 +00001531 if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1532 // In order to prevent the optimizer from throwing away the check, don't
1533 // attach range metadata to the load.
Richard Smith1629da92012-12-13 07:11:50 +00001534 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001535 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1536 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001537
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001538 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001539}
1540
John McCall3a7f6922010-10-27 20:58:56 +00001541llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1542 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001543 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001544 // This should really always be an i1, but sometimes it's already
1545 // an i8, and it's awkward to track those cases down.
1546 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001547 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1548 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1549 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001550 }
1551
1552 return Value;
1553}
1554
1555llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1556 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001557 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001558 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1559 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001560 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1561 }
1562
1563 return Value;
1564}
1565
John McCall7f416cc2015-09-08 08:05:57 +00001566void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1567 bool Volatile, QualType Ty,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001568 LValueBaseInfo BaseInfo,
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00001569 llvm::MDNode *TBAAAccessType,
Manman Renc451e572013-04-04 21:53:22 +00001570 bool isInit, QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001571 uint64_t TBAAOffset,
1572 bool isNontemporal) {
Craig Topper99e79272013-07-26 05:59:26 +00001573
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001574 if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1575 // Handle vectors differently to get better performance.
1576 if (Ty->isVectorType()) {
1577 llvm::Type *SrcTy = Value->getType();
Simon Pilgrima5dbbc62017-06-01 20:13:34 +00001578 auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001579 // Handle vec3 special.
Simon Pilgrima5dbbc62017-06-01 20:13:34 +00001580 if (VecTy && VecTy->getNumElements() == 3) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00001581 // Our source is a vec3, do a shuffle vector to make it a vec4.
1582 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1583 Builder.getInt32(2),
1584 llvm::UndefValue::get(Builder.getInt32Ty())};
1585 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1586 Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
1587 MaskV, "extractVec");
1588 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1589 }
1590 if (Addr.getElementType() != SrcTy) {
1591 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1592 }
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001593 }
1594 }
Craig Topper99e79272013-07-26 05:59:26 +00001595
John McCall3a7f6922010-10-27 20:58:56 +00001596 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001597
David Majnemera38c9f12016-05-24 16:09:25 +00001598 LValue AtomicLValue =
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00001599 LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAAccessType);
David Majnemera5b195a2015-02-14 01:35:12 +00001600 if (Ty->isAtomicType() ||
David Majnemera38c9f12016-05-24 16:09:25 +00001601 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1602 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
John McCalla8ec7eb2013-03-07 21:37:17 +00001603 return;
1604 }
1605
Daniel Dunbar03816342010-08-21 02:24:36 +00001606 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001607 if (isNontemporal) {
1608 llvm::MDNode *Node =
1609 llvm::MDNode::get(Store->getContext(),
1610 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1611 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1612 }
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00001613 if (TBAAAccessType) {
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00001614 bool MayAlias = BaseInfo.getMayAlias();
1615 llvm::MDNode *TBAA = MayAlias
Ivan A. Kosarev5c8e7592017-10-02 11:10:04 +00001616 ? CGM.getTBAAMayAliasTypeInfo()
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00001617 : CGM.getTBAAStructTagInfo(TBAABaseType, TBAAAccessType, TBAAOffset);
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00001618 if (TBAA)
1619 CGM.DecorateInstructionWithTBAA(Store, TBAA, MayAlias);
Manman Renc451e572013-04-04 21:53:22 +00001620 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001621}
1622
David Chisnallfa35df62012-01-16 17:27:18 +00001623void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001624 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001625 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00001626 lvalue.getType(), lvalue.getBaseInfo(),
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00001627 lvalue.getTBAAAccessType(), isInit,
1628 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1629 lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001630}
1631
Mike Stump4a3999f2009-09-09 13:00:44 +00001632/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1633/// method emits the address of the lvalue, then loads the result as an rvalue,
1634/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001635RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001636 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001637 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001638 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001639 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1640 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001641 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001642 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001643 // In MRC mode, we do a load+autorelease.
1644 if (!getLangOpts().ObjCAutoRefCount) {
1645 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1646 }
1647
1648 // In ARC mode, we load retained and then consume the value.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001649 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1650 Object = EmitObjCConsumeObject(LV.getType(), Object);
1651 return RValue::get(Object);
1652 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001653
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001654 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001655 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001656
John McCalla1dee5302010-08-22 10:59:02 +00001657 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001658 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001659 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001660
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001661 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001662 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001663 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001664 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001665 "vecext"));
1666 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001667
1668 // If this is a reference to a subset of the elements of a vector, either
1669 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001670 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001671 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001672
Renato Golin230c5eb2014-05-19 18:15:42 +00001673 // Global Register variables always invoke intrinsics
1674 if (LV.isGlobalReg())
1675 return EmitLoadOfGlobalRegLValue(LV);
1676
John McCallc109a252011-11-07 03:59:57 +00001677 assert(LV.isBitField() && "Unknown LValue type!");
Vedant Kumar129edab2017-03-09 16:06:27 +00001678 return EmitLoadOfBitfieldLValue(LV, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +00001679}
1680
Vedant Kumar129edab2017-03-09 16:06:27 +00001681RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1682 SourceLocation Loc) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001683 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001684
Daniel Dunbar3447a022010-04-13 23:34:15 +00001685 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001686 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001687
John McCall7f416cc2015-09-08 08:05:57 +00001688 Address Ptr = LV.getBitFieldAddress();
1689 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001690
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001691 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001692 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001693 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1694 if (HighBits)
1695 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1696 if (Info.Offset + HighBits)
1697 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1698 } else {
1699 if (Info.Offset)
1700 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001701 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001702 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1703 Info.Size),
1704 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001705 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001706 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Vedant Kumar129edab2017-03-09 16:06:27 +00001707 EmitScalarRangeCheck(Val, LV.getType(), Loc);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001708 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001709}
1710
Nate Begemanb699c9b2009-01-18 06:42:49 +00001711// If this is a reference to a subset of the elements of a vector, create an
1712// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001713RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001714 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1715 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001716
Nate Begemanf322eab2008-05-09 06:41:27 +00001717 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001718
1719 // If the result of the expression is a non-vector type, we must be extracting
1720 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001721 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001722 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001723 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001724 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001725 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001726 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001727
1728 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001729 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001730
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001731 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001732 for (unsigned i = 0; i != NumResultElts; ++i)
1733 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001734
Chris Lattner91c08ad2011-02-15 00:14:06 +00001735 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1736 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001737 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001738 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001739}
1740
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001741/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001742Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1743 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001744 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1745 QualType EQT = ExprVT->getElementType();
1746 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001747
John McCall7f416cc2015-09-08 08:05:57 +00001748 Address CastToPointerElement =
1749 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1750 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001751
1752 const llvm::Constant *Elts = LV.getExtVectorElts();
1753 unsigned ix = getAccessedFieldNo(0, Elts);
1754
John McCall7f416cc2015-09-08 08:05:57 +00001755 Address VectorBasePtrPlusIx =
1756 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1757 getContext().getTypeSizeInChars(EQT),
1758 "vector.elt");
1759
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001760 return VectorBasePtrPlusIx;
1761}
1762
Renato Golin230c5eb2014-05-19 18:15:42 +00001763/// @brief Load of global gamed gegisters are always calls to intrinsics.
1764RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001765 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1766 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001767 llvm::MDNode *RegName = cast<llvm::MDNode>(
1768 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001769
1770 // We accept integer and pointer types only
1771 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1772 llvm::Type *Ty = OrigTy;
1773 if (OrigTy->isPointerTy())
1774 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1775 llvm::Type *Types[] = { Ty };
1776
Renato Golin230c5eb2014-05-19 18:15:42 +00001777 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001778 llvm::Value *Call = Builder.CreateCall(
1779 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001780 if (OrigTy->isPointerTy())
1781 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001782 return RValue::get(Call);
1783}
Chris Lattner40ff7012007-08-03 16:18:34 +00001784
Chris Lattner9369a562007-06-29 16:31:29 +00001785
Chris Lattner8394d792007-06-05 20:53:16 +00001786/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1787/// lvalue, where both are guaranteed to the have the same type, and that type
1788/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001789void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001790 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001791 if (!Dst.isSimple()) {
1792 if (Dst.isVectorElt()) {
1793 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001794 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1795 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001796 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001797 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001798 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1799 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001800 return;
1801 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001802
Nate Begemance4d7fc2008-04-18 23:10:10 +00001803 // If this is an update of extended vector elements, insert them as
1804 // appropriate.
1805 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001806 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001807
Renato Golin230c5eb2014-05-19 18:15:42 +00001808 if (Dst.isGlobalReg())
1809 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1810
John McCallc109a252011-11-07 03:59:57 +00001811 assert(Dst.isBitField() && "Unknown LValue type");
1812 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001813 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001814
John McCall31168b02011-06-15 23:02:42 +00001815 // There's special magic for assigning into an ARC-qualified l-value.
1816 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1817 switch (Lifetime) {
1818 case Qualifiers::OCL_None:
1819 llvm_unreachable("present but none");
1820
1821 case Qualifiers::OCL_ExplicitNone:
1822 // nothing special
1823 break;
1824
1825 case Qualifiers::OCL_Strong:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001826 if (isInit) {
1827 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1828 break;
1829 }
John McCall55e1fbc2011-06-25 02:11:03 +00001830 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001831 return;
1832
1833 case Qualifiers::OCL_Weak:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001834 if (isInit)
1835 // Initialize and then skip the primitive store.
1836 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1837 else
1838 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001839 return;
1840
1841 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001842 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1843 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001844 // fall into the normal path
1845 break;
1846 }
1847 }
1848
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001849 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001850 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001851 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001852 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001853 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001854 return;
1855 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001856
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001857 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001858 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001859 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001860 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001861 if (Dst.isObjCIvar()) {
1862 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001863 llvm::Type *ResultType = IntPtrTy;
1864 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1865 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001866 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001867 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001868 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1869 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001870 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001871 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001872 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001873 } else if (Dst.isGlobalObjCRef()) {
1874 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1875 Dst.isThreadLocalRef());
1876 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001877 else
1878 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001879 return;
1880 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001881
Chris Lattner6278e6a2007-08-11 00:04:45 +00001882 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001883 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001884}
1885
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001886void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001887 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001888 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001889 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001890 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001891
Daniel Dunbar67aba792010-04-15 03:47:33 +00001892 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001893 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001894
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001895 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001896 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001897 /*IsSigned=*/false);
1898 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001899
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001900 // See if there are other bits in the bitfield's storage we'll need to load
1901 // and mask together with source before storing.
1902 if (Info.StorageSize != Info.Size) {
1903 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001904 llvm::Value *Val =
1905 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001906
1907 // Mask the source value as needed.
1908 if (!hasBooleanRepresentation(Dst.getType()))
1909 SrcVal = Builder.CreateAnd(SrcVal,
1910 llvm::APInt::getLowBitsSet(Info.StorageSize,
1911 Info.Size),
1912 "bf.value");
1913 MaskedVal = SrcVal;
1914 if (Info.Offset)
1915 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1916
1917 // Mask out the original value.
1918 Val = Builder.CreateAnd(Val,
1919 ~llvm::APInt::getBitsSet(Info.StorageSize,
1920 Info.Offset,
1921 Info.Offset + Info.Size),
1922 "bf.clear");
1923
1924 // Or together the unchanged values and the source value.
1925 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1926 } else {
1927 assert(Info.Offset == 0);
1928 }
1929
1930 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001931 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001932
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001933 // Return the new value of the bit-field, if requested.
1934 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001935 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001936
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001937 // Sign extend the value if needed.
1938 if (Info.IsSigned) {
1939 assert(Info.Size <= Info.StorageSize);
1940 unsigned HighBits = Info.StorageSize - Info.Size;
1941 if (HighBits) {
1942 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1943 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1944 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001945 }
1946
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001947 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1948 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001949 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001950 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001951}
1952
Nate Begemance4d7fc2008-04-18 23:10:10 +00001953void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001954 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001955 // This access turns into a read/modify/write of the vector. Load the input
1956 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001957 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1958 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001959 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001960
Chris Lattner4647a212007-08-31 22:49:20 +00001961 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001962
John McCall55e1fbc2011-06-25 02:11:03 +00001963 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001964 unsigned NumSrcElts = VTy->getNumElements();
Craig Topperf2f1a092016-07-08 02:17:35 +00001965 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001966 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001967 // Use shuffle vector is the src and destination are the same number of
1968 // elements and restore the vector mask since it is on the side it will be
1969 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001970 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001971 for (unsigned i = 0; i != NumSrcElts; ++i)
1972 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001973
Chris Lattner91c08ad2011-02-15 00:14:06 +00001974 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001975 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001976 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001977 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001978 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001979 // Extended the source vector to the same length and then shuffle it
1980 // into the destination.
1981 // FIXME: since we're shuffling with undef, can we just use the indices
1982 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001983 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001984 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001985 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001986 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001987 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001988 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001989 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001990 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001991 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001992 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001993 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001994 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001995 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001996
Joey Goulycf4143b2013-11-21 17:09:05 +00001997 // When the vector size is odd and .odd or .hi is used, the last element
1998 // of the Elts constant array will be one past the size of the vector.
1999 // Ignore the last element here, if it is greater than the mask size.
2000 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
2001 NumSrcElts--;
2002
Nate Begemanb699c9b2009-01-18 06:42:49 +00002003 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00002004 for (unsigned i = 0; i != NumSrcElts; ++i)
2005 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00002006 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002007 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00002008 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00002009 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00002010 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00002011 }
2012 } else {
2013 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00002014 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00002015 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002016 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00002017 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002018
John McCall7f416cc2015-09-08 08:05:57 +00002019 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
2020 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00002021}
2022
Renato Golin230c5eb2014-05-19 18:15:42 +00002023/// @brief Store of global named registers are always calls to intrinsics.
2024void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00002025 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
2026 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002027 llvm::MDNode *RegName = cast<llvm::MDNode>(
2028 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00002029 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00002030
2031 // We accept integer and pointer types only
2032 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
2033 llvm::Type *Ty = OrigTy;
2034 if (OrigTy->isPointerTy())
2035 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2036 llvm::Type *Types[] = { Ty };
2037
Renato Golin230c5eb2014-05-19 18:15:42 +00002038 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
2039 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00002040 if (OrigTy->isPointerTy())
2041 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00002042 Builder.CreateCall(
2043 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00002044}
2045
Eric Christopherc9e2a682014-05-20 17:10:39 +00002046// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002047// generating write-barries API. It is currently a global, ivar,
2048// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002049static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002050 LValue &LV,
2051 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002052 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002053 return;
Craig Topper99e79272013-07-26 05:59:26 +00002054
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002055 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002056 QualType ExpTy = E->getType();
2057 if (IsMemberAccess && ExpTy->isPointerType()) {
2058 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00002059 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002060 // writer-barrier conservatively.
2061 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2062 if (ExpTy->isRecordType()) {
2063 LV.setObjCIvar(false);
2064 return;
2065 }
2066 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002067 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002068 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00002069 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002070 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00002071 return;
2072 }
Craig Topper99e79272013-07-26 05:59:26 +00002073
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002074 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
2075 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00002076 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002077 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00002078 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00002079 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002080 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002081 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002082 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002083 }
Craig Topper99e79272013-07-26 05:59:26 +00002084
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002085 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002086 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002087 return;
2088 }
Craig Topper99e79272013-07-26 05:59:26 +00002089
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002090 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002091 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002092 if (LV.isObjCIvar()) {
2093 // If cast is to a structure pointer, follow gcc's behavior and make it
2094 // a non-ivar write-barrier.
2095 QualType ExpTy = E->getType();
2096 if (ExpTy->isPointerType())
2097 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2098 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00002099 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002100 }
2101 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00002102 }
Peter Collingbourne91147592011-04-15 00:35:48 +00002103
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002104 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00002105 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2106 return;
2107 }
2108
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002109 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002110 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002111 return;
2112 }
Craig Topper99e79272013-07-26 05:59:26 +00002113
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002114 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002115 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002116 return;
2117 }
John McCall31168b02011-06-15 23:02:42 +00002118
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002119 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002120 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00002121 return;
2122 }
2123
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002124 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002125 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00002126 if (LV.isObjCIvar() && !LV.isObjCArray())
2127 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002128 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00002129 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002130 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00002131 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00002132 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002133 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002134 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002135 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002136
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002137 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00002138 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00002139 // We don't know if member is an 'ivar', but this flag is looked at
2140 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00002141 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002142 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002143 }
2144}
2145
Chris Lattner3f32d692011-07-12 06:52:18 +00002146static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00002147EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00002148 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002149 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00002150 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00002151 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00002152}
2153
Alexey Bataev97720002014-11-11 04:05:39 +00002154static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00002155 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2156 llvm::Type *RealVarTy, SourceLocation Loc) {
2157 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2158 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002159 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2160 return CGF.MakeAddrLValue(Addr, T, BaseInfo);
John McCall7f416cc2015-09-08 08:05:57 +00002161}
2162
2163Address CodeGenFunction::EmitLoadOfReference(Address Addr,
2164 const ReferenceType *RefTy,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002165 LValueBaseInfo *BaseInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002166 llvm::Value *Ptr = Builder.CreateLoad(Addr);
2167 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002168 BaseInfo, /*forPointee*/ true));
John McCall7f416cc2015-09-08 08:05:57 +00002169}
2170
2171LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
2172 const ReferenceType *RefTy) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002173 LValueBaseInfo BaseInfo;
2174 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &BaseInfo);
2175 return MakeAddrLValue(Addr, RefTy->getPointeeType(), BaseInfo);
Alexey Bataev97720002014-11-11 04:05:39 +00002176}
2177
Alexey Bataev31300ed2016-02-04 11:27:03 +00002178Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2179 const PointerType *PtrTy,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002180 LValueBaseInfo *BaseInfo) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00002181 llvm::Value *Addr = Builder.CreateLoad(Ptr);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002182 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(),
2183 BaseInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00002184 /*forPointeeType=*/true));
2185}
2186
2187LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2188 const PointerType *PtrTy) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002189 LValueBaseInfo BaseInfo;
2190 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo);
2191 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00002192}
2193
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002194static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2195 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00002196 QualType T = E->getType();
2197
2198 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00002199 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2200 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00002201 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2202
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002203 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002204 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2205 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00002206 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00002207 Address Addr(V, Alignment);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002208 LValue LV;
Alexey Bataev97720002014-11-11 04:05:39 +00002209 // Emit reference to the private copy of the variable if it is an OpenMP
2210 // threadprivate variable.
2211 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00002212 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002213 E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00002214 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2215 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002216 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002217 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2218 LV = CGF.MakeAddrLValue(Addr, T, BaseInfo);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002219 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002220 setObjCGCLValueClass(CGF.getContext(), E, LV);
2221 return LV;
2222}
2223
John McCallb92ab1a2016-10-26 23:46:34 +00002224static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2225 const FunctionDecl *FD) {
2226 if (FD->hasAttr<WeakRefAttr>()) {
2227 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2228 return aliasee.getPointer();
2229 }
2230
2231 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002232 if (!FD->hasPrototype()) {
2233 if (const FunctionProtoType *Proto =
2234 FD->getType()->getAs<FunctionProtoType>()) {
2235 // Ugly case: for a K&R-style definition, the type of the definition
2236 // isn't the same as the type of a use. Correct for this with a
2237 // bitcast.
2238 QualType NoProtoType =
John McCallb92ab1a2016-10-26 23:46:34 +00002239 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2240 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2241 V = llvm::ConstantExpr::getBitCast(V,
2242 CGM.getTypes().ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002243 }
2244 }
John McCallb92ab1a2016-10-26 23:46:34 +00002245 return V;
2246}
2247
2248static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2249 const Expr *E, const FunctionDecl *FD) {
2250 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
Eli Friedmana0544d62011-12-03 04:14:32 +00002251 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002252 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2253 return CGF.MakeAddrLValue(V, E->getType(), Alignment, BaseInfo);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002254}
2255
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00002256static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2257 llvm::Value *ThisValue) {
2258 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2259 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2260 return CGF.EmitLValueForField(LV, FD);
2261}
2262
Renato Golin230c5eb2014-05-19 18:15:42 +00002263/// Named Registers are named metadata pointing to the register name
2264/// which will be read from/written to as an argument to the intrinsic
2265/// @llvm.read/write_register.
2266/// So far, only the name is being passed down, but other options such as
2267/// register type, allocation type or even optimization options could be
2268/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002269static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002270 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002271 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002272 assert(Asm->getLabel().size() < 64-Name.size() &&
2273 "Register name too big");
2274 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002275 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002276 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002277 if (M->getNumOperands() == 0) {
2278 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2279 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002280 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002281 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2282 }
John McCall7f416cc2015-09-08 08:05:57 +00002283
2284 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2285
2286 llvm::Value *Ptr =
2287 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2288 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002289}
2290
Chris Lattnerd7f58862007-06-02 05:24:33 +00002291LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002292 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002293 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002294
Renato Goline7b3d5d2014-05-27 16:46:27 +00002295 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2296 // Global Named registers access via intrinsics only
2297 if (VD->getStorageClass() == SC_Register &&
2298 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002299 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002300
Renato Goline7b3d5d2014-05-27 16:46:27 +00002301 // A DeclRefExpr for a reference initialized by a constant expression can
2302 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002303 const Expr *Init = VD->getAnyInitializer(VD);
2304 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2305 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002306 VD->checkInitIsICE() &&
2307 // Do not emit if it is private OpenMP variable.
2308 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2309 LocalDeclMap.count(VD))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002310 llvm::Constant *Val =
John McCallde0fe072017-08-15 21:42:52 +00002311 ConstantEmitter(*this).emitAbstract(E->getLocation(),
2312 *VD->evaluateValue(),
2313 VD->getType());
Richard Smith5a1104b2012-10-20 01:38:33 +00002314 assert(Val && "failed to emit reference constant expression");
2315 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002316
2317 // Should we be using the alignment of the constant pointer we emitted?
2318 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2319 /*pointee*/ true);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002320 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2321 return MakeAddrLValue(Address(Val, Alignment), T, BaseInfo);
Richard Smith5a1104b2012-10-20 01:38:33 +00002322 }
David Majnemer602cfe72015-01-01 09:49:44 +00002323
2324 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002325 if (E->refersToEnclosingVariableOrCapture()) {
Alexey Bataev6a71f362017-08-22 17:54:52 +00002326 VD = VD->getCanonicalDecl();
David Majnemer602cfe72015-01-01 09:49:44 +00002327 if (auto *FD = LambdaCaptureFields.lookup(VD))
2328 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2329 else if (CapturedStmtInfo) {
Alexey Bataevac5eabb2016-11-07 11:16:04 +00002330 auto I = LocalDeclMap.find(VD);
2331 if (I != LocalDeclMap.end()) {
2332 if (auto RefTy = VD->getType()->getAs<ReferenceType>())
2333 return EmitLoadOfReferenceLValue(I->second, RefTy);
2334 return MakeAddrLValue(I->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002335 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002336 LValue CapLVal =
2337 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2338 CapturedStmtInfo->getContextValue());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002339 bool MayAlias = CapLVal.getBaseInfo().getMayAlias();
Alexey Bataevc71a4092015-09-11 10:29:41 +00002340 return MakeAddrLValue(
2341 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002342 CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl, MayAlias));
David Majnemer602cfe72015-01-01 09:49:44 +00002343 }
John McCall7f416cc2015-09-08 08:05:57 +00002344
David Majnemer602cfe72015-01-01 09:49:44 +00002345 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002346 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002347 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2348 return MakeAddrLValue(addr, T, BaseInfo);
David Majnemer602cfe72015-01-01 09:49:44 +00002349 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002350 }
2351
Eli Friedman5720e342012-01-21 04:52:58 +00002352 // FIXME: We should be able to assert this for FunctionDecls as well!
2353 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2354 // those with a valid source location.
2355 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2356 !E->getLocation().isValid()) &&
2357 "Should not use decl without marking it used!");
2358
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002359 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002360 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002361 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002362 return MakeAddrLValue(Aliasee, T,
2363 LValueBaseInfo(AlignmentSource::Decl, false));
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002364 }
2365
Renato Goline7b3d5d2014-05-27 16:46:27 +00002366 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002367 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002368 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002369 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002370
John McCall7f416cc2015-09-08 08:05:57 +00002371 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002372
John McCall7f416cc2015-09-08 08:05:57 +00002373 // The variable should generally be present in the local decl map.
2374 auto iter = LocalDeclMap.find(VD);
2375 if (iter != LocalDeclMap.end()) {
2376 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002377
John McCall7f416cc2015-09-08 08:05:57 +00002378 // Otherwise, it might be static local we haven't emitted yet for
2379 // some reason; most likely, because it's in an outer function.
2380 } else if (VD->isStaticLocal()) {
2381 addr = Address(CGM.getOrCreateStaticVarDecl(
2382 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2383 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002384
John McCall7f416cc2015-09-08 08:05:57 +00002385 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002386 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002387 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2388 }
2389
2390
2391 // Check for OpenMP threadprivate variables.
2392 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2393 return EmitThreadPrivateVarDeclLValue(
2394 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2395 E->getExprLoc());
2396 }
2397
2398 // Drill into block byref variables.
2399 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2400 if (isBlockByref) {
2401 addr = emitBlockByrefAddress(addr, VD);
2402 }
2403
2404 // Drill into reference types.
2405 LValue LV;
2406 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2407 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2408 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002409 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2410 LV = MakeAddrLValue(addr, T, BaseInfo);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002411 }
Chris Lattner3f32d692011-07-12 06:52:18 +00002412
John McCallcdda29c2013-03-13 03:10:54 +00002413 bool isLocalStorage = VD->hasLocalStorage();
2414
2415 bool NonGCable = isLocalStorage &&
2416 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002417 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002418 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002419 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002420 LV.setNonGC(true);
2421 }
John McCallcdda29c2013-03-13 03:10:54 +00002422
2423 bool isImpreciseLifetime =
2424 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2425 if (isImpreciseLifetime)
2426 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002427 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002428 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002429 }
John McCallf3a88602011-02-03 08:15:49 +00002430
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002431 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002432 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002433
Richard Smithda383632016-08-15 01:33:41 +00002434 // FIXME: While we're emitting a binding from an enclosing scope, all other
2435 // DeclRefExprs we see should be implicitly treated as if they also refer to
2436 // an enclosing scope.
2437 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2438 return EmitLValue(BD->getBinding());
2439
David Blaikie83d382b2011-09-23 05:06:16 +00002440 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002441}
Chris Lattnere47e4402007-06-01 18:02:12 +00002442
Chris Lattner8394d792007-06-05 20:53:16 +00002443LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2444 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002445 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002446 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002447
Chris Lattner0f398c42008-07-26 22:37:01 +00002448 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002449 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002450 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002451 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002452 QualType T = E->getSubExpr()->getType()->getPointeeType();
2453 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002454
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002455 LValueBaseInfo BaseInfo;
2456 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo);
2457 LValue LV = MakeAddrLValue(Addr, T, BaseInfo);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002458 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002459
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002460 // We should not generate __weak write barrier on indirect reference
2461 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2462 // But, we continue to generate __strong write barrier on indirect write
2463 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002464 if (getLangOpts().ObjC1 &&
2465 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002466 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002467 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002468 return LV;
2469 }
John McCalle3027922010-08-25 11:45:40 +00002470 case UO_Real:
2471 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002472 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002473 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002474
Richard Smith0b6b8e42012-02-18 20:53:32 +00002475 // __real is valid on scalars. This is a faster way of testing that.
2476 // __imag can only produce an rvalue on scalars.
2477 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002478 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002479 assert(E->getSubExpr()->getType()->isArithmeticType());
2480 return LV;
2481 }
2482
Alexey Bataev611b0a12016-11-07 18:15:02 +00002483 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
John McCalla2342eb2010-12-05 02:00:02 +00002484
John McCall7f416cc2015-09-08 08:05:57 +00002485 Address Component =
2486 (E->getOpcode() == UO_Real
2487 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2488 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002489 LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo());
Alexey Bataev611b0a12016-11-07 18:15:02 +00002490 ElemLV.getQuals().addQualifiers(LV.getQuals());
2491 return ElemLV;
Chris Lattner595db862007-10-30 22:53:42 +00002492 }
John McCalle3027922010-08-25 11:45:40 +00002493 case UO_PreInc:
2494 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002495 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002496 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002497
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002498 if (E->getType()->isAnyComplexType())
2499 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2500 else
2501 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2502 return LV;
2503 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002504 }
Chris Lattner8394d792007-06-05 20:53:16 +00002505}
2506
Chris Lattner4347e3692007-06-06 04:54:52 +00002507LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002508 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002509 E->getType(),
2510 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattner4347e3692007-06-06 04:54:52 +00002511}
2512
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002513LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002514 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002515 E->getType(),
2516 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002517}
2518
Mike Stump4a3999f2009-09-09 13:00:44 +00002519LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002520 auto SL = E->getFunctionName();
2521 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2522 StringRef FnName = CurFn->getName();
2523 if (FnName.startswith("\01"))
2524 FnName = FnName.substr(1);
2525 StringRef NameItems[] = {
2526 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2527 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002528 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002529 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2530 std::string Name = SL->getString();
2531 if (!Name.empty()) {
2532 unsigned Discriminator =
2533 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2534 if (Discriminator)
2535 Name += "_" + Twine(Discriminator + 1).str();
2536 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002537 return MakeAddrLValue(C, E->getType(), BaseInfo);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002538 } else {
2539 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002540 return MakeAddrLValue(C, E->getType(), BaseInfo);
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002541 }
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002542 }
Alexey Bataevec474782014-10-09 08:45:04 +00002543 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00002544 return MakeAddrLValue(C, E->getType(), BaseInfo);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002545}
2546
Richard Smithe30752c2012-10-09 19:52:38 +00002547/// Emit a type description suitable for use by a runtime sanitizer library. The
2548/// format of a type descriptor is
2549///
2550/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002551/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002552/// \endcode
2553///
Richard Smith683398a2012-10-09 23:55:19 +00002554/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2555/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002556llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002557 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002558 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002559 return C;
2560
Richard Smithe30752c2012-10-09 19:52:38 +00002561 uint16_t TypeKind = -1;
2562 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002563
Richard Smithe30752c2012-10-09 19:52:38 +00002564 if (T->isIntegerType()) {
2565 TypeKind = 0;
2566 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002567 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002568 } else if (T->isFloatingType()) {
2569 TypeKind = 1;
2570 TypeInfo = getContext().getTypeSize(T);
2571 }
2572
2573 // Format the type name as if for a diagnostic, including quotes and
2574 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002575 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002576 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2577 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002578 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002579 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002580
2581 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002582 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2583 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002584 };
2585 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2586
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002587 auto *GV = new llvm::GlobalVariable(
2588 CGM.getModule(), Descriptor->getType(),
2589 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002590 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002591 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002592
2593 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002594 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002595
Richard Smithe30752c2012-10-09 19:52:38 +00002596 return GV;
2597}
2598
2599llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2600 llvm::Type *TargetTy = IntPtrTy;
2601
Richard Smith48366f72013-03-22 00:47:07 +00002602 // Floating-point types which fit into intptr_t are bitcast to integers
2603 // and then passed directly (after zero-extension, if necessary).
2604 if (V->getType()->isFloatingPointTy()) {
2605 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2606 if (Bits <= TargetTy->getIntegerBitWidth())
2607 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2608 Bits));
2609 }
2610
Richard Smithe30752c2012-10-09 19:52:38 +00002611 // Integers which fit in intptr_t are zero-extended and passed directly.
2612 if (V->getType()->isIntegerTy() &&
2613 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2614 return Builder.CreateZExt(V, TargetTy);
2615
2616 // Pointers are passed directly, everything else is passed by address.
2617 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002618 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002619 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002620 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002621 }
2622 return Builder.CreatePtrToInt(V, TargetTy);
2623}
2624
2625/// \brief Emit a representation of a SourceLocation for passing to a handler
2626/// in a sanitizer runtime library. The format for this data is:
2627/// \code
2628/// struct SourceLocation {
2629/// const char *Filename;
2630/// int32_t Line, Column;
2631/// };
2632/// \endcode
2633/// For an invalid SourceLocation, the Filename pointer is null.
2634llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002635 llvm::Constant *Filename;
2636 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002637
Alexey Samsonov6c124142014-07-18 17:50:06 +00002638 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2639 if (PLoc.isValid()) {
Filipe Cabecinhasab731f72016-05-12 16:51:36 +00002640 StringRef FilenameString = PLoc.getFilename();
2641
2642 int PathComponentsToStrip =
2643 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2644 if (PathComponentsToStrip < 0) {
2645 assert(PathComponentsToStrip != INT_MIN);
2646 int PathComponentsToKeep = -PathComponentsToStrip;
2647 auto I = llvm::sys::path::rbegin(FilenameString);
2648 auto E = llvm::sys::path::rend(FilenameString);
2649 while (I != E && --PathComponentsToKeep)
2650 ++I;
2651
2652 FilenameString = FilenameString.substr(I - E);
2653 } else if (PathComponentsToStrip > 0) {
2654 auto I = llvm::sys::path::begin(FilenameString);
2655 auto E = llvm::sys::path::end(FilenameString);
2656 while (I != E && PathComponentsToStrip--)
2657 ++I;
2658
2659 if (I != E)
2660 FilenameString =
2661 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2662 else
2663 FilenameString = llvm::sys::path::filename(FilenameString);
2664 }
2665
2666 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002667 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2668 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2669 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002670 Line = PLoc.getLine();
2671 Column = PLoc.getColumn();
2672 } else {
2673 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2674 Line = Column = 0;
2675 }
2676
2677 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2678 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002679
2680 return llvm::ConstantStruct::getAnon(Data);
2681}
2682
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002683namespace {
2684/// \brief Specify under what conditions this check can be recovered
2685enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002686 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002687 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002688 /// Check supports recovering, runtime has both fatal (noreturn) and
2689 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002690 Recoverable,
2691 /// Runtime conditionally aborts, always need to support recovery.
2692 AlwaysRecoverable
2693};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002694}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002695
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002696static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2697 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002698 switch (Kind) {
2699 case SanitizerKind::Vptr:
2700 return CheckRecoverableKind::AlwaysRecoverable;
2701 case SanitizerKind::Return:
2702 case SanitizerKind::Unreachable:
2703 return CheckRecoverableKind::Unrecoverable;
2704 default:
2705 return CheckRecoverableKind::Recoverable;
2706 }
2707}
2708
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002709namespace {
2710struct SanitizerHandlerInfo {
2711 char const *const Name;
2712 unsigned Version;
2713};
Saleem Abdulrasoolca6e2b42016-12-13 03:27:35 +00002714}
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002715
2716const SanitizerHandlerInfo SanitizerHandlers[] = {
2717#define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2718 LIST_SANITIZER_CHECKS
2719#undef SANITIZER_CHECK
2720};
2721
Alexey Samsonov88459522015-01-12 22:39:12 +00002722static void emitCheckHandlerCall(CodeGenFunction &CGF,
2723 llvm::FunctionType *FnType,
2724 ArrayRef<llvm::Value *> FnArgs,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002725 SanitizerHandler CheckHandler,
Alexey Samsonov88459522015-01-12 22:39:12 +00002726 CheckRecoverableKind RecoverKind, bool IsFatal,
2727 llvm::BasicBlock *ContBB) {
2728 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2729 bool NeedsAbortSuffix =
2730 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002731 bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002732 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2733 const StringRef CheckName = CheckInfo.Name;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002734 std::string FnName = "__ubsan_handle_" + CheckName.str();
2735 if (CheckInfo.Version && !MinimalRuntime)
2736 FnName += "_v" + llvm::utostr(CheckInfo.Version);
2737 if (MinimalRuntime)
2738 FnName += "_minimal";
2739 if (NeedsAbortSuffix)
2740 FnName += "_abort";
Alexey Samsonov88459522015-01-12 22:39:12 +00002741 bool MayReturn =
2742 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2743
2744 llvm::AttrBuilder B;
2745 if (!MayReturn) {
2746 B.addAttribute(llvm::Attribute::NoReturn)
2747 .addAttribute(llvm::Attribute::NoUnwind);
2748 }
2749 B.addAttribute(llvm::Attribute::UWTable);
2750
2751 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2752 FnType, FnName,
Reid Klecknerde864822017-03-21 16:57:30 +00002753 llvm::AttributeList::get(CGF.getLLVMContext(),
2754 llvm::AttributeList::FunctionIndex, B),
Saleem Abdulrasool05b8fde2016-12-15 16:30:20 +00002755 /*Local=*/true);
Alexey Samsonov88459522015-01-12 22:39:12 +00002756 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2757 if (!MayReturn) {
2758 HandlerCall->setDoesNotReturn();
2759 CGF.Builder.CreateUnreachable();
2760 } else {
2761 CGF.Builder.CreateBr(ContBB);
2762 }
2763}
2764
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002765void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002766 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002767 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002768 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002769 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002770 assert(Checked.size() > 0);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002771 assert(CheckHandler >= 0 &&
2772 CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers));
2773 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
Alexey Samsonov88459522015-01-12 22:39:12 +00002774
2775 llvm::Value *FatalCond = nullptr;
2776 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002777 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002778 for (int i = 0, n = Checked.size(); i < n; ++i) {
2779 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002780 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002781 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002782 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2783 ? TrapCond
2784 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2785 ? RecoverableCond
2786 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002787 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2788 }
2789
Peter Collingbourne9881b782015-06-18 23:59:22 +00002790 if (TrapCond)
2791 EmitTrapCheck(TrapCond);
2792 if (!FatalCond && !RecoverableCond)
2793 return;
2794
Alexey Samsonov88459522015-01-12 22:39:12 +00002795 llvm::Value *JointCond;
2796 if (FatalCond && RecoverableCond)
2797 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2798 else
2799 JointCond = FatalCond ? FatalCond : RecoverableCond;
2800 assert(JointCond);
2801
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002802 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002803 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002804#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002805 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002806 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002807 "All recoverable kinds in a single check must be same!");
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002808 assert(SanOpts.has(Checked[i].second));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002809 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002810#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002811
Richard Smith4d1458e2012-09-08 02:08:36 +00002812 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002813 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2814 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002815 // Give hint that we very much don't expect to execute the handler
2816 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2817 llvm::MDBuilder MDHelper(getLLVMContext());
2818 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2819 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002820 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002821
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002822 // Handler functions take an i8* pointing to the (handler-specific) static
2823 // information block, followed by a sequence of intptr_t arguments
2824 // representing operand values.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002825 SmallVector<llvm::Value *, 4> Args;
2826 SmallVector<llvm::Type *, 4> ArgTypes;
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002827 if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
2828 Args.reserve(DynamicArgs.size() + 1);
2829 ArgTypes.reserve(DynamicArgs.size() + 1);
Richard Smithe30752c2012-10-09 19:52:38 +00002830
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002831 // Emit handler arguments and create handler function type.
2832 if (!StaticArgs.empty()) {
2833 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2834 auto *InfoPtr =
2835 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2836 llvm::GlobalVariable::PrivateLinkage, Info);
2837 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2838 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2839 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2840 ArgTypes.push_back(Int8PtrTy);
2841 }
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002842
Evgeniy Stepanov6d2b6f02017-08-29 20:03:51 +00002843 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2844 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2845 ArgTypes.push_back(IntPtrTy);
2846 }
Richard Smithe30752c2012-10-09 19:52:38 +00002847 }
2848
2849 llvm::FunctionType *FnType =
2850 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002851
Alexey Samsonov88459522015-01-12 22:39:12 +00002852 if (!FatalCond || !RecoverableCond) {
2853 // Simple case: we need to generate a single handler call, either
2854 // fatal, or non-fatal.
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002855 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
Alexey Samsonov88459522015-01-12 22:39:12 +00002856 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002857 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002858 // Emit two handler calls: first one for set of unrecoverable checks,
2859 // another one for recoverable.
2860 llvm::BasicBlock *NonFatalHandlerBB =
2861 createBasicBlock("non_fatal." + CheckName);
2862 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2863 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2864 EmitBlock(FatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002865 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
Alexey Samsonov88459522015-01-12 22:39:12 +00002866 NonFatalHandlerBB);
2867 EmitBlock(NonFatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002868 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
Alexey Samsonov88459522015-01-12 22:39:12 +00002869 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002870 }
Richard Smithe30752c2012-10-09 19:52:38 +00002871
Richard Smith4d1458e2012-09-08 02:08:36 +00002872 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002873}
2874
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002875void CodeGenFunction::EmitCfiSlowPathCheck(
2876 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2877 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002878 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2879
2880 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2881 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2882
2883 llvm::MDBuilder MDHelper(getLLVMContext());
2884 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2885 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2886
2887 EmitBlock(CheckBB);
2888
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002889 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2890
2891 llvm::CallInst *CheckCall;
2892 if (WithDiag) {
2893 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2894 auto *InfoPtr =
2895 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2896 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002897 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002898 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2899
2900 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2901 "__cfi_slowpath_diag",
2902 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2903 false));
2904 CheckCall = Builder.CreateCall(
2905 SlowPathDiagFn,
2906 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2907 } else {
2908 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2909 "__cfi_slowpath",
2910 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2911 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2912 }
2913
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002914 CheckCall->setDoesNotThrow();
2915
2916 EmitBlock(Cont);
2917}
2918
Evgeniy Stepanov1a8030e2017-04-07 23:00:38 +00002919// Emit a stub for __cfi_check function so that the linker knows about this
2920// symbol in LTO mode.
2921void CodeGenFunction::EmitCfiCheckStub() {
2922 llvm::Module *M = &CGM.getModule();
2923 auto &Ctx = M->getContext();
2924 llvm::Function *F = llvm::Function::Create(
2925 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
2926 llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
2927 llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
2928 // FIXME: consider emitting an intrinsic call like
2929 // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
2930 // which can be lowered in CrossDSOCFI pass to the actual contents of
2931 // __cfi_check. This would allow inlining of __cfi_check calls.
2932 llvm::CallInst::Create(
2933 llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
2934 llvm::ReturnInst::Create(Ctx, nullptr, BB);
2935}
2936
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002937// This function is basically a switch over the CFI failure kind, which is
2938// extracted from CFICheckFailData (1st function argument). Each case is either
2939// llvm.trap or a call to one of the two runtime handlers, based on
2940// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2941// failure kind) traps, but this should really never happen. CFICheckFailData
2942// can be nullptr if the calling module has -fsanitize-trap behavior for this
2943// check kind; in this case __cfi_check_fail traps as well.
2944void CodeGenFunction::EmitCfiCheckFail() {
2945 SanitizerScope SanScope(this);
2946 FunctionArgList Args;
Alexey Bataev56223232017-06-09 13:40:18 +00002947 ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
2948 ImplicitParamDecl::Other);
2949 ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
2950 ImplicitParamDecl::Other);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002951 Args.push_back(&ArgData);
2952 Args.push_back(&ArgAddr);
2953
John McCallc56a8b32016-03-11 04:30:31 +00002954 const CGFunctionInfo &FI =
2955 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002956
2957 llvm::Function *F = llvm::Function::Create(
2958 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2959 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2960 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2961
2962 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2963 SourceLocation());
2964
2965 llvm::Value *Data =
2966 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2967 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2968 llvm::Value *Addr =
2969 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2970 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2971
2972 // Data == nullptr means the calling module has trap behaviour for this check.
2973 llvm::Value *DataIsNotNullPtr =
2974 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2975 EmitTrapCheck(DataIsNotNullPtr);
2976
2977 llvm::StructType *SourceLocationTy =
Serge Guelton1d993272017-05-09 19:31:30 +00002978 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002979 llvm::StructType *CfiCheckFailDataTy =
Serge Guelton1d993272017-05-09 19:31:30 +00002980 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002981
2982 llvm::Value *V = Builder.CreateConstGEP2_32(
2983 CfiCheckFailDataTy,
2984 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2985 0);
2986 Address CheckKindAddr(V, getIntAlign());
2987 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2988
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002989 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2990 CGM.getLLVMContext(),
2991 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2992 llvm::Value *ValidVtable = Builder.CreateZExt(
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002993 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002994 {Addr, AllVtables}),
2995 IntPtrTy);
2996
Evgeniy Stepanov4d3b0872016-01-25 23:45:37 +00002997 const std::pair<int, SanitizerMask> CheckKinds[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002998 {CFITCK_VCall, SanitizerKind::CFIVCall},
2999 {CFITCK_NVCall, SanitizerKind::CFINVCall},
3000 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
3001 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
3002 {CFITCK_ICall, SanitizerKind::CFIICall}};
3003
3004 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
3005 for (auto CheckKindMaskPair : CheckKinds) {
3006 int Kind = CheckKindMaskPair.first;
3007 SanitizerMask Mask = CheckKindMaskPair.second;
3008 llvm::Value *Cond =
3009 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00003010 if (CGM.getLangOpts().Sanitize.has(Mask))
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00003011 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00003012 {Data, Addr, ValidVtable});
3013 else
3014 EmitTrapCheck(Cond);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00003015 }
3016
3017 FinishFunction();
3018 // The only reference to this function will be created during LTO link.
3019 // Make sure it survives until then.
3020 CGM.addUsedGlobal(F);
3021}
3022
Chad Rosierae229d52013-01-29 23:31:22 +00003023void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00003024 llvm::BasicBlock *Cont = createBasicBlock("cont");
3025
3026 // If we're optimizing, collapse all calls to trap down to just one per
3027 // function to save on code size.
3028 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
3029 TrapBB = createBasicBlock("trap");
3030 Builder.CreateCondBr(Checked, Cont, TrapBB);
3031 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003032 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00003033 TrapCall->setDoesNotReturn();
3034 TrapCall->setDoesNotThrow();
3035 Builder.CreateUnreachable();
3036 } else {
3037 Builder.CreateCondBr(Checked, Cont, TrapBB);
3038 }
3039
3040 EmitBlock(Cont);
3041}
3042
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003043llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00003044 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003045
Amaury Sechet21f51b32016-09-09 04:42:49 +00003046 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3047 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3048 CGM.getCodeGenOpts().TrapFuncName);
Reid Klecknerde864822017-03-21 16:57:30 +00003049 TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
Amaury Sechet21f51b32016-09-09 04:42:49 +00003050 }
Akira Hatanaka85365cd2015-07-02 22:15:41 +00003051
3052 return TrapCall;
3053}
3054
John McCall7f416cc2015-09-08 08:05:57 +00003055Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003056 LValueBaseInfo *BaseInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00003057 assert(E->getType()->isArrayType() &&
3058 "Array to pointer decay must have array source type!");
3059
3060 // Expressions of array type can't be bitfields or vector elements.
3061 LValue LV = EmitLValue(E);
3062 Address Addr = LV.getAddress();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003063 if (BaseInfo) *BaseInfo = LV.getBaseInfo();
John McCall7f416cc2015-09-08 08:05:57 +00003064
3065 // If the array type was an incomplete type, we need to make sure
3066 // the decay ends up being the right type.
3067 llvm::Type *NewTy = ConvertType(E->getType());
3068 Addr = Builder.CreateElementBitCast(Addr, NewTy);
3069
3070 // Note that VLA pointers are always decayed, so we don't need to do
3071 // anything here.
3072 if (!E->getType()->isVariableArrayType()) {
3073 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3074 "Expected pointer to array");
3075 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
3076 }
3077
3078 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
3079 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
3080}
3081
Chris Lattner6c5abe82010-06-26 23:03:20 +00003082/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
3083/// array to pointer, return the array subexpression.
3084static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
3085 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003086 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00003087 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00003088 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00003089
Chris Lattner6c5abe82010-06-26 23:03:20 +00003090 // If this is a decay from variable width array, bail out.
3091 const Expr *SubExpr = CE->getSubExpr();
3092 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00003093 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00003094
Chris Lattner6c5abe82010-06-26 23:03:20 +00003095 return SubExpr;
3096}
3097
John McCall7f416cc2015-09-08 08:05:57 +00003098static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3099 llvm::Value *ptr,
3100 ArrayRef<llvm::Value*> indices,
3101 bool inbounds,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003102 bool signedIndices,
Vedant Kumara125eb52017-06-01 19:22:18 +00003103 SourceLocation loc,
John McCall7f416cc2015-09-08 08:05:57 +00003104 const llvm::Twine &name = "arrayidx") {
3105 if (inbounds) {
Vedant Kumar175b6d12017-07-13 20:55:26 +00003106 return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices,
3107 CodeGenFunction::NotSubtraction, loc,
3108 name);
John McCall7f416cc2015-09-08 08:05:57 +00003109 } else {
3110 return CGF.Builder.CreateGEP(ptr, indices, name);
3111 }
3112}
3113
3114static CharUnits getArrayElementAlign(CharUnits arrayAlign,
3115 llvm::Value *idx,
3116 CharUnits eltSize) {
3117 // If we have a constant index, we can use the exact offset of the
3118 // element we're accessing.
3119 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3120 CharUnits offset = constantIdx->getZExtValue() * eltSize;
3121 return arrayAlign.alignmentAtOffset(offset);
3122
3123 // Otherwise, use the worst-case alignment for any element.
3124 } else {
3125 return arrayAlign.alignmentOfArrayElement(eltSize);
3126 }
3127}
3128
3129static QualType getFixedSizeElementType(const ASTContext &ctx,
3130 const VariableArrayType *vla) {
3131 QualType eltType;
3132 do {
3133 eltType = vla->getElementType();
3134 } while ((vla = ctx.getAsVariableArrayType(eltType)));
3135 return eltType;
3136}
3137
3138static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
Vedant Kumara125eb52017-06-01 19:22:18 +00003139 ArrayRef<llvm::Value *> indices,
John McCall7f416cc2015-09-08 08:05:57 +00003140 QualType eltType, bool inbounds,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003141 bool signedIndices, SourceLocation loc,
John McCall7f416cc2015-09-08 08:05:57 +00003142 const llvm::Twine &name = "arrayidx") {
3143 // All the indices except that last must be zero.
3144#ifndef NDEBUG
3145 for (auto idx : indices.drop_back())
3146 assert(isa<llvm::ConstantInt>(idx) &&
3147 cast<llvm::ConstantInt>(idx)->isZero());
3148#endif
3149
3150 // Determine the element size of the statically-sized base. This is
3151 // the thing that the indices are expressed in terms of.
3152 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3153 eltType = getFixedSizeElementType(CGF.getContext(), vla);
3154 }
3155
3156 // We can use that to compute the best alignment of the element.
3157 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3158 CharUnits eltAlign =
3159 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3160
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003161 llvm::Value *eltPtr = emitArraySubscriptGEP(
3162 CGF, addr.getPointer(), indices, inbounds, signedIndices, loc, name);
John McCall7f416cc2015-09-08 08:05:57 +00003163 return Address(eltPtr, eltAlign);
3164}
3165
Richard Smith539e4a72013-02-23 02:53:19 +00003166LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3167 bool Accessed) {
Richard Smith9e67b992016-09-26 23:49:47 +00003168 // The index must always be an integer, which is not an aggregate. Emit it
3169 // in lexical order (this complexity is, sadly, required by C++17).
3170 llvm::Value *IdxPre =
3171 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003172 bool SignedIndices = false;
Richard Smith40885712016-09-27 00:53:24 +00003173 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
Richard Smith9e67b992016-09-26 23:49:47 +00003174 auto *Idx = IdxPre;
3175 if (E->getLHS() != E->getIdx()) {
3176 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3177 Idx = EmitScalarExpr(E->getIdx());
3178 }
Eli Friedman07bbeca2009-06-06 19:09:26 +00003179
Richard Smith9e67b992016-09-26 23:49:47 +00003180 QualType IdxTy = E->getIdx()->getType();
3181 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003182 SignedIndices |= IdxSigned;
Richard Smith9e67b992016-09-26 23:49:47 +00003183
3184 if (SanOpts.has(SanitizerKind::ArrayBounds))
3185 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3186
3187 // Extend or truncate the index type to 32 or 64-bits.
3188 if (Promote && Idx->getType() != IntPtrTy)
3189 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3190
3191 return Idx;
3192 };
3193 IdxPre = nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +00003194
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003195 // If the base is a vector type, then we are forming a vector element lvalue
3196 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003197 if (E->getBase()->getType()->isVectorType() &&
3198 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003199 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00003200 LValue LHS = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003201 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
Ted Kremenekc81614d2007-08-20 16:18:38 +00003202 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Eli Friedman327944b2008-06-13 23:01:12 +00003203 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
John McCall7f416cc2015-09-08 08:05:57 +00003204 E->getBase()->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003205 LHS.getBaseInfo());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00003206 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003207
John McCall7f416cc2015-09-08 08:05:57 +00003208 // All the other cases basically behave like simple offsetting.
3209
John McCall7f416cc2015-09-08 08:05:57 +00003210 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003211 if (isa<ExtVectorElementExpr>(E->getBase())) {
3212 LValue LV = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00003213 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003214 Address Addr = EmitExtVectorElementLValue(LV);
3215
3216 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
Vedant Kumara125eb52017-06-01 19:22:18 +00003217 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003218 SignedIndices, E->getExprLoc());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003219 return MakeAddrLValue(Addr, EltType, LV.getBaseInfo());
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003220 }
John McCall7f416cc2015-09-08 08:05:57 +00003221
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003222 LValueBaseInfo BaseInfo;
John McCall7f416cc2015-09-08 08:05:57 +00003223 Address Addr = Address::invalid();
3224 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00003225 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00003226 // The base must be a pointer, which is not an aggregate. Emit
3227 // it. It needs to be emitted first in case it's what captures
3228 // the VLA bounds.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003229 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003230 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Mike Stump4a3999f2009-09-09 13:00:44 +00003231
John McCall23c29fe2011-06-24 21:55:10 +00003232 // The element count here is the total number of non-VLA elements.
3233 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00003234
John McCall77527a82011-06-25 01:32:37 +00003235 // Effectively, the multiply by the VLA size is part of the GEP.
3236 // GEP indexes are signed, and scaling an index isn't permitted to
3237 // signed-overflow, so we use the same semantics for our explicit
3238 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003239 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00003240 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003241 } else {
3242 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003243 }
John McCall7f416cc2015-09-08 08:05:57 +00003244
3245 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003246 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003247 SignedIndices, E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00003248
Chris Lattner6c5abe82010-06-26 23:03:20 +00003249 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3250 // Indexing over an interface, as in "NSString *P; P[4];"
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003251
John McCall7f416cc2015-09-08 08:05:57 +00003252 // Emit the base pointer.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003253 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003254 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3255
3256 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3257 llvm::Value *InterfaceSizeVal =
3258 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3259
3260 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
John McCall7f416cc2015-09-08 08:05:57 +00003261
3262 // We don't necessarily build correct LLVM struct types for ObjC
3263 // interfaces, so we can't rely on GEP to do this scaling
3264 // correctly, so we need to cast to i8*. FIXME: is this actually
3265 // true? A lot of other things in the fragile ABI would break...
3266 llvm::Type *OrigBaseTy = Addr.getType();
3267 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3268
3269 // Do the GEP.
3270 CharUnits EltAlign =
3271 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003272 llvm::Value *EltPtr =
3273 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false,
3274 SignedIndices, E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00003275 Addr = Address(EltPtr, EltAlign);
3276
3277 // Cast back.
3278 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00003279 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3280 // If this is A[i] where A is an array, the frontend will have decayed the
3281 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3282 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3283 // "gep x, i" here. Emit one "gep A, 0, i".
3284 assert(Array->getType()->isArrayType() &&
3285 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00003286 LValue ArrayLV;
3287 // For simple multidimensional array indexing, set the 'accessed' flag for
3288 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003289 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00003290 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3291 else
3292 ArrayLV = EmitLValue(Array);
Richard Smith9e67b992016-09-26 23:49:47 +00003293 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Craig Topper99e79272013-07-26 05:59:26 +00003294
Daniel Dunbar82634272011-04-01 00:49:43 +00003295 // Propagate the alignment from the array itself to the result.
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003296 Addr = emitArraySubscriptGEP(
3297 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3298 E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3299 E->getExprLoc());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003300 BaseInfo = ArrayLV.getBaseInfo();
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003301 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003302 // The base must be a pointer; emit it with an estimate of its alignment.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003303 Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Richard Smith9e67b992016-09-26 23:49:47 +00003304 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003305 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003306 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003307 SignedIndices, E->getExprLoc());
Anders Carlsson3d312f82008-12-21 00:11:23 +00003308 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003309
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003310 LValue LV = MakeAddrLValue(Addr, E->getType(), BaseInfo);
Mike Stump4a3999f2009-09-09 13:00:44 +00003311
John McCall7f416cc2015-09-08 08:05:57 +00003312 // TODO: Preserve/extend path TBAA metadata?
John McCall8ccfcb52009-09-24 19:53:00 +00003313
Richard Smith9c6890a2012-11-01 22:30:59 +00003314 if (getLangOpts().ObjC1 &&
3315 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00003316 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00003317 setObjCGCLValueClass(getContext(), E, LV);
3318 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00003319 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00003320}
3321
Alexey Bataev31300ed2016-02-04 11:27:03 +00003322static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003323 LValueBaseInfo &BaseInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003324 QualType BaseTy, QualType ElTy,
3325 bool IsLowerBound) {
3326 LValue BaseLVal;
3327 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3328 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3329 if (BaseTy->isArrayType()) {
3330 Address Addr = BaseLVal.getAddress();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003331 BaseInfo = BaseLVal.getBaseInfo();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003332
3333 // If the array type was an incomplete type, we need to make sure
3334 // the decay ends up being the right type.
3335 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3336 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3337
3338 // Note that VLA pointers are always decayed, so we don't need to do
3339 // anything here.
3340 if (!BaseTy->isVariableArrayType()) {
3341 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3342 "Expected pointer to array");
3343 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3344 "arraydecay");
3345 }
3346
3347 return CGF.Builder.CreateElementBitCast(Addr,
3348 CGF.ConvertTypeForMem(ElTy));
3349 }
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003350 LValueBaseInfo TypeInfo;
3351 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &TypeInfo);
3352 BaseInfo.mergeForCast(TypeInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003353 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3354 }
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003355 return CGF.EmitPointerWithAlignment(Base, &BaseInfo);
Alexey Bataev31300ed2016-02-04 11:27:03 +00003356}
3357
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003358LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3359 bool IsLowerBound) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003360 QualType BaseTy;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003361 if (auto *ASE =
3362 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
Alexey Bataev31300ed2016-02-04 11:27:03 +00003363 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003364 else
Alexey Bataev31300ed2016-02-04 11:27:03 +00003365 BaseTy = E->getBase()->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003366 QualType ResultExprTy;
3367 if (auto *AT = getContext().getAsArrayType(BaseTy))
3368 ResultExprTy = AT->getElementType();
3369 else
3370 ResultExprTy = BaseTy->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003371 llvm::Value *Idx = nullptr;
Benjamin Kramer5ff67472016-04-11 08:26:13 +00003372 if (IsLowerBound || E->getColonLoc().isInvalid()) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003373 // Requesting lower bound or upper bound, but without provided length and
3374 // without ':' symbol for the default length -> length = 1.
3375 // Idx = LowerBound ?: 0;
3376 if (auto *LowerBound = E->getLowerBound()) {
3377 Idx = Builder.CreateIntCast(
3378 EmitScalarExpr(LowerBound), IntPtrTy,
3379 LowerBound->getType()->hasSignedIntegerRepresentation());
3380 } else
3381 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3382 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003383 // Try to emit length or lower bound as constant. If this is possible, 1
3384 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3385 // IR (LB + Len) - 1.
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003386 auto &C = CGM.getContext();
3387 auto *Length = E->getLength();
3388 llvm::APSInt ConstLength;
3389 if (Length) {
3390 // Idx = LowerBound + Length - 1;
3391 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3392 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3393 Length = nullptr;
3394 }
3395 auto *LowerBound = E->getLowerBound();
3396 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3397 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3398 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3399 LowerBound = nullptr;
3400 }
3401 if (!Length)
3402 --ConstLength;
3403 else if (!LowerBound)
3404 --ConstLowerBound;
3405
3406 if (Length || LowerBound) {
3407 auto *LowerBoundVal =
3408 LowerBound
3409 ? Builder.CreateIntCast(
3410 EmitScalarExpr(LowerBound), IntPtrTy,
3411 LowerBound->getType()->hasSignedIntegerRepresentation())
3412 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3413 auto *LengthVal =
3414 Length
3415 ? Builder.CreateIntCast(
3416 EmitScalarExpr(Length), IntPtrTy,
3417 Length->getType()->hasSignedIntegerRepresentation())
3418 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3419 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3420 /*HasNUW=*/false,
3421 !getLangOpts().isSignedOverflowDefined());
3422 if (Length && LowerBound) {
3423 Idx = Builder.CreateSub(
3424 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3425 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3426 }
3427 } else
3428 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3429 } else {
3430 // Idx = ArraySize - 1;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003431 QualType ArrayTy = BaseTy->isPointerType()
3432 ? E->getBase()->IgnoreParenImpCasts()->getType()
3433 : BaseTy;
3434 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003435 Length = VAT->getSizeExpr();
3436 if (Length->isIntegerConstantExpr(ConstLength, C))
3437 Length = nullptr;
3438 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003439 auto *CAT = C.getAsConstantArrayType(ArrayTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003440 ConstLength = CAT->getSize();
3441 }
3442 if (Length) {
3443 auto *LengthVal = Builder.CreateIntCast(
3444 EmitScalarExpr(Length), IntPtrTy,
3445 Length->getType()->hasSignedIntegerRepresentation());
3446 Idx = Builder.CreateSub(
3447 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3448 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3449 } else {
3450 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3451 --ConstLength;
3452 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3453 }
3454 }
3455 }
3456 assert(Idx);
3457
Alexey Bataev31300ed2016-02-04 11:27:03 +00003458 Address EltPtr = Address::invalid();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003459 LValueBaseInfo BaseInfo;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003460 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003461 // The base must be a pointer, which is not an aggregate. Emit
3462 // it. It needs to be emitted first in case it's what captures
3463 // the VLA bounds.
3464 Address Base =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003465 emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, BaseTy,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003466 VLA->getElementType(), IsLowerBound);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003467 // The element count here is the total number of non-VLA elements.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003468 llvm::Value *NumElements = getVLASize(VLA).first;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003469
3470 // Effectively, the multiply by the VLA size is part of the GEP.
3471 // GEP indexes are signed, and scaling an index isn't permitted to
3472 // signed-overflow, so we use the same semantics for our explicit
3473 // multiply. We suppress this if overflow is not undefined behavior.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003474 if (getLangOpts().isSignedOverflowDefined())
3475 Idx = Builder.CreateMul(Idx, NumElements);
3476 else
3477 Idx = Builder.CreateNSWMul(Idx, NumElements);
3478 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
Vedant Kumara125eb52017-06-01 19:22:18 +00003479 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003480 /*SignedIndices=*/false, E->getExprLoc());
Alexey Bataev31300ed2016-02-04 11:27:03 +00003481 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3482 // If this is A[i] where A is an array, the frontend will have decayed the
3483 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3484 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3485 // "gep x, i" here. Emit one "gep A, 0, i".
3486 assert(Array->getType()->isArrayType() &&
3487 "Array to pointer decay must have array source type!");
3488 LValue ArrayLV;
3489 // For simple multidimensional array indexing, set the 'accessed' flag for
3490 // better bounds-checking of the base expression.
3491 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3492 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3493 else
3494 ArrayLV = EmitLValue(Array);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003495
Alexey Bataev31300ed2016-02-04 11:27:03 +00003496 // Propagate the alignment from the array itself to the result.
3497 EltPtr = emitArraySubscriptGEP(
3498 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
Vedant Kumara125eb52017-06-01 19:22:18 +00003499 ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003500 /*SignedIndices=*/false, E->getExprLoc());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003501 BaseInfo = ArrayLV.getBaseInfo();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003502 } else {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003503 Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
Alexey Bataev31300ed2016-02-04 11:27:03 +00003504 BaseTy, ResultExprTy, IsLowerBound);
3505 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
Vedant Kumara125eb52017-06-01 19:22:18 +00003506 !getLangOpts().isSignedOverflowDefined(),
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003507 /*SignedIndices=*/false, E->getExprLoc());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003508 }
3509
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003510 return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003511}
3512
Chris Lattner9e751ca2007-08-02 23:37:31 +00003513LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00003514EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00003515 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003516 LValue Base;
3517
3518 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00003519 if (E->isArrow()) {
3520 // If it is a pointer to a vector, emit the address and form an lvalue with
3521 // it.
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003522 LValueBaseInfo BaseInfo;
3523 Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003524 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003525 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo);
Daniel Dunbarf166a522010-08-21 03:44:13 +00003526 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00003527 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00003528 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3529 // emit the base as an lvalue.
3530 assert(E->getBase()->getType()->isVectorType());
3531 Base = EmitLValue(E->getBase());
3532 } else {
3533 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00003534 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00003535 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00003536 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00003537
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00003538 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00003539 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00003540 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00003541 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003542 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattner4e1a3232009-12-23 21:31:11 +00003543 }
John McCall1553b192011-06-16 04:16:24 +00003544
3545 QualType type =
3546 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00003547
Nate Begemand3862152008-05-13 21:03:02 +00003548 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00003549 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00003550 E->getEncodedElementAccess(Indices);
3551
3552 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00003553 llvm::Constant *CV =
3554 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00003555 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003556 Base.getBaseInfo());
Nate Begemand3862152008-05-13 21:03:02 +00003557 }
3558 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3559
3560 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003561 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00003562
Chris Lattner595ba3a2012-01-30 06:20:36 +00003563 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3564 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00003565 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00003566 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003567 Base.getBaseInfo());
Chris Lattner9e751ca2007-08-02 23:37:31 +00003568}
3569
Devang Patel30efa2e2007-10-23 20:28:39 +00003570LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Alex Lorenz6cc83172017-08-25 10:07:00 +00003571 if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
3572 EmitIgnoredExpr(E->getBase());
3573 return EmitDeclRefLValue(DRE);
3574 }
3575
Devang Pateld68df202007-10-24 22:26:28 +00003576 Expr *BaseExpr = E->getBase();
Chris Lattner4e4186b2007-12-02 18:52:07 +00003577 // 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 +00003578 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00003579 if (E->isArrow()) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003580 LValueBaseInfo BaseInfo;
3581 Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo);
Richard Smith69d0d262012-08-24 00:54:33 +00003582 QualType PtrTy = BaseExpr->getType()->getPointeeType();
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003583 SanitizerSet SkippedChecks;
Vedant Kumarffd7c882017-04-14 22:03:34 +00003584 bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
3585 if (IsBaseCXXThis)
3586 SkippedChecks.set(SanitizerKind::Alignment, true);
3587 if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
Vedant Kumar34b1fd62017-02-17 23:22:59 +00003588 SkippedChecks.set(SanitizerKind::Null, true);
3589 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
3590 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003591 BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo);
Richard Smith69d0d262012-08-24 00:54:33 +00003592 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003593 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003594
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003595 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003596 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003597 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003598 setObjCGCLValueClass(getContext(), E, LV);
3599 return LV;
3600 }
Craig Topper99e79272013-07-26 05:59:26 +00003601
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003602 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003603 return EmitFunctionDeclLValue(*this, E, FD);
3604
David Blaikie83d382b2011-09-23 05:06:16 +00003605 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003606}
Devang Patel30efa2e2007-10-23 20:28:39 +00003607
John McCalldec348f72013-05-03 07:33:41 +00003608/// Given that we are currently emitting a lambda, emit an l-value for
3609/// one of its members.
3610LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3611 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3612 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3613 QualType LambdaTagType =
3614 getContext().getTagDeclType(Field->getParent());
3615 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3616 return EmitLValueForField(LambdaLV, Field);
3617}
3618
John McCall7f416cc2015-09-08 08:05:57 +00003619/// Drill down to the storage of a field without walking into
3620/// reference types.
3621///
3622/// The resulting address doesn't necessarily have the right type.
3623static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3624 const FieldDecl *field) {
3625 const RecordDecl *rec = field->getParent();
3626
3627 unsigned idx =
3628 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3629
3630 CharUnits offset;
3631 // Adjust the alignment down to the given offset.
3632 // As a special case, if the LLVM field index is 0, we know that this
3633 // is zero.
3634 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3635 .getFieldOffset(field->getFieldIndex()) == 0) &&
3636 "LLVM field at index zero had non-zero offset?");
3637 if (idx != 0) {
3638 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3639 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3640 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3641 }
3642
3643 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3644}
3645
Piotr Padlewskic1d26062017-06-01 18:39:34 +00003646static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
3647 const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
3648 if (!RD)
3649 return false;
3650
3651 if (RD->isDynamicClass())
3652 return true;
3653
3654 for (const auto &Base : RD->bases())
3655 if (hasAnyVptr(Base.getType(), Context))
3656 return true;
3657
3658 for (const FieldDecl *Field : RD->fields())
3659 if (hasAnyVptr(Field->getType(), Context))
3660 return true;
3661
3662 return false;
3663}
3664
Eli Friedman7f1ff602012-04-16 03:54:45 +00003665LValue CodeGenFunction::EmitLValueForField(LValue base,
3666 const FieldDecl *field) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003667 LValueBaseInfo BaseInfo = base.getBaseInfo();
John McCall7f416cc2015-09-08 08:05:57 +00003668 AlignmentSource fieldAlignSource =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003669 getFieldAlignmentSource(BaseInfo.getAlignmentSource());
3670 LValueBaseInfo FieldBaseInfo(fieldAlignSource, BaseInfo.getMayAlias());
John McCall7f416cc2015-09-08 08:05:57 +00003671
Hal Finkelc9fac9e2017-09-03 17:18:25 +00003672 QualType type = field->getType();
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00003673 const RecordDecl *rec = field->getParent();
Hal Finkelc9fac9e2017-09-03 17:18:25 +00003674 if (rec->isUnion() || rec->hasAttr<MayAliasAttr>() || type->isVectorType())
Krzysztof Parzyszek5960a572017-05-25 12:55:47 +00003675 FieldBaseInfo.setMayAlias(true);
3676 bool mayAlias = FieldBaseInfo.getMayAlias();
3677
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003678 if (field->isBitField()) {
3679 const CGRecordLayout &RL =
3680 CGM.getTypes().getCGRecordLayout(field->getParent());
3681 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003682 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003683 unsigned Idx = RL.getLLVMFieldNo(field);
3684 if (Idx != 0)
3685 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003686 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3687 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003688 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003689 llvm::Type *FieldIntTy =
3690 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3691 if (Addr.getElementType() != FieldIntTy)
3692 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003693
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003694 QualType fieldType =
3695 field->getType().withCVRQualifiers(base.getVRQualifiers());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003696 return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo);
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003697 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003698
John McCall7f416cc2015-09-08 08:05:57 +00003699 Address addr = base.getAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003700 unsigned cvr = base.getVRQualifiers();
Manman Renc451e572013-04-04 21:53:22 +00003701 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
John McCall53fcbd22011-02-26 08:07:02 +00003702 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003703 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00003704 assert(!type->isReferenceType() && "union has reference member");
Manman Renc451e572013-04-04 21:53:22 +00003705 // TODO: handle path-aware TBAA for union.
3706 TBAAPath = false;
Piotr Padlewskic1d26062017-06-01 18:39:34 +00003707
3708 const auto FieldType = field->getType();
3709 if (CGM.getCodeGenOpts().StrictVTablePointers &&
3710 hasAnyVptr(FieldType, getContext()))
3711 // Because unions can easily skip invariant.barriers, we need to add
3712 // a barrier every time CXXRecord field with vptr is referenced.
3713 addr = Address(Builder.CreateInvariantGroupBarrier(addr.getPointer()),
3714 addr.getAlignment());
John McCall53fcbd22011-02-26 08:07:02 +00003715 } else {
3716 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003717 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003718
3719 // If this is a reference field, load the reference right now.
3720 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3721 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3722 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3723
Manman Renc451e572013-04-04 21:53:22 +00003724 // Loading the reference will disable path-aware TBAA.
3725 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003726 if (CGM.shouldUseTBAA()) {
Ivan A. Kosarev5c8e7592017-10-02 11:10:04 +00003727 llvm::MDNode *tbaa = mayAlias ? CGM.getTBAAMayAliasTypeInfo() :
3728 CGM.getTBAATypeInfo(type);
Manman Ren4f755de2013-10-08 00:08:49 +00003729 if (tbaa)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00003730 CGM.DecorateInstructionWithTBAA(load, tbaa);
John McCall53fcbd22011-02-26 08:07:02 +00003731 }
3732
John McCall53fcbd22011-02-26 08:07:02 +00003733 mayAlias = false;
3734 type = refType->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003735
3736 CharUnits alignment =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003737 getNaturalTypeAlignment(type, &FieldBaseInfo, /*pointee*/ true);
3738 FieldBaseInfo.setMayAlias(false);
John McCall7f416cc2015-09-08 08:05:57 +00003739 addr = Address(load, alignment);
3740
3741 // Qualifiers on the struct don't apply to the referencee, and
3742 // we'll pick up CVR from the actual type later, so reset these
3743 // additional qualifiers now.
3744 cvr = 0;
John McCall53fcbd22011-02-26 08:07:02 +00003745 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003746 }
Craig Topper99e79272013-07-26 05:59:26 +00003747
Chris Lattner13ee4f42011-07-10 05:34:54 +00003748 // Make sure that the address is pointing to the right type. This is critical
3749 // for both unions and structs. A union needs a bitcast, a struct element
3750 // will need a bitcast if the LLVM type laid out doesn't match the desired
3751 // type.
John McCall7f416cc2015-09-08 08:05:57 +00003752 addr = Builder.CreateElementBitCast(addr,
3753 CGM.getTypes().ConvertTypeForMem(type),
3754 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003755
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003756 if (field->hasAttr<AnnotateAttr>())
3757 addr = EmitFieldAnnotations(field, addr);
3758
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003759 LValue LV = MakeAddrLValue(addr, type, FieldBaseInfo);
John McCall53fcbd22011-02-26 08:07:02 +00003760 LV.getQuals().addCVRQualifiers(cvr);
Manman Renc451e572013-04-04 21:53:22 +00003761 if (TBAAPath) {
3762 const ASTRecordLayout &Layout =
3763 getContext().getASTRecordLayout(field->getParent());
3764 // Set the base type to be the base type of the base LValue and
3765 // update offset to be relative to the base type.
Manman Ren0e521662013-04-27 00:39:37 +00003766 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3767 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
Manman Renc451e572013-04-04 21:53:22 +00003768 Layout.getFieldOffset(field->getFieldIndex()) /
3769 getContext().getCharWidth());
3770 }
Daniel Dunbarf166a522010-08-21 03:44:13 +00003771
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003772 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003773 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3774 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003775
3776 // Fields of may_alias structs act like 'char' for TBAA purposes.
3777 // FIXME: this should get propagated down through anonymous structs
3778 // and unions.
Ivan A. Kosarev289574e2017-10-02 09:54:47 +00003779 if (mayAlias && LV.getTBAAAccessType())
Ivan A. Kosarev5c8e7592017-10-02 11:10:04 +00003780 LV.setTBAAAccessType(CGM.getTBAAMayAliasTypeInfo());
John McCall53fcbd22011-02-26 08:07:02 +00003781
Daniel Dunbarf166a522010-08-21 03:44:13 +00003782 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003783}
3784
Craig Topper99e79272013-07-26 05:59:26 +00003785LValue
3786CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003787 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003788 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003789
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003790 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003791 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003792
John McCall7f416cc2015-09-08 08:05:57 +00003793 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003794
John McCall7f416cc2015-09-08 08:05:57 +00003795 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003796 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003797 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003798
John McCall7f416cc2015-09-08 08:05:57 +00003799 // TODO: access-path TBAA?
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003800 LValueBaseInfo BaseInfo = Base.getBaseInfo();
3801 LValueBaseInfo FieldBaseInfo(
3802 getFieldAlignmentSource(BaseInfo.getAlignmentSource()),
3803 BaseInfo.getMayAlias());
3804 return MakeAddrLValue(V, FieldType, FieldBaseInfo);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003805}
3806
Chris Lattnerf53c0962010-09-06 00:11:41 +00003807LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003808 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
Richard Smith2d988f02011-11-22 22:48:32 +00003809 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003810 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003811 return MakeAddrLValue(GlobalPtr, E->getType(), BaseInfo);
Richard Smith2d988f02011-11-22 22:48:32 +00003812 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003813 if (E->getType()->isVariablyModifiedType())
3814 // make sure to emit the VLA size.
3815 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003816
John McCall7f416cc2015-09-08 08:05:57 +00003817 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003818 const Expr *InitExpr = E->getInitializer();
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003819 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), BaseInfo);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003820
Chad Rosier615ed1a2012-03-29 17:37:10 +00003821 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3822 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003823
3824 return Result;
3825}
3826
Richard Smithbb653bd2012-05-14 21:57:21 +00003827LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3828 if (!E->isGLValue())
3829 // Initializing an aggregate temporary in C++11: T{...}.
3830 return EmitAggExprToLValue(E);
3831
3832 // An lvalue initializer list must be initializing a reference.
Richard Smith122f88d2016-12-06 23:52:28 +00003833 assert(E->isTransparent() && "non-transparent glvalue init list");
Richard Smithbb653bd2012-05-14 21:57:21 +00003834 return EmitLValue(E->getInit(0));
3835}
3836
Richard Smithf3076ff2014-06-20 18:43:47 +00003837/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3838/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3839/// LValue is returned and the current block has been terminated.
3840static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3841 const Expr *Operand) {
3842 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3843 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3844 return None;
3845 }
3846
3847 return CGF.EmitLValue(Operand);
3848}
3849
John McCallc07a0c72011-02-17 10:25:35 +00003850LValue CodeGenFunction::
3851EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3852 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003853 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003854 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003855 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003856 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003857 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003858
Eli Friedman59954892012-01-25 05:04:17 +00003859 OpaqueValueMapping binding(*this, expr);
3860
John McCallc07a0c72011-02-17 10:25:35 +00003861 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003862 bool CondExprBool;
3863 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003864 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003865 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003866
Justin Bogneref512b92014-01-06 22:27:43 +00003867 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003868 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003869 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003870 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003871 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003872 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003873 }
3874
John McCallc07a0c72011-02-17 10:25:35 +00003875 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3876 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3877 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003878
3879 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003880 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003881
John McCall0a6bf2e2011-01-26 19:21:13 +00003882 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003883 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003884 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003885 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003886 Optional<LValue> lhs =
3887 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003888 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003889
Richard Smithf3076ff2014-06-20 18:43:47 +00003890 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003891 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003892
John McCallc07a0c72011-02-17 10:25:35 +00003893 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003894 if (lhs)
3895 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003896
John McCall0a6bf2e2011-01-26 19:21:13 +00003897 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003898 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003899 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003900 Optional<LValue> rhs =
3901 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003902 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003903 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003904 return EmitUnsupportedLValue(expr, "conditional operator");
3905 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003906
John McCallc07a0c72011-02-17 10:25:35 +00003907 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003908
Richard Smithf3076ff2014-06-20 18:43:47 +00003909 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003910 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003911 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003912 phi->addIncoming(lhs->getPointer(), lhsBlock);
3913 phi->addIncoming(rhs->getPointer(), rhsBlock);
3914 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3915 AlignmentSource alignSource =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00003916 std::max(lhs->getBaseInfo().getAlignmentSource(),
3917 rhs->getBaseInfo().getAlignmentSource());
3918 bool MayAlias = lhs->getBaseInfo().getMayAlias() ||
3919 rhs->getBaseInfo().getMayAlias();
3920 return MakeAddrLValue(result, expr->getType(),
3921 LValueBaseInfo(alignSource, MayAlias));
Richard Smithf3076ff2014-06-20 18:43:47 +00003922 } else {
3923 assert((lhs || rhs) &&
3924 "both operands of glvalue conditional are throw-expressions?");
3925 return lhs ? *lhs : *rhs;
3926 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003927}
3928
Richard Smithbb653bd2012-05-14 21:57:21 +00003929/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3930/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003931/// otherwise if a cast is needed by the code generator in an lvalue context,
3932/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003933/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003934/// are permitted with aggregate result, including noop aggregate casts, and
3935/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003936LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003937 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003938 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003939 case CK_BitCast:
3940 case CK_ArrayToPointerDecay:
3941 case CK_FunctionToPointerDecay:
3942 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003943 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003944 case CK_IntegralToPointer:
3945 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003946 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003947 case CK_VectorSplat:
3948 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00003949 case CK_BooleanToSignedIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003950 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003951 case CK_IntegralToFloating:
3952 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003953 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003954 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003955 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003956 case CK_FloatingComplexToReal:
3957 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003958 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003959 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003960 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003961 case CK_IntegralComplexToReal:
3962 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003963 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003964 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003965 case CK_DerivedToBaseMemberPointer:
3966 case CK_BaseToDerivedMemberPointer:
3967 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003968 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003969 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003970 case CK_ARCProduceObject:
3971 case CK_ARCConsumeObject:
3972 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003973 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003974 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003975 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003976 case CK_IntToOCLSampler:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003977 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3978
3979 case CK_Dependent:
3980 llvm_unreachable("dependent cast kind in IR gen!");
3981
3982 case CK_BuiltinFnToFnPtr:
3983 llvm_unreachable("builtin functions are handled elsewhere");
3984
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003985 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003986 case CK_NonAtomicToAtomic:
3987 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003988 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00003989
Anders Carlsson8a01a752011-04-11 02:03:26 +00003990 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00003991 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003992 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003993 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00003994 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00003995 }
3996
John McCalle3027922010-08-25 11:45:40 +00003997 case CK_ConstructorConversion:
3998 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00003999 case CK_CPointerToObjCPointerCast:
4000 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00004001 case CK_NoOp:
4002 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00004003 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00004004
John McCalle3027922010-08-25 11:45:40 +00004005 case CK_UncheckedDerivedToBase:
4006 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00004007 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00004008 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004009 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00004010
Anders Carlssond95f9602009-09-12 16:16:49 +00004011 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004012 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00004013
Anders Carlssond95f9602009-09-12 16:16:49 +00004014 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00004015 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00004016 This, DerivedClassDecl, E->path_begin(), E->path_end(),
4017 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00004018
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004019 return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo());
Anders Carlssond95f9602009-09-12 16:16:49 +00004020 }
John McCalle3027922010-08-25 11:45:40 +00004021 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00004022 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00004023 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00004024 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004025 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00004026
Anders Carlsson8c793172009-11-23 17:57:54 +00004027 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00004028
Anders Carlsson8c793172009-11-23 17:57:54 +00004029 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00004030 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00004031 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00004032 E->path_begin(), E->path_end(),
4033 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00004034
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004035 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
4036 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00004037 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004038 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00004039 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00004040
Peter Collingbourned2926c92015-03-14 02:42:25 +00004041 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00004042 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
4043 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00004044 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00004045
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004046 return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo());
Eli Friedman8c98dff2009-11-16 05:48:01 +00004047 }
John McCalle3027922010-08-25 11:45:40 +00004048 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00004049 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004050 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00004051
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00004052 CGM.EmitExplicitCastExprType(CE, this);
Anders Carlsson50cb3212009-11-14 21:21:42 +00004053 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004054 Address V = Builder.CreateBitCast(LV.getAddress(),
4055 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00004056
4057 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00004058 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
4059 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00004060 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00004061
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004062 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo());
Anders Carlsson50cb3212009-11-14 21:21:42 +00004063 }
John McCalle3027922010-08-25 11:45:40 +00004064 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004065 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00004066 Address V = Builder.CreateElementBitCast(LV.getAddress(),
4067 ConvertType(E->getType()));
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004068 return MakeAddrLValue(V, E->getType(), LV.getBaseInfo());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004069 }
Egor Churaev89831422016-12-23 14:55:49 +00004070 case CK_ZeroToOCLQueue:
4071 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00004072 case CK_ZeroToOCLEvent:
4073 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00004074 }
Craig Topper99e79272013-07-26 05:59:26 +00004075
Douglas Gregorcdb466e2010-07-15 18:58:16 +00004076 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00004077}
4078
John McCall1bf58462011-02-16 08:02:54 +00004079LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00004080 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00004081 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00004082}
4083
Eli Friedman7f1ff602012-04-16 03:54:45 +00004084RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004085 const FieldDecl *FD,
4086 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004087 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00004088 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00004089 switch (getEvaluationKind(FT)) {
4090 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004091 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00004092 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00004093 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00004094 case TEK_Scalar:
Reid Kleckner9d031092016-05-02 22:42:34 +00004095 // This routine is used to load fields one-by-one to perform a copy, so
4096 // don't load reference fields.
4097 if (FD->getType()->isReferenceType())
4098 return RValue::get(FieldLV.getPointer());
Nick Lewycky2d84e842013-10-02 02:29:49 +00004099 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00004100 }
4101 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004102}
Douglas Gregorfe314812011-06-21 17:03:29 +00004103
Chris Lattnere47e4402007-06-01 18:02:12 +00004104//===--------------------------------------------------------------------===//
4105// Expression Emission
4106//===--------------------------------------------------------------------===//
4107
Craig Topper99e79272013-07-26 05:59:26 +00004108RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00004109 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00004110 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00004111 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00004112 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00004113
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004114 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00004115 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00004116
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004117 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00004118 return EmitCUDAKernelCallExpr(CE, ReturnValue);
4119
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004120 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
John McCallb92ab1a2016-10-26 23:46:34 +00004121 if (const CXXMethodDecl *MD =
4122 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
Anders Carlssonbfb36712009-12-24 21:13:40 +00004123 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00004124
John McCallb92ab1a2016-10-26 23:46:34 +00004125 CGCallee callee = EmitCallee(E->getCallee());
Craig Topper99e79272013-07-26 05:59:26 +00004126
John McCallb92ab1a2016-10-26 23:46:34 +00004127 if (callee.isBuiltin()) {
4128 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
4129 E, ReturnValue);
Douglas Gregorad8a3362009-09-04 17:36:40 +00004130 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004131
John McCallb92ab1a2016-10-26 23:46:34 +00004132 if (callee.isPseudoDestructor()) {
4133 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
4134 }
4135
4136 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
4137}
4138
4139/// Emit a CallExpr without considering whether it might be a subclass.
4140RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
4141 ReturnValueSlot ReturnValue) {
4142 CGCallee Callee = EmitCallee(E->getCallee());
4143 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
4144}
4145
4146static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
4147 if (auto builtinID = FD->getBuiltinID()) {
4148 return CGCallee::forBuiltin(builtinID, FD);
4149 }
4150
4151 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
4152 return CGCallee::forDirect(calleePtr, FD);
4153}
4154
4155CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
4156 E = E->IgnoreParens();
4157
4158 // Look through function-to-pointer decay.
4159 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
4160 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
4161 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
4162 return EmitCallee(ICE->getSubExpr());
4163 }
4164
4165 // Resolve direct calls.
4166 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
4167 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
4168 return EmitDirectCallee(*this, FD);
4169 }
4170 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
4171 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
4172 EmitIgnoredExpr(ME->getBase());
4173 return EmitDirectCallee(*this, FD);
4174 }
4175
4176 // Look through template substitutions.
4177 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4178 return EmitCallee(NTTP->getReplacement());
4179
4180 // Treat pseudo-destructor calls differently.
4181 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4182 return CGCallee::forPseudoDestructor(PDE);
4183 }
4184
4185 // Otherwise, we have an indirect reference.
4186 llvm::Value *calleePtr;
4187 QualType functionType;
4188 if (auto ptrType = E->getType()->getAs<PointerType>()) {
4189 calleePtr = EmitScalarExpr(E);
4190 functionType = ptrType->getPointeeType();
4191 } else {
4192 functionType = E->getType();
4193 calleePtr = EmitLValue(E).getPointer();
4194 }
4195 assert(functionType->isFunctionType());
4196 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
4197 E->getReferencedDeclOfCallee());
4198 CGCallee callee(calleeInfo, calleePtr);
4199 return callee;
Chris Lattner9e47ead2007-08-31 04:44:06 +00004200}
4201
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004202LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00004203 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00004204 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00004205 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00004206 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00004207 return EmitLValue(E->getRHS());
4208 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004209
John McCalle3027922010-08-25 11:45:40 +00004210 if (E->getOpcode() == BO_PtrMemD ||
4211 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004212 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004213
John McCalla2342eb2010-12-05 02:00:02 +00004214 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00004215
4216 // Note that in all of these cases, __block variables need the RHS
4217 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00004218
4219 switch (getEvaluationKind(E->getType())) {
4220 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00004221 switch (E->getLHS()->getType().getObjCLifetime()) {
4222 case Qualifiers::OCL_Strong:
4223 return EmitARCStoreStrong(E, /*ignored*/ false).first;
4224
4225 case Qualifiers::OCL_Autoreleasing:
4226 return EmitARCStoreAutoreleasing(E).first;
4227
4228 // No reason to do any of these differently.
4229 case Qualifiers::OCL_None:
4230 case Qualifiers::OCL_ExplicitNone:
4231 case Qualifiers::OCL_Weak:
4232 break;
4233 }
4234
John McCalld0a30012010-12-06 06:10:02 +00004235 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00004236 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
Vedant Kumar6b22dda2017-04-26 21:55:17 +00004237 if (RV.isScalar())
4238 EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
John McCall55e1fbc2011-06-25 02:11:03 +00004239 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00004240 return LV;
4241 }
John McCall4f29b492010-11-16 23:07:28 +00004242
John McCall47fb9502013-03-07 21:37:08 +00004243 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00004244 return EmitComplexAssignmentLValue(E);
4245
John McCall47fb9502013-03-07 21:37:08 +00004246 case TEK_Aggregate:
4247 return EmitAggExprToLValue(E);
4248 }
4249 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00004250}
4251
Christopher Lambd91c3d42007-12-29 05:02:41 +00004252LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00004253 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00004254
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004255 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004256 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004257 LValueBaseInfo(AlignmentSource::Decl, false));
Craig Topper99e79272013-07-26 05:59:26 +00004258
David Majnemerced8bdf2015-02-25 17:36:15 +00004259 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004260 "Can't have a scalar return unless the return type is a "
4261 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00004262
John McCall7f416cc2015-09-08 08:05:57 +00004263 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00004264}
4265
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004266LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4267 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00004268 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00004269}
4270
Anders Carlsson3be22e22009-05-30 23:23:33 +00004271LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004272 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
4273 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00004274 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00004275 EmitCXXConstructExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004276 return MakeAddrLValue(Slot.getAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004277 LValueBaseInfo(AlignmentSource::Decl, false));
Anders Carlsson3be22e22009-05-30 23:23:33 +00004278}
4279
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004280LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00004281CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004282 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00004283}
4284
John McCall7f416cc2015-09-08 08:05:57 +00004285Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
4286 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4287 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00004288}
4289
4290LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004291 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004292 LValueBaseInfo(AlignmentSource::Decl, false));
Nico Webercf4ff5862012-10-11 10:13:44 +00004293}
4294
Mike Stumpc9b231c2009-11-15 08:09:41 +00004295LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004296CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004297 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00004298 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00004299 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004300 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
4301 return MakeAddrLValue(Slot.getAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004302 LValueBaseInfo(AlignmentSource::Decl, false));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004303}
4304
Eli Friedman5bc17122012-02-08 05:34:55 +00004305LValue
4306CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00004307 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00004308 EmitLambdaExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004309 return MakeAddrLValue(Slot.getAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004310 LValueBaseInfo(AlignmentSource::Decl, false));
Eli Friedman5bc17122012-02-08 05:34:55 +00004311}
4312
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004313LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004314 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00004315
Anders Carlsson280e61f12010-06-21 20:59:55 +00004316 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004317 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004318 LValueBaseInfo(AlignmentSource::Decl, false));
Craig Topper99e79272013-07-26 05:59:26 +00004319
Alp Toker314cc812014-01-25 16:55:45 +00004320 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00004321 "Can't have a scalar return unless the return type is a "
4322 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00004323
John McCall7f416cc2015-09-08 08:05:57 +00004324 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004325}
4326
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004327LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004328 Address V =
4329 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004330 return MakeAddrLValue(V, E->getType(),
4331 LValueBaseInfo(AlignmentSource::Decl, false));
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004332}
4333
Daniel Dunbar722f4242009-04-22 05:08:15 +00004334llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004335 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004336 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004337}
4338
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004339LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4340 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004341 const ObjCIvarDecl *Ivar,
4342 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00004343 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00004344 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004345}
4346
4347LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004348 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00004349 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004350 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00004351 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004352 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004353 if (E->isArrow()) {
4354 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004355 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00004356 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004357 } else {
4358 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00004359 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004360 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00004361 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004362 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004363
Craig Topper99e79272013-07-26 05:59:26 +00004364 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00004365 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4366 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00004367 setObjCGCLValueClass(getContext(), E, LV);
4368 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00004369}
4370
Chris Lattnera4185c52009-04-25 19:35:26 +00004371LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00004372 // Can only get l-value for message expression returning aggregate type
4373 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00004374 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004375 LValueBaseInfo(AlignmentSource::Decl, false));
Chris Lattnera4185c52009-04-25 19:35:26 +00004376}
4377
John McCallb92ab1a2016-10-26 23:46:34 +00004378RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004379 const CallExpr *E, ReturnValueSlot ReturnValue,
John McCallb92ab1a2016-10-26 23:46:34 +00004380 llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00004381 // Get the actual function type. The callee type will always be a pointer to
4382 // function type or a block pointer type.
4383 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00004384 "Call must have function pointer type!");
4385
John McCallb92ab1a2016-10-26 23:46:34 +00004386 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
Samuel Antao798f11c2015-11-23 22:04:44 +00004387
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004388 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
Eric Christopher39db7262015-11-14 01:56:04 +00004389 // We can only guarantee that a function is called from the correct
4390 // context/function based on the appropriate target attributes,
4391 // so only check in the case where we have both always_inline and target
4392 // since otherwise we could be making a conditional call after a check for
4393 // the proper cpu features (and it won't cause code generation issues due to
4394 // function based code generation).
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004395 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4396 TargetDecl->hasAttr<TargetAttr>())
4397 checkTargetFeatures(E, FD);
4398
John McCall6fd4c232009-10-23 08:22:42 +00004399 CalleeType = getContext().getCanonicalType(CalleeType);
4400
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004401 const auto *FnType =
4402 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00004403
John McCallb92ab1a2016-10-26 23:46:34 +00004404 CGCallee Callee = OrigCallee;
4405
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004406 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004407 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4408 if (llvm::Constant *PrefixSig =
4409 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00004410 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004411 llvm::Constant *FTRTTIConst =
4412 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
Vedant Kumarbb5d4852017-09-13 00:04:35 +00004413 llvm::Type *PrefixStructTyElems[] = {PrefixSig->getType(), Int32Ty};
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004414 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4415 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4416
John McCallb92ab1a2016-10-26 23:46:34 +00004417 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4418
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004419 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
John McCallb92ab1a2016-10-26 23:46:34 +00004420 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004421 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004422 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00004423 llvm::Value *CalleeSig =
4424 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004425 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4426
4427 llvm::BasicBlock *Cont = createBasicBlock("cont");
4428 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4429 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4430
4431 EmitBlock(TypeCheck);
4432 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004433 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
Vedant Kumarbb5d4852017-09-13 00:04:35 +00004434 llvm::Value *CalleeRTTIEncoded =
John McCall7f416cc2015-09-08 08:05:57 +00004435 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Vedant Kumarbb5d4852017-09-13 00:04:35 +00004436 llvm::Value *CalleeRTTI =
4437 DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004438 llvm::Value *CalleeRTTIMatch =
4439 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4440 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004441 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004442 EmitCheckTypeDescriptor(CalleeType)
4443 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00004444 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004445 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004446
4447 Builder.CreateBr(Cont);
4448 EmitBlock(Cont);
4449 }
4450 }
4451
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004452 // If we are checking indirect calls and this call is indirect, check that the
4453 // function pointer is a member of the bit set for the function type.
4454 if (SanOpts.has(SanitizerKind::CFIICall) &&
4455 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4456 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00004457 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004458
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004459 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004460 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004461
John McCallb92ab1a2016-10-26 23:46:34 +00004462 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4463 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004464 llvm::Value *TypeTest = Builder.CreateCall(
4465 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004466
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004467 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004468 llvm::Constant *StaticData[] = {
4469 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4470 EmitCheckSourceLocation(E->getLocStart()),
4471 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4472 };
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004473 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4474 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004475 CastedCallee, StaticData);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004476 } else {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004477 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004478 SanitizerHandler::CFICheckFail, StaticData,
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004479 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004480 }
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004481 }
4482
Daniel Dunbarc722b852008-08-30 03:02:31 +00004483 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00004484 if (Chain)
4485 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4486 CGM.getContext().VoidPtrTy);
Richard Smith762672a2016-09-28 19:09:10 +00004487
4488 // C++17 requires that we evaluate arguments to a call using assignment syntax
Richard Smitha560ccf2016-09-29 21:30:12 +00004489 // right-to-left, and that we evaluate arguments to certain other operators
4490 // left-to-right. Note that we allow this to override the order dictated by
4491 // the calling convention on the MS ABI, which means that parameter
4492 // destruction order is not necessarily reverse construction order.
4493 // FIXME: Revisit this based on C++ committee response to unimplementability.
4494 EvaluationOrder Order = EvaluationOrder::Default;
4495 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4496 if (OCE->isAssignmentOp())
4497 Order = EvaluationOrder::ForceRightToLeft;
4498 else {
4499 switch (OCE->getOperator()) {
4500 case OO_LessLess:
4501 case OO_GreaterGreater:
4502 case OO_AmpAmp:
4503 case OO_PipePipe:
4504 case OO_Comma:
4505 case OO_ArrowStar:
4506 Order = EvaluationOrder::ForceLeftToRight;
4507 break;
4508 default:
4509 break;
4510 }
4511 }
4512 }
Richard Smith762672a2016-09-28 19:09:10 +00004513
David Blaikief05779e2015-07-21 18:37:18 +00004514 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
Richard Smitha560ccf2016-09-29 21:30:12 +00004515 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
Daniel Dunbarc722b852008-08-30 03:02:31 +00004516
Peter Collingbournef7706832014-12-12 23:41:25 +00004517 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4518 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00004519
4520 // C99 6.5.2.2p6:
4521 // If the expression that denotes the called function has a type
4522 // that does not include a prototype, [the default argument
4523 // promotions are performed]. If the number of arguments does not
4524 // equal the number of parameters, the behavior is undefined. If
4525 // the function is defined with a type that includes a prototype,
4526 // and either the prototype ends with an ellipsis (, ...) or the
4527 // types of the arguments after promotion are not compatible with
4528 // the types of the parameters, the behavior is undefined. If the
4529 // function is defined with a type that does not include a
4530 // prototype, and the types of the arguments after promotion are
4531 // not compatible with those of the parameters after promotion,
4532 // the behavior is undefined [except in some trivial cases].
4533 // That is, in the general case, we should assume that a call
4534 // through an unprototyped function type works like a *non-variadic*
4535 // call. The way we make this work is to cast to the exact type
4536 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00004537 //
4538 // Chain calls use this same code path to add the invisible chain parameter
4539 // to the function type.
4540 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00004541 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00004542 CalleeTy = CalleeTy->getPointerTo();
John McCallb92ab1a2016-10-26 23:46:34 +00004543
4544 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4545 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4546 Callee.setFunctionPointer(CalleePtr);
John McCallcbc038a2011-09-21 08:08:30 +00004547 }
4548
John McCallb92ab1a2016-10-26 23:46:34 +00004549 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00004550}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004551
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004552LValue CodeGenFunction::
4553EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004554 Address BaseAddr = Address::invalid();
4555 if (E->getOpcode() == BO_PtrMemI) {
4556 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4557 } else {
4558 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4559 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004560
John McCallc134eb52010-08-31 21:07:20 +00004561 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4562
4563 const MemberPointerType *MPT
4564 = E->getRHS()->getType()->getAs<MemberPointerType>();
4565
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004566 LValueBaseInfo BaseInfo;
John McCall7f416cc2015-09-08 08:05:57 +00004567 Address MemberAddr =
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004568 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo);
John McCallc134eb52010-08-31 21:07:20 +00004569
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004570 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004571}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004572
John McCall47fb9502013-03-07 21:37:08 +00004573/// Given the address of a temporary variable, produce an r-value of
4574/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00004575RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004576 QualType type,
4577 SourceLocation loc) {
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004578 LValue lvalue = MakeAddrLValue(addr, type,
4579 LValueBaseInfo(AlignmentSource::Decl, false));
John McCall47fb9502013-03-07 21:37:08 +00004580 switch (getEvaluationKind(type)) {
4581 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004582 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004583 case TEK_Aggregate:
4584 return lvalue.asAggregateRValue();
4585 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004586 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004587 }
4588 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004589}
4590
Duncan Sandse81111c2012-04-10 08:23:07 +00004591void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004592 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00004593 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004594 return;
4595
Duncan Sands65229ed2012-04-16 16:29:47 +00004596 llvm::MDBuilder MDHelper(getLLVMContext());
4597 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004598
Duncan Sands6fc46192012-04-14 12:37:26 +00004599 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004600}
John McCallfe96e0b2011-11-06 09:01:30 +00004601
4602namespace {
4603 struct LValueOrRValue {
4604 LValue LV;
4605 RValue RV;
4606 };
4607}
4608
4609static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4610 const PseudoObjectExpr *E,
4611 bool forLValue,
4612 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004613 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00004614
4615 // Find the result expression, if any.
4616 const Expr *resultExpr = E->getResultExpr();
4617 LValueOrRValue result;
4618
4619 for (PseudoObjectExpr::const_semantics_iterator
4620 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4621 const Expr *semantic = *i;
4622
4623 // If this semantic expression is an opaque value, bind it
4624 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004625 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00004626
4627 // If this is the result expression, we may need to evaluate
4628 // directly into the slot.
4629 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4630 OVMA opaqueData;
4631 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00004632 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00004633 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004634 LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
John McCall7f416cc2015-09-08 08:05:57 +00004635 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
Krzysztof Parzyszek8f248232017-05-18 17:07:11 +00004636 BaseInfo);
John McCallfe96e0b2011-11-06 09:01:30 +00004637 opaqueData = OVMA::bind(CGF, ov, LV);
4638 result.RV = slot.asRValue();
4639
4640 // Otherwise, emit as normal.
4641 } else {
4642 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4643
4644 // If this is the result, also evaluate the result now.
4645 if (ov == resultExpr) {
4646 if (forLValue)
4647 result.LV = CGF.EmitLValue(ov);
4648 else
4649 result.RV = CGF.EmitAnyExpr(ov, slot);
4650 }
4651 }
4652
4653 opaques.push_back(opaqueData);
4654
4655 // Otherwise, if the expression is the result, evaluate it
4656 // and remember the result.
4657 } else if (semantic == resultExpr) {
4658 if (forLValue)
4659 result.LV = CGF.EmitLValue(semantic);
4660 else
4661 result.RV = CGF.EmitAnyExpr(semantic, slot);
4662
4663 // Otherwise, evaluate the expression in an ignored context.
4664 } else {
4665 CGF.EmitIgnoredExpr(semantic);
4666 }
4667 }
4668
4669 // Unbind all the opaques now.
4670 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4671 opaques[i].unbind(CGF);
4672
4673 return result;
4674}
4675
4676RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4677 AggValueSlot slot) {
4678 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4679}
4680
4681LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4682 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4683}