blob: 98a6b173f88469b7d8b3845f79f8da2a6e785ee9 [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
14#include "CodeGenFunction.h"
John McCall5d865c322010-08-31 07:33:07 +000015#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CGCall.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"
21#include "CodeGenModule.h"
John McCallcbc038a2011-09-21 08:08:30 +000022#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000023#include "clang/AST/ASTContext.h"
Renato Golin230c5eb2014-05-19 18:15:42 +000024#include "clang/AST/Attr.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000025#include "clang/AST/DeclObjC.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000026#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "llvm/ADT/Hashing.h"
Alexey Bataevec474782014-10-09 08:45:04 +000028#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000029#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/LLVMContext.h"
32#include "llvm/IR/MDBuilder.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000033#include "llvm/Support/ConvertUTF.h"
Peter Collingbourne3eea6772015-05-11 21:39:14 +000034#include "llvm/Support/MathExtras.h"
Filipe Cabecinhasab731f72016-05-12 16:51:36 +000035#include "llvm/Support/Path.h"
Peter Collingbournedc134532016-01-16 00:31:22 +000036#include "llvm/Transforms/Utils/SanitizerStats.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000037
Chris Lattnere47e4402007-06-01 18:02:12 +000038using namespace clang;
39using namespace CodeGen;
40
Chris Lattnerd7f58862007-06-02 05:24:33 +000041//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000042// Miscellaneous Helper Methods
43//===--------------------------------------------------------------------===//
44
John McCallad7c5c12011-02-08 08:22:06 +000045llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
46 unsigned addressSpace =
47 cast<llvm::PointerType>(value->getType())->getAddressSpace();
48
Chris Lattner2192fe52011-07-18 04:24:23 +000049 llvm::PointerType *destType = Int8PtrTy;
John McCallad7c5c12011-02-08 08:22:06 +000050 if (addressSpace)
51 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
52
53 if (value->getType() == destType) return value;
54 return Builder.CreateBitCast(value, destType);
55}
56
Chris Lattnere9a64532007-06-22 21:44:33 +000057/// CreateTempAlloca - This creates a alloca and inserts it into the entry
58/// block.
John McCall7f416cc2015-09-08 08:05:57 +000059Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
60 const Twine &Name) {
61 auto Alloca = CreateTempAlloca(Ty, Name);
62 Alloca->setAlignment(Align.getQuantity());
63 return Address(Alloca, Align);
64}
65
66/// CreateTempAlloca - This creates a alloca and inserts it into the entry
67/// block.
Chris Lattner2192fe52011-07-18 04:24:23 +000068llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000069 const Twine &Name) {
Craig Topper8a13c412014-05-21 05:09:00 +000070 return new llvm::AllocaInst(Ty, nullptr, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +000071}
Chris Lattner8394d792007-06-05 20:53:16 +000072
John McCall7f416cc2015-09-08 08:05:57 +000073/// CreateDefaultAlignTempAlloca - This creates an alloca with the
74/// default alignment of the corresponding LLVM type, which is *not*
75/// guaranteed to be related in any way to the expected alignment of
76/// an AST type that might have been lowered to Ty.
77Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
78 const Twine &Name) {
79 CharUnits Align =
80 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
81 return CreateTempAlloca(Ty, Align, Name);
82}
83
84void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
85 assert(isa<llvm::AllocaInst>(Var.getPointer()));
86 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
87 Store->setAlignment(Var.getAlignment().getQuantity());
John McCall2e6567a2010-04-22 01:10:34 +000088 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +000089 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
John McCall2e6567a2010-04-22 01:10:34 +000090}
91
John McCall7f416cc2015-09-08 08:05:57 +000092Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +000093 CharUnits Align = getContext().getTypeAlignInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +000094 return CreateTempAlloca(ConvertType(Ty), Align, Name);
Daniel Dunbard0049182010-02-16 19:44:13 +000095}
96
John McCall7f416cc2015-09-08 08:05:57 +000097Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name) {
Daniel Dunbara7566f12010-02-09 02:48:28 +000098 // FIXME: Should we prefer the preferred type alignment here?
John McCall7f416cc2015-09-08 08:05:57 +000099 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name);
100}
101
102Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
103 const Twine &Name) {
104 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name);
Daniel Dunbara7566f12010-02-09 02:48:28 +0000105}
106
Chris Lattner8394d792007-06-05 20:53:16 +0000107/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
108/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000109llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000110 PGO.setCurrentStmt(E);
John McCall7a9aac22010-08-23 01:21:21 +0000111 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +0000112 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +0000113 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +0000114 }
John McCall7a9aac22010-08-23 01:21:21 +0000115
116 QualType BoolTy = getContext().BoolTy;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000117 SourceLocation Loc = E->getExprLoc();
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000118 if (!E->getType()->isAnyComplexType())
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000119 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +0000120
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000121 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
122 Loc);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000123}
124
John McCalla2342eb2010-12-05 02:00:02 +0000125/// EmitIgnoredExpr - Emit code to compute the specified expression,
126/// ignoring the result.
127void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
128 if (E->isRValue())
129 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
130
131 // Just emit it as an l-value and drop the result.
132 EmitLValue(E);
133}
134
John McCall7a626f62010-09-15 10:14:12 +0000135/// EmitAnyExpr - Emit code to compute the specified expression which
136/// can have any type. The result is returned as an RValue struct.
137/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000138/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000139RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
140 AggValueSlot aggSlot,
141 bool ignoreResult) {
John McCall47fb9502013-03-07 21:37:08 +0000142 switch (getEvaluationKind(E->getType())) {
143 case TEK_Scalar:
John McCall4e8ca4f2012-07-02 23:58:38 +0000144 return RValue::get(EmitScalarExpr(E, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000145 case TEK_Complex:
John McCall4e8ca4f2012-07-02 23:58:38 +0000146 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000147 case TEK_Aggregate:
148 if (!ignoreResult && aggSlot.isIgnored())
149 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
150 EmitAggExpr(E, aggSlot);
151 return aggSlot.asRValue();
152 }
153 llvm_unreachable("bad evaluation kind");
Chris Lattner4647a212007-08-31 22:49:20 +0000154}
155
Mike Stump4a3999f2009-09-09 13:00:44 +0000156/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
157/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000158RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
159 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000160
John McCall47fb9502013-03-07 21:37:08 +0000161 if (hasAggregateEvaluationKind(E->getType()))
John McCall7a626f62010-09-15 10:14:12 +0000162 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
163 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000164}
165
John McCall21886962010-04-21 10:05:39 +0000166/// EmitAnyExprToMem - Evaluate an expression into a given memory
167/// location.
168void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000169 Address Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000170 Qualifiers Quals,
171 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000172 // FIXME: This function should take an LValue as an argument.
John McCall47fb9502013-03-07 21:37:08 +0000173 switch (getEvaluationKind(E->getType())) {
174 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000175 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
John McCall47fb9502013-03-07 21:37:08 +0000176 /*isInit*/ false);
177 return;
178
179 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000180 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000181 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000182 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000183 AggValueSlot::IsAliased_t(!IsInit)));
John McCall47fb9502013-03-07 21:37:08 +0000184 return;
185 }
186
187 case TEK_Scalar: {
John McCall21886962010-04-21 10:05:39 +0000188 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000189 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000190 EmitStoreThroughLValue(RV, LV);
John McCall47fb9502013-03-07 21:37:08 +0000191 return;
John McCall21886962010-04-21 10:05:39 +0000192 }
John McCall47fb9502013-03-07 21:37:08 +0000193 }
194 llvm_unreachable("bad evaluation kind");
John McCall21886962010-04-21 10:05:39 +0000195}
196
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000197static void
198pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
John McCall7f416cc2015-09-08 08:05:57 +0000199 const Expr *E, Address ReferenceTemporary) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000200 // Objective-C++ ARC:
201 // If we are binding a reference to a temporary that has ownership, we
202 // need to perform retain/release operations on the temporary.
Richard Smith736a9472013-06-12 20:42:33 +0000203 //
204 // FIXME: This should be looking at E, not M.
John McCall460ce582015-10-22 18:38:17 +0000205 if (auto Lifetime = M->getType().getObjCLifetime()) {
206 switch (Lifetime) {
Richard Smith736a9472013-06-12 20:42:33 +0000207 case Qualifiers::OCL_None:
208 case Qualifiers::OCL_ExplicitNone:
209 // Carry on to normal cleanup handling.
210 break;
Sebastian Redl29526f02011-11-27 16:50:07 +0000211
Richard Smith736a9472013-06-12 20:42:33 +0000212 case Qualifiers::OCL_Autoreleasing:
213 // Nothing to do; cleaned up by an autorelease pool.
214 return;
215
216 case Qualifiers::OCL_Strong:
217 case Qualifiers::OCL_Weak:
218 switch (StorageDuration Duration = M->getStorageDuration()) {
219 case SD_Static:
220 // Note: we intentionally do not register a cleanup to release
221 // the object on program termination.
222 return;
223
224 case SD_Thread:
225 // FIXME: We should probably register a cleanup in this case.
226 return;
227
228 case SD_Automatic:
229 case SD_FullExpression:
Richard Smith736a9472013-06-12 20:42:33 +0000230 CodeGenFunction::Destroyer *Destroy;
231 CleanupKind CleanupKind;
232 if (Lifetime == Qualifiers::OCL_Strong) {
233 const ValueDecl *VD = M->getExtendingDecl();
234 bool Precise =
235 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
236 CleanupKind = CGF.getARCCleanupKind();
237 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
238 : &CodeGenFunction::destroyARCStrongImprecise;
239 } else {
240 // __weak objects always get EH cleanups; otherwise, exceptions
241 // could cause really nasty crashes instead of mere leaks.
242 CleanupKind = NormalAndEHCleanup;
243 Destroy = &CodeGenFunction::destroyARCWeak;
244 }
245 if (Duration == SD_FullExpression)
246 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000247 M->getType(), *Destroy,
Richard Smith736a9472013-06-12 20:42:33 +0000248 CleanupKind & EHCleanup);
249 else
250 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000251 M->getType(),
Richard Smith736a9472013-06-12 20:42:33 +0000252 *Destroy, CleanupKind & EHCleanup);
253 return;
254
255 case SD_Dynamic:
256 llvm_unreachable("temporary cannot have dynamic storage duration");
257 }
258 llvm_unreachable("unknown storage duration");
259 }
260 }
261
Craig Topper8a13c412014-05-21 05:09:00 +0000262 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
Richard Smith736a9472013-06-12 20:42:33 +0000263 if (const RecordType *RT =
264 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
265 // Get the destructor for the reference temporary.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000266 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith736a9472013-06-12 20:42:33 +0000267 if (!ClassDecl->hasTrivialDestructor())
268 ReferenceTemporaryDtor = ClassDecl->getDestructor();
269 }
270
271 if (!ReferenceTemporaryDtor)
272 return;
273
274 // Call the destructor for the temporary.
275 switch (M->getStorageDuration()) {
276 case SD_Static:
277 case SD_Thread: {
278 llvm::Constant *CleanupFn;
279 llvm::Constant *CleanupArg;
280 if (E->getType()->isArrayType()) {
281 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
John McCall7f416cc2015-09-08 08:05:57 +0000282 ReferenceTemporary, E->getType(),
David Blaikieebe87e12013-08-27 23:57:18 +0000283 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
284 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
Richard Smith736a9472013-06-12 20:42:33 +0000285 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
286 } else {
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000287 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
288 StructorType::Complete);
John McCall7f416cc2015-09-08 08:05:57 +0000289 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
Richard Smith736a9472013-06-12 20:42:33 +0000290 }
291 CGF.CGM.getCXXABI().registerGlobalDtor(
292 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
293 break;
294 }
295
296 case SD_FullExpression:
297 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
298 CodeGenFunction::destroyCXXObject,
299 CGF.getLangOpts().Exceptions);
300 break;
301
302 case SD_Automatic:
303 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
304 ReferenceTemporary, E->getType(),
305 CodeGenFunction::destroyCXXObject,
306 CGF.getLangOpts().Exceptions);
307 break;
308
309 case SD_Dynamic:
310 llvm_unreachable("temporary cannot have dynamic storage duration");
311 }
312}
313
John McCall7f416cc2015-09-08 08:05:57 +0000314static Address
Richard Smith736a9472013-06-12 20:42:33 +0000315createReferenceTemporary(CodeGenFunction &CGF,
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000316 const MaterializeTemporaryExpr *M, const Expr *Inner) {
Richard Smith736a9472013-06-12 20:42:33 +0000317 switch (M->getStorageDuration()) {
318 case SD_FullExpression:
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000319 case SD_Automatic: {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000320 // If we have a constant temporary array or record try to promote it into a
321 // constant global under the same rules a normal constant would've been
322 // promoted. This is easier on the optimizer and generally emits fewer
323 // instructions.
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000324 QualType Ty = Inner->getType();
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000325 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000326 (Ty->isArrayType() || Ty->isRecordType()) &&
327 CGF.CGM.isTypeConstant(Ty, true))
328 if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000329 auto *GV = new llvm::GlobalVariable(
330 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
331 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp");
John McCall7f416cc2015-09-08 08:05:57 +0000332 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
333 GV->setAlignment(alignment.getQuantity());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000334 // FIXME: Should we put the new global into a COMDAT?
John McCall7f416cc2015-09-08 08:05:57 +0000335 return Address(GV, alignment);
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000336 }
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000337 return CGF.CreateMemTemp(Ty, "ref.tmp");
338 }
Richard Smith736a9472013-06-12 20:42:33 +0000339 case SD_Thread:
340 case SD_Static:
Hans Wennborgf9d865b2015-03-17 16:38:58 +0000341 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
Richard Smith736a9472013-06-12 20:42:33 +0000342
343 case SD_Dynamic:
344 llvm_unreachable("temporary can't have dynamic storage duration");
345 }
346 llvm_unreachable("unknown storage duration");
347}
348
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000349LValue CodeGenFunction::
350EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000351 const Expr *E = M->GetTemporaryExpr();
Richard Smith7c5d4dc2013-06-11 02:41:00 +0000352
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000353 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
354 // as that will cause the lifetime adjustment to be lost for ARC
John McCall460ce582015-10-22 18:38:17 +0000355 auto ownership = M->getType().getObjCLifetime();
356 if (ownership != Qualifiers::OCL_None &&
357 ownership != Qualifiers::OCL_ExplicitNone) {
John McCall7f416cc2015-09-08 08:05:57 +0000358 Address Object = createReferenceTemporary(*this, M, E);
359 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
360 Object = Address(llvm::ConstantExpr::getBitCast(Var,
361 ConvertTypeForMem(E->getType())
362 ->getPointerTo(Object.getAddressSpace())),
363 Object.getAlignment());
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000364
365 // createReferenceTemporary will promote the temporary to a global with a
366 // constant initializer if it can. It can only do this to a value of
367 // ARC-manageable type if the value is global and therefore "immune" to
368 // ref-counting operations. Therefore we have no need to emit either a
369 // dynamic initialization or a cleanup and we can just return the address
370 // of the temporary.
371 if (Var->hasInitializer())
372 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
373
Richard Smitha509f2f2013-06-14 03:07:01 +0000374 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
375 }
John McCall7f416cc2015-09-08 08:05:57 +0000376 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
377 AlignmentSource::Decl);
Richard Smitha509f2f2013-06-14 03:07:01 +0000378
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000379 switch (getEvaluationKind(E->getType())) {
380 default: llvm_unreachable("expected scalar or aggregate expression");
381 case TEK_Scalar:
382 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
383 break;
384 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000385 EmitAggExpr(E, AggValueSlot::forAddr(Object,
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000386 E->getType().getQualifiers(),
387 AggValueSlot::IsDestructed,
388 AggValueSlot::DoesNotNeedGCBarriers,
389 AggValueSlot::IsNotAliased));
390 break;
391 }
392 }
Richard Smith736a9472013-06-12 20:42:33 +0000393
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000394 pushTemporaryCleanup(*this, M, E, Object);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000395 return RefTempDst;
Jordan Roseb1312a52013-04-11 00:58:58 +0000396 }
397
Richard Smithf3fabd22013-06-03 00:17:11 +0000398 SmallVector<const Expr *, 2> CommaLHSs;
Jordan Roseb1312a52013-04-11 00:58:58 +0000399 SmallVector<SubobjectAdjustment, 2> Adjustments;
Richard Smithf3fabd22013-06-03 00:17:11 +0000400 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
401
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000402 for (const auto &Ignored : CommaLHSs)
403 EmitIgnoredExpr(Ignored);
Richard Smithf3fabd22013-06-03 00:17:11 +0000404
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000405 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
Richard Smith736a9472013-06-12 20:42:33 +0000406 if (opaque->getType()->isRecordType()) {
407 assert(Adjustments.empty());
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000408 return EmitOpaqueValueLValue(opaque);
Jordan Roseb1312a52013-04-11 00:58:58 +0000409 }
410 }
411
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000412 // Create and initialize the reference temporary.
John McCall7f416cc2015-09-08 08:05:57 +0000413 Address Object = createReferenceTemporary(*this, M, E);
414 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
415 Object = Address(llvm::ConstantExpr::getBitCast(
416 Var, ConvertTypeForMem(E->getType())->getPointerTo()),
417 Object.getAlignment());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000418 // If the temporary is a global and has a constant initializer or is a
419 // constant temporary that we promoted to a global, we may have already
420 // initialized it.
Richard Smitha509f2f2013-06-14 03:07:01 +0000421 if (!Var->hasInitializer()) {
422 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
423 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
424 }
425 } else {
426 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
427 }
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000428 pushTemporaryCleanup(*this, M, E, Object);
Jordan Roseb1312a52013-04-11 00:58:58 +0000429
Richard Smith736a9472013-06-12 20:42:33 +0000430 // Perform derived-to-base casts and/or field accesses, to get from the
431 // temporary object we created (and, potentially, for which we extended
432 // the lifetime) to the subobject we're binding the reference to.
433 for (unsigned I = Adjustments.size(); I != 0; --I) {
434 SubobjectAdjustment &Adjustment = Adjustments[I-1];
435 switch (Adjustment.Kind) {
436 case SubobjectAdjustment::DerivedToBaseAdjustment:
437 Object =
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000438 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
439 Adjustment.DerivedToBase.BasePath->path_begin(),
440 Adjustment.DerivedToBase.BasePath->path_end(),
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000441 /*NullCheckValue=*/ false, E->getExprLoc());
Richard Smith736a9472013-06-12 20:42:33 +0000442 break;
Richard Smithf3fabd22013-06-03 00:17:11 +0000443
Richard Smith736a9472013-06-12 20:42:33 +0000444 case SubobjectAdjustment::FieldAdjustment: {
John McCall7f416cc2015-09-08 08:05:57 +0000445 LValue LV = MakeAddrLValue(Object, E->getType(),
446 AlignmentSource::Decl);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000447 LV = EmitLValueForField(LV, Adjustment.Field);
Richard Smith736a9472013-06-12 20:42:33 +0000448 assert(LV.isSimple() &&
449 "materialized temporary field is not a simple lvalue");
450 Object = LV.getAddress();
451 break;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000452 }
453
Richard Smith736a9472013-06-12 20:42:33 +0000454 case SubobjectAdjustment::MemberPointerAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000455 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
John McCall7f416cc2015-09-08 08:05:57 +0000456 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
457 Adjustment.Ptr.MPT);
Richard Smith736a9472013-06-12 20:42:33 +0000458 break;
459 }
460 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000461 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000462
John McCall7f416cc2015-09-08 08:05:57 +0000463 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000464}
465
466RValue
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000467CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
468 // Emit the expression as an lvalue.
469 LValue LV = EmitLValue(E);
470 assert(LV.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000471 llvm::Value *Value = LV.getPointer();
Richard Smith736a9472013-06-12 20:42:33 +0000472
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000473 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000474 // C++11 [dcl.ref]p5 (as amended by core issue 453):
475 // If a glvalue to which a reference is directly bound designates neither
476 // an existing object or function of an appropriate type nor a region of
477 // storage of suitable size and alignment to contain an object of the
478 // reference's type, the behavior is undefined.
479 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000480 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000481 }
John McCall8680f872010-07-21 06:29:51 +0000482
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000483 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000484}
485
486
Mike Stump4a3999f2009-09-09 13:00:44 +0000487/// getAccessedFieldNo - Given an encoded value and a result number, return the
488/// input field number being accessed.
489unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000490 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000491 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
492 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000493}
494
Richard Smith4d3110a2012-10-25 02:14:12 +0000495/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
496static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
497 llvm::Value *High) {
498 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
499 llvm::Value *K47 = Builder.getInt64(47);
500 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
501 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
502 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
503 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
504 return Builder.CreateMul(B1, KMul);
505}
506
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000507bool CodeGenFunction::sanitizePerformTypeCheck() const {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000508 return SanOpts.has(SanitizerKind::Null) |
509 SanOpts.has(SanitizerKind::Alignment) |
510 SanOpts.has(SanitizerKind::ObjectSize) |
511 SanOpts.has(SanitizerKind::Vptr);
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000512}
513
Richard Smithe30752c2012-10-09 19:52:38 +0000514void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +0000515 llvm::Value *Ptr, QualType Ty,
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000516 CharUnits Alignment, bool SkipNullCheck) {
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000517 if (!sanitizePerformTypeCheck())
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000518 return;
519
Richard Smith2d8b2942012-11-01 07:22:08 +0000520 // Don't check pointers outside the default address space. The null check
521 // isn't correct, the object-size check isn't supported by LLVM, and we can't
522 // communicate the addresses to the runtime handler for the vptr check.
John McCall7f416cc2015-09-08 08:05:57 +0000523 if (Ptr->getType()->getPointerAddressSpace())
Richard Smith2d8b2942012-11-01 07:22:08 +0000524 return;
525
Alexey Samsonov24cad992014-07-17 18:46:27 +0000526 SanitizerScope SanScope(this);
527
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000528 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
Craig Topper8a13c412014-05-21 05:09:00 +0000529 llvm::BasicBlock *Done = nullptr;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000530
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000531 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
532 TCK == TCK_UpcastToVirtualBase;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000533 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
534 !SkipNullCheck) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000535 // The glvalue must not be an empty glvalue.
John McCall7f416cc2015-09-08 08:05:57 +0000536 llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr);
Richard Smith2c5868c2013-02-13 21:18:23 +0000537
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000538 if (AllowNullPointers) {
539 // When performing pointer casts, it's OK if the value is null.
Richard Smith2c5868c2013-02-13 21:18:23 +0000540 // Skip the remaining checks in that case.
541 Done = createBasicBlock("null");
542 llvm::BasicBlock *Rest = createBasicBlock("not.null");
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000543 Builder.CreateCondBr(IsNonNull, Rest, Done);
Richard Smith2c5868c2013-02-13 21:18:23 +0000544 EmitBlock(Rest);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +0000545 } else {
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000546 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
Richard Smith2c5868c2013-02-13 21:18:23 +0000547 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000548 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000549
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000550 if (SanOpts.has(SanitizerKind::ObjectSize) && !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000551 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000552
Richard Smith69d0d262012-08-24 00:54:33 +0000553 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000554 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000555 // to check this.
Matt Arsenault2f152632013-10-07 19:00:18 +0000556 // FIXME: Get object address space
557 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
558 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smith69d0d262012-08-24 00:54:33 +0000559 llvm::Value *Min = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +0000560 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
Richard Smith69d0d262012-08-24 00:54:33 +0000561 llvm::Value *LargeEnough =
David Blaikie43f9bb72015-05-18 22:14:03 +0000562 Builder.CreateICmpUGE(Builder.CreateCall(F, {CastAddr, Min}),
Richard Smith69d0d262012-08-24 00:54:33 +0000563 llvm::ConstantInt::get(IntPtrTy, Size));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000564 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
Richard Smithe30752c2012-10-09 19:52:38 +0000565 }
Richard Smith69d0d262012-08-24 00:54:33 +0000566
Richard Smithb1b0ab42012-11-05 22:21:05 +0000567 uint64_t AlignVal = 0;
568
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000569 if (SanOpts.has(SanitizerKind::Alignment)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000570 AlignVal = Alignment.getQuantity();
571 if (!Ty->isIncompleteType() && !AlignVal)
572 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
573
Richard Smith69d0d262012-08-24 00:54:33 +0000574 // The glvalue must be suitably aligned.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000575 if (AlignVal) {
576 llvm::Value *Align =
John McCall7f416cc2015-09-08 08:05:57 +0000577 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
Richard Smithb1b0ab42012-11-05 22:21:05 +0000578 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
579 llvm::Value *Aligned =
580 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000581 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000582 }
Richard Smith69d0d262012-08-24 00:54:33 +0000583 }
584
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000585 if (Checks.size() > 0) {
Richard Smithe30752c2012-10-09 19:52:38 +0000586 llvm::Constant *StaticData[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +0000587 EmitCheckSourceLocation(Loc),
Richard Smithe30752c2012-10-09 19:52:38 +0000588 EmitCheckTypeDescriptor(Ty),
589 llvm::ConstantInt::get(SizeTy, AlignVal),
590 llvm::ConstantInt::get(Int8Ty, TCK)
591 };
John McCall7f416cc2015-09-08 08:05:57 +0000592 EmitCheck(Checks, "type_mismatch", StaticData, Ptr);
Richard Smithe30752c2012-10-09 19:52:38 +0000593 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000594
Richard Smithb1b0ab42012-11-05 22:21:05 +0000595 // If possible, check that the vptr indicates that there is a subobject of
596 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000597 //
598 // C++11 [basic.life]p5,6:
599 // [For storage which does not refer to an object within its lifetime]
600 // The program has undefined behavior if:
601 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000602 // or call a non-static member function
Richard Smith4d3110a2012-10-25 02:14:12 +0000603 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000604 if (SanOpts.has(SanitizerKind::Vptr) &&
Richard Smith2c5868c2013-02-13 21:18:23 +0000605 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000606 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
607 TCK == TCK_UpcastToVirtualBase) &&
Richard Smith4d3110a2012-10-25 02:14:12 +0000608 RD && RD->hasDefinition() && RD->isDynamicClass()) {
Richard Smith4d3110a2012-10-25 02:14:12 +0000609 // Compute a hash of the mangled name of the type.
610 //
611 // FIXME: This is not guaranteed to be deterministic! Move to a
612 // fingerprinting mechanism once LLVM provides one. For the time
613 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000614 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000615 llvm::raw_svector_ostream Out(MangledName);
616 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
617 Out);
Richard Smith4d3110a2012-10-25 02:14:12 +0000618
Alexey Samsonov84856012014-07-10 22:34:19 +0000619 // Blacklist based on the mangled type.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000620 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
621 Out.str())) {
Alexey Samsonov84856012014-07-10 22:34:19 +0000622 llvm::hash_code TypeHash = hash_value(Out.str());
Richard Smith4d3110a2012-10-25 02:14:12 +0000623
Alexey Samsonov84856012014-07-10 22:34:19 +0000624 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
625 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
626 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
John McCall7f416cc2015-09-08 08:05:57 +0000627 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000628 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
629 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
Richard Smith4d3110a2012-10-25 02:14:12 +0000630
Alexey Samsonov84856012014-07-10 22:34:19 +0000631 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
632 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
Richard Smith4d3110a2012-10-25 02:14:12 +0000633
Alexey Samsonov84856012014-07-10 22:34:19 +0000634 // Look the hash up in our cache.
635 const int CacheSize = 128;
636 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
637 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
638 "__ubsan_vptr_type_cache");
639 llvm::Value *Slot = Builder.CreateAnd(Hash,
640 llvm::ConstantInt::get(IntPtrTy,
641 CacheSize-1));
642 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
643 llvm::Value *CacheVal =
John McCall7f416cc2015-09-08 08:05:57 +0000644 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
645 getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000646
647 // If the hash isn't in the cache, call a runtime handler to perform the
648 // hard work of checking whether the vptr is for an object of the right
649 // type. This will either fill in the cache and return, or produce a
650 // diagnostic.
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000651 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
Alexey Samsonov84856012014-07-10 22:34:19 +0000652 llvm::Constant *StaticData[] = {
653 EmitCheckSourceLocation(Loc),
654 EmitCheckTypeDescriptor(Ty),
655 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
656 llvm::ConstantInt::get(Int8Ty, TCK)
657 };
John McCall7f416cc2015-09-08 08:05:57 +0000658 llvm::Value *DynamicData[] = { Ptr, Hash };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000659 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
660 "dynamic_type_cache_miss", StaticData, DynamicData);
Alexey Samsonov84856012014-07-10 22:34:19 +0000661 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000662 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000663
664 if (Done) {
665 Builder.CreateBr(Done);
666 EmitBlock(Done);
667 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000668}
Chris Lattner4647a212007-08-31 22:49:20 +0000669
Richard Smith539e4a72013-02-23 02:53:19 +0000670/// Determine whether this expression refers to a flexible array member in a
671/// struct. We disable array bounds checks for such members.
672static bool isFlexibleArrayMemberExpr(const Expr *E) {
673 // For compatibility with existing code, we treat arrays of length 0 or
674 // 1 as flexible array members.
675 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000676 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000677 if (CAT->getSize().ugt(1))
678 return false;
679 } else if (!isa<IncompleteArrayType>(AT))
680 return false;
681
682 E = E->IgnoreParens();
683
684 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000685 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000686 // FIXME: If the base type of the member expr is not FD->getParent(),
687 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000688 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith539e4a72013-02-23 02:53:19 +0000689 RecordDecl::field_iterator FI(
690 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
691 return ++FI == FD->getParent()->field_end();
692 }
693 }
694
695 return false;
696}
697
698/// If Base is known to point to the start of an array, return the length of
699/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000700static llvm::Value *getArrayIndexingBound(
701 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000702 // For the vector indexing extension, the bound is the number of elements.
703 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
704 IndexedType = Base->getType();
705 return CGF.Builder.getInt32(VT->getNumElements());
706 }
707
708 Base = Base->IgnoreParens();
709
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000710 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000711 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
712 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
713 IndexedType = CE->getSubExpr()->getType();
714 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000715 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000716 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000717 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000718 return CGF.getVLASize(VAT).first;
719 }
720 }
721
Craig Topper8a13c412014-05-21 05:09:00 +0000722 return nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000723}
724
725void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
726 llvm::Value *Index, QualType IndexType,
727 bool Accessed) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000728 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
Richard Smith6b53e222013-10-22 22:51:04 +0000729 "should not be called unless adding bounds checks");
Alexey Samsonov24cad992014-07-17 18:46:27 +0000730 SanitizerScope SanScope(this);
Richard Smith2847b222013-02-24 01:56:24 +0000731
Richard Smith539e4a72013-02-23 02:53:19 +0000732 QualType IndexedType;
733 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
734 if (!Bound)
735 return;
736
737 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
738 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
739 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
740
741 llvm::Constant *StaticData[] = {
742 EmitCheckSourceLocation(E->getExprLoc()),
743 EmitCheckTypeDescriptor(IndexedType),
744 EmitCheckTypeDescriptor(IndexType)
745 };
746 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
747 : Builder.CreateICmpULE(IndexVal, BoundVal);
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000748 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds), "out_of_bounds",
749 StaticData, Index);
Richard Smith539e4a72013-02-23 02:53:19 +0000750}
751
Chris Lattner116ce8f2010-01-09 21:40:03 +0000752
Chris Lattner116ce8f2010-01-09 21:40:03 +0000753CodeGenFunction::ComplexPairTy CodeGenFunction::
754EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
755 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000756 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +0000757
Chris Lattner116ce8f2010-01-09 21:40:03 +0000758 llvm::Value *NextVal;
759 if (isa<llvm::IntegerType>(InVal.first->getType())) {
760 uint64_t AmountVal = isInc ? 1 : -1;
761 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +0000762
Chris Lattner116ce8f2010-01-09 21:40:03 +0000763 // Add the inc/dec to the real part.
764 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
765 } else {
766 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
767 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
768 if (!isInc)
769 FVal.changeSign();
770 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
Craig Topper99e79272013-07-26 05:59:26 +0000771
Chris Lattner116ce8f2010-01-09 21:40:03 +0000772 // Add the inc/dec to the real part.
773 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
774 }
Craig Topper99e79272013-07-26 05:59:26 +0000775
Chris Lattner116ce8f2010-01-09 21:40:03 +0000776 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +0000777
Chris Lattner116ce8f2010-01-09 21:40:03 +0000778 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +0000779 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Craig Topper99e79272013-07-26 05:59:26 +0000780
Chris Lattner116ce8f2010-01-09 21:40:03 +0000781 // If this is a postinc, return the value read from memory, otherwise use the
782 // updated value.
783 return isPre ? IncVal : InVal;
784}
785
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000786void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
787 CodeGenFunction *CGF) {
788 // Bind VLAs in the cast type.
789 if (CGF && E->getType()->isVariablyModifiedType())
790 CGF->EmitVariablyModifiedType(E->getType());
791
792 if (CGDebugInfo *DI = getModuleDebugInfo())
793 DI->EmitExplicitCastType(E->getType());
794}
795
Chris Lattnera45c5af2007-06-02 19:47:04 +0000796//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000797// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000798//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000799
John McCall7f416cc2015-09-08 08:05:57 +0000800/// EmitPointerWithAlignment - Given an expression of pointer type, try to
801/// derive a more accurate bound on the alignment of the pointer.
802Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
803 AlignmentSource *Source) {
804 // We allow this with ObjC object pointers because of fragile ABIs.
805 assert(E->getType()->isPointerType() ||
806 E->getType()->isObjCObjectPointerType());
807 E = E->IgnoreParens();
808
809 // Casts:
810 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000811 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
812 CGM.EmitExplicitCastExprType(ECE, this);
John McCall7f416cc2015-09-08 08:05:57 +0000813
814 switch (CE->getCastKind()) {
815 // Non-converting casts (but not C's implicit conversion from void*).
816 case CK_BitCast:
817 case CK_NoOp:
818 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
819 if (PtrTy->getPointeeType()->isVoidType())
820 break;
821
822 AlignmentSource InnerSource;
823 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerSource);
824 if (Source) *Source = InnerSource;
825
826 // If this is an explicit bitcast, and the source l-value is
827 // opaque, honor the alignment of the casted-to type.
828 if (isa<ExplicitCastExpr>(CE) &&
John McCall7f416cc2015-09-08 08:05:57 +0000829 InnerSource != AlignmentSource::Decl) {
830 Addr = Address(Addr.getPointer(),
831 getNaturalPointeeTypeAlignment(E->getType(), Source));
832 }
833
Peter Collingbourne574975e2016-01-14 02:49:48 +0000834 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
835 CE->getCastKind() == CK_BitCast) {
Peter Collingbourneee381ff2015-09-09 00:01:31 +0000836 if (auto PT = E->getType()->getAs<PointerType>())
837 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
838 /*MayBeNull=*/true,
839 CodeGenFunction::CFITCK_UnrelatedCast,
840 CE->getLocStart());
841 }
842
John McCall7f416cc2015-09-08 08:05:57 +0000843 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
844 }
845 break;
846
847 // Array-to-pointer decay.
848 case CK_ArrayToPointerDecay:
849 return EmitArrayToPointerDecay(CE->getSubExpr(), Source);
850
851 // Derived-to-base conversions.
852 case CK_UncheckedDerivedToBase:
853 case CK_DerivedToBase: {
854 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), Source);
855 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
856 return GetAddressOfBaseClass(Addr, Derived,
857 CE->path_begin(), CE->path_end(),
858 ShouldNullCheckClassCastValue(CE),
859 CE->getExprLoc());
860 }
861
862 // TODO: Is there any reason to treat base-to-derived conversions
863 // specially?
864 default:
865 break;
866 }
867 }
868
869 // Unary &.
870 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
871 if (UO->getOpcode() == UO_AddrOf) {
872 LValue LV = EmitLValue(UO->getSubExpr());
873 if (Source) *Source = LV.getAlignmentSource();
874 return LV.getAddress();
875 }
876 }
877
878 // TODO: conditional operators, comma.
879
880 // Otherwise, use the alignment of the type.
881 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), Source);
882 return Address(EmitScalarExpr(E), Align);
883}
884
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000885RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000886 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +0000887 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +0000888
889 switch (getEvaluationKind(Ty)) {
890 case TEK_Complex: {
891 llvm::Type *EltTy =
892 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +0000893 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000894 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000895 }
Craig Topper99e79272013-07-26 05:59:26 +0000896
Chris Lattner65526f02010-08-23 05:26:13 +0000897 // If this is a use of an undefined aggregate type, the aggregate must have an
898 // identifiable address. Just because the contents of the value are undefined
899 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +0000900 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000901 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +0000902 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000903 }
John McCall47fb9502013-03-07 21:37:08 +0000904
905 case TEK_Scalar:
906 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
907 }
908 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +0000909}
910
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000911RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
912 const char *Name) {
913 ErrorUnsupported(E, Name);
914 return GetUndefRValue(E->getType());
915}
916
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000917LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
918 const char *Name) {
919 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000920 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +0000921 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
922 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000923}
924
Richard Smith4d1458e2012-09-08 02:08:36 +0000925LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +0000926 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000927 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +0000928 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
929 else
930 LV = EmitLValue(E);
Daniel Dunbardc406b82010-04-05 21:36:35 +0000931 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
John McCall7f416cc2015-09-08 08:05:57 +0000932 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
Richard Smithe30752c2012-10-09 19:52:38 +0000933 E->getType(), LV.getAlignment());
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000934 return LV;
935}
936
Chris Lattner8394d792007-06-05 20:53:16 +0000937/// EmitLValue - Emit code to compute a designator that specifies the location
938/// of the expression.
939///
Mike Stump4a3999f2009-09-09 13:00:44 +0000940/// This can return one of two things: a simple address or a bitfield reference.
941/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
942/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +0000943///
Mike Stump4a3999f2009-09-09 13:00:44 +0000944/// If this returns a bitfield reference, nothing about the pointee type of the
945/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +0000946///
Mike Stump4a3999f2009-09-09 13:00:44 +0000947/// If this returns a normal address, and if the lvalue's C type is fixed size,
948/// this method guarantees that the returned pointer type will point to an LLVM
949/// type of the same size of the lvalue's type. If the lvalue has a variable
950/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +0000951///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000952LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +0000953 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +0000954 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000955 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000956
John McCallc109a252011-11-07 03:59:57 +0000957 case Expr::ObjCPropertyRefExprClass:
958 llvm_unreachable("cannot emit a property reference directly");
959
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000960 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +0000961 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000962 case Expr::ObjCIsaExprClass:
963 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000964 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +0000965 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +0000966 case Expr::CompoundAssignOperatorClass: {
967 QualType Ty = E->getType();
968 if (const AtomicType *AT = Ty->getAs<AtomicType>())
969 Ty = AT->getValueType();
970 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +0000971 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
972 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +0000973 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000974 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +0000975 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000976 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +0000977 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000978 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +0000979 case Expr::VAArgExprClass:
980 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000981 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000982 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +0000983 case Expr::ParenExprClass:
984 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +0000985 case Expr::GenericSelectionExprClass:
986 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +0000987 case Expr::PredefinedExprClass:
988 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +0000989 case Expr::StringLiteralClass:
990 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +0000991 case Expr::ObjCEncodeExprClass:
992 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +0000993 case Expr::PseudoObjectExprClass:
994 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +0000995 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +0000996 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +0000997 case Expr::CXXTemporaryObjectExprClass:
998 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +0000999 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1000 case Expr::CXXBindTemporaryExprClass:
1001 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +00001002 case Expr::CXXUuidofExprClass:
1003 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +00001004 case Expr::LambdaExprClass:
1005 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +00001006
1007 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001008 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +00001009 enterFullExpression(cleanups);
1010 RunCleanupsScope Scope(*this);
1011 return EmitLValue(cleanups->getSubExpr());
1012 }
1013
Anders Carlsson52ce3bb2009-11-14 01:51:50 +00001014 case Expr::CXXDefaultArgExprClass:
1015 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001016 case Expr::CXXDefaultInitExprClass: {
1017 CXXDefaultInitExprScope Scope(*this);
1018 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1019 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001020 case Expr::CXXTypeidExprClass:
1021 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001022
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001023 case Expr::ObjCMessageExprClass:
1024 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001025 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001026 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001027 case Expr::StmtExprClass:
1028 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001029 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001030 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001031 case Expr::ArraySubscriptExprClass:
1032 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001033 case Expr::OMPArraySectionExprClass:
1034 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001035 case Expr::ExtVectorElementExprClass:
1036 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001037 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001038 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001039 case Expr::CompoundLiteralExprClass:
1040 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001041 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001042 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001043 case Expr::BinaryConditionalOperatorClass:
1044 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001045 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001046 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001047 case Expr::OpaqueValueExprClass:
1048 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001049 case Expr::SubstNonTypeTemplateParmExprClass:
1050 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001051 case Expr::ImplicitCastExprClass:
1052 case Expr::CStyleCastExprClass:
1053 case Expr::CXXFunctionalCastExprClass:
1054 case Expr::CXXStaticCastExprClass:
1055 case Expr::CXXDynamicCastExprClass:
1056 case Expr::CXXReinterpretCastExprClass:
1057 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001058 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001059 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001060
Douglas Gregorfe314812011-06-21 17:03:29 +00001061 case Expr::MaterializeTemporaryExprClass:
1062 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001063 }
1064}
1065
John McCall71335052012-03-10 03:05:10 +00001066/// Given an object of the given canonical type, can we safely copy a
1067/// value out of it based on its initializer?
1068static bool isConstantEmittableObjectType(QualType type) {
1069 assert(type.isCanonical());
1070 assert(!type->isReferenceType());
1071
1072 // Must be const-qualified but non-volatile.
1073 Qualifiers qs = type.getLocalQualifiers();
1074 if (!qs.hasConst() || qs.hasVolatile()) return false;
1075
1076 // Otherwise, all object types satisfy this except C++ classes with
1077 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001078 if (const auto *RT = dyn_cast<RecordType>(type))
1079 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001080 if (RD->hasMutableFields() || !RD->isTrivial())
1081 return false;
1082
1083 return true;
1084}
1085
1086/// Can we constant-emit a load of a reference to a variable of the
1087/// given type? This is different from predicates like
1088/// Decl::isUsableInConstantExpressions because we do want it to apply
1089/// in situations that don't necessarily satisfy the language's rules
1090/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1091/// to do this with const float variables even if those variables
1092/// aren't marked 'constexpr'.
1093enum ConstantEmissionKind {
1094 CEK_None,
1095 CEK_AsReferenceOnly,
1096 CEK_AsValueOrReference,
1097 CEK_AsValueOnly
1098};
1099static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1100 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001101 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001102 if (isConstantEmittableObjectType(ref->getPointeeType()))
1103 return CEK_AsValueOrReference;
1104 return CEK_AsReferenceOnly;
1105 }
1106 if (isConstantEmittableObjectType(type))
1107 return CEK_AsValueOnly;
1108 return CEK_None;
1109}
1110
1111/// Try to emit a reference to the given value without producing it as
1112/// an l-value. This is actually more than an optimization: we can't
1113/// produce an l-value for variables that we never actually captured
1114/// in a block or lambda, which means const int variables or constexpr
1115/// literals or similar.
1116CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001117CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1118 ValueDecl *value = refExpr->getDecl();
1119
John McCall71335052012-03-10 03:05:10 +00001120 // The value needs to be an enum constant or a constant variable.
1121 ConstantEmissionKind CEK;
1122 if (isa<ParmVarDecl>(value)) {
1123 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001124 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001125 CEK = checkVarTypeForConstantEmission(var->getType());
1126 } else if (isa<EnumConstantDecl>(value)) {
1127 CEK = CEK_AsValueOnly;
1128 } else {
1129 CEK = CEK_None;
1130 }
1131 if (CEK == CEK_None) return ConstantEmission();
1132
John McCall71335052012-03-10 03:05:10 +00001133 Expr::EvalResult result;
1134 bool resultIsReference;
1135 QualType resultType;
1136
1137 // It's best to evaluate all the way as an r-value if that's permitted.
1138 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001139 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001140 resultIsReference = false;
1141 resultType = refExpr->getType();
1142
1143 // Otherwise, try to evaluate as an l-value.
1144 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001145 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001146 resultIsReference = true;
1147 resultType = value->getType();
1148
1149 // Failure.
1150 } else {
1151 return ConstantEmission();
1152 }
1153
1154 // In any case, if the initializer has side-effects, abandon ship.
1155 if (result.HasSideEffects)
1156 return ConstantEmission();
1157
1158 // Emit as a constant.
1159 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1160
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001161 // Make sure we emit a debug reference to the global variable.
1162 // This should probably fire even for
1163 if (isa<VarDecl>(value)) {
1164 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1165 EmitDeclRefExprDbgValue(refExpr, C);
1166 } else {
1167 assert(isa<EnumConstantDecl>(value));
1168 EmitDeclRefExprDbgValue(refExpr, C);
1169 }
John McCall71335052012-03-10 03:05:10 +00001170
1171 // If we emitted a reference constant, we need to dereference that.
1172 if (resultIsReference)
1173 return ConstantEmission::forReference(C);
1174
1175 return ConstantEmission::forValue(C);
1176}
1177
Nick Lewycky2d84e842013-10-02 02:29:49 +00001178llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1179 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +00001180 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001181 lvalue.getType(), Loc, lvalue.getAlignmentSource(),
1182 lvalue.getTBAAInfo(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001183 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1184 lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001185}
1186
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001187static bool hasBooleanRepresentation(QualType Ty) {
1188 if (Ty->isBooleanType())
1189 return true;
1190
1191 if (const EnumType *ET = Ty->getAs<EnumType>())
1192 return ET->getDecl()->getIntegerType()->isBooleanType();
1193
Douglas Gregor298f43d2012-04-12 20:42:30 +00001194 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1195 return hasBooleanRepresentation(AT->getValueType());
1196
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001197 return false;
1198}
1199
Richard Smith1629da92012-12-13 07:11:50 +00001200static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1201 llvm::APInt &Min, llvm::APInt &End,
1202 bool StrictEnums) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001203 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001204 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1205 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001206 bool IsBool = hasBooleanRepresentation(Ty);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001207 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001208 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001209
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001210 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001211 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1212 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001213 } else {
1214 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001215 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001216 unsigned Bitwidth = LTy->getScalarSizeInBits();
1217 unsigned NumNegativeBits = ED->getNumNegativeBits();
1218 unsigned NumPositiveBits = ED->getNumPositiveBits();
1219
1220 if (NumNegativeBits) {
1221 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1222 assert(NumBits <= Bitwidth);
1223 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1224 Min = -End;
1225 } else {
1226 assert(NumPositiveBits <= Bitwidth);
1227 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1228 Min = llvm::APInt(Bitwidth, 0);
1229 }
1230 }
Richard Smith1629da92012-12-13 07:11:50 +00001231 return true;
1232}
1233
1234llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1235 llvm::APInt Min, End;
1236 if (!getRangeForType(*this, Ty, Min, End,
1237 CGM.getCodeGenOpts().StrictEnums))
Craig Topper8a13c412014-05-21 05:09:00 +00001238 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001239
Duncan Sandsc720e782012-04-15 18:04:54 +00001240 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001241 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001242}
1243
John McCall7f416cc2015-09-08 08:05:57 +00001244llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1245 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001246 SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +00001247 AlignmentSource AlignSource,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001248 llvm::MDNode *TBAAInfo,
1249 QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001250 uint64_t TBAAOffset,
1251 bool isNontemporal) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001252 // For better performance, handle vector loads differently.
1253 if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001254 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001255
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001256 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001257
John McCall7f416cc2015-09-08 08:05:57 +00001258 // Handle vectors of size 3 like size 4 for better performance.
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001259 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001260
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001261 // Bitcast to vec4 type.
1262 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
1263 4);
John McCall7f416cc2015-09-08 08:05:57 +00001264 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001265 // Now load value.
John McCall7f416cc2015-09-08 08:05:57 +00001266 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001267
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001268 // Shuffle vector to get vec3.
John McCall7f416cc2015-09-08 08:05:57 +00001269 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
Benjamin Kramer99383102015-07-28 16:25:32 +00001270 {0, 1, 2}, "extractVec");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001271 return EmitFromMemory(V, Ty);
1272 }
1273 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001274
1275 // Atomic operations have to be done on integral types.
David Majnemera38c9f12016-05-24 16:09:25 +00001276 LValue AtomicLValue =
John McCall7f416cc2015-09-08 08:05:57 +00001277 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
David Majnemera38c9f12016-05-24 16:09:25 +00001278 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1279 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001280 }
Craig Topper99e79272013-07-26 05:59:26 +00001281
John McCall7f416cc2015-09-08 08:05:57 +00001282 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001283 if (isNontemporal) {
1284 llvm::MDNode *Node = llvm::MDNode::get(
1285 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1286 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1287 }
Manman Renc451e572013-04-04 21:53:22 +00001288 if (TBAAInfo) {
1289 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1290 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001291 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001292 CGM.DecorateInstructionWithTBAA(Load, TBAAPath,
1293 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001294 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001295
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00001296 bool NeedsBoolCheck =
1297 SanOpts.has(SanitizerKind::Bool) && hasBooleanRepresentation(Ty);
1298 bool NeedsEnumCheck =
1299 SanOpts.has(SanitizerKind::Enum) && Ty->getAs<EnumType>();
1300 if (NeedsBoolCheck || NeedsEnumCheck) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00001301 SanitizerScope SanScope(this);
Richard Smith1629da92012-12-13 07:11:50 +00001302 llvm::APInt Min, End;
1303 if (getRangeForType(*this, Ty, Min, End, true)) {
1304 --End;
1305 llvm::Value *Check;
1306 if (!Min)
1307 Check = Builder.CreateICmpULE(
1308 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1309 else {
1310 llvm::Value *Upper = Builder.CreateICmpSLE(
1311 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1312 llvm::Value *Lower = Builder.CreateICmpSGE(
1313 Load, llvm::ConstantInt::get(getLLVMContext(), Min));
1314 Check = Builder.CreateAnd(Upper, Lower);
1315 }
Nick Lewycky2d84e842013-10-02 02:29:49 +00001316 llvm::Constant *StaticArgs[] = {
1317 EmitCheckSourceLocation(Loc),
1318 EmitCheckTypeDescriptor(Ty)
1319 };
Peter Collingbourne3eea6772015-05-11 21:39:14 +00001320 SanitizerMask Kind = NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
Alexey Samsonove396bfc2014-11-11 22:03:54 +00001321 EmitCheck(std::make_pair(Check, Kind), "load_invalid_value", StaticArgs,
1322 EmitCheckValue(Load));
Richard Smith1629da92012-12-13 07:11:50 +00001323 }
1324 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001325 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1326 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001327
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001328 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001329}
1330
John McCall3a7f6922010-10-27 20:58:56 +00001331llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1332 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001333 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001334 // This should really always be an i1, but sometimes it's already
1335 // an i8, and it's awkward to track those cases down.
1336 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001337 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1338 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1339 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001340 }
1341
1342 return Value;
1343}
1344
1345llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1346 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001347 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001348 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1349 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001350 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1351 }
1352
1353 return Value;
1354}
1355
John McCall7f416cc2015-09-08 08:05:57 +00001356void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1357 bool Volatile, QualType Ty,
1358 AlignmentSource AlignSource,
1359 llvm::MDNode *TBAAInfo,
Manman Renc451e572013-04-04 21:53:22 +00001360 bool isInit, QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001361 uint64_t TBAAOffset,
1362 bool isNontemporal) {
Craig Topper99e79272013-07-26 05:59:26 +00001363
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001364 // Handle vectors differently to get better performance.
1365 if (Ty->isVectorType()) {
1366 llvm::Type *SrcTy = Value->getType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001367 auto *VecTy = cast<llvm::VectorType>(SrcTy);
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001368 // Handle vec3 special.
1369 if (VecTy->getNumElements() == 3) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001370 // Our source is a vec3, do a shuffle vector to make it a vec4.
Benjamin Kramer99383102015-07-28 16:25:32 +00001371 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1372 Builder.getInt32(2),
1373 llvm::UndefValue::get(Builder.getInt32Ty())};
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001374 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1375 Value = Builder.CreateShuffleVector(Value,
1376 llvm::UndefValue::get(VecTy),
1377 MaskV, "extractVec");
1378 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1379 }
John McCall7f416cc2015-09-08 08:05:57 +00001380 if (Addr.getElementType() != SrcTy) {
1381 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001382 }
1383 }
Craig Topper99e79272013-07-26 05:59:26 +00001384
John McCall3a7f6922010-10-27 20:58:56 +00001385 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001386
David Majnemera38c9f12016-05-24 16:09:25 +00001387 LValue AtomicLValue =
1388 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
David Majnemera5b195a2015-02-14 01:35:12 +00001389 if (Ty->isAtomicType() ||
David Majnemera38c9f12016-05-24 16:09:25 +00001390 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1391 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
John McCalla8ec7eb2013-03-07 21:37:17 +00001392 return;
1393 }
1394
Daniel Dunbar03816342010-08-21 02:24:36 +00001395 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001396 if (isNontemporal) {
1397 llvm::MDNode *Node =
1398 llvm::MDNode::get(Store->getContext(),
1399 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1400 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1401 }
Manman Renc451e572013-04-04 21:53:22 +00001402 if (TBAAInfo) {
1403 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1404 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001405 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001406 CGM.DecorateInstructionWithTBAA(Store, TBAAPath,
1407 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001408 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001409}
1410
David Chisnallfa35df62012-01-16 17:27:18 +00001411void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001412 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001413 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001414 lvalue.getType(), lvalue.getAlignmentSource(),
Manman Renc451e572013-04-04 21:53:22 +00001415 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001416 lvalue.getTBAAOffset(), lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001417}
1418
Mike Stump4a3999f2009-09-09 13:00:44 +00001419/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1420/// method emits the address of the lvalue, then loads the result as an rvalue,
1421/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001422RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001423 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001424 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001425 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001426 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1427 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001428 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001429 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001430 // In MRC mode, we do a load+autorelease.
1431 if (!getLangOpts().ObjCAutoRefCount) {
1432 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1433 }
1434
1435 // In ARC mode, we load retained and then consume the value.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001436 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1437 Object = EmitObjCConsumeObject(LV.getType(), Object);
1438 return RValue::get(Object);
1439 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001440
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001441 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001442 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001443
John McCalla1dee5302010-08-22 10:59:02 +00001444 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001445 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001446 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001447
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001448 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001449 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001450 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001451 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001452 "vecext"));
1453 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001454
1455 // If this is a reference to a subset of the elements of a vector, either
1456 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001457 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001458 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001459
Renato Golin230c5eb2014-05-19 18:15:42 +00001460 // Global Register variables always invoke intrinsics
1461 if (LV.isGlobalReg())
1462 return EmitLoadOfGlobalRegLValue(LV);
1463
John McCallc109a252011-11-07 03:59:57 +00001464 assert(LV.isBitField() && "Unknown LValue type!");
1465 return EmitLoadOfBitfieldLValue(LV);
Chris Lattner8394d792007-06-05 20:53:16 +00001466}
1467
John McCall55e1fbc2011-06-25 02:11:03 +00001468RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001469 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001470
Daniel Dunbar3447a022010-04-13 23:34:15 +00001471 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001472 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001473
John McCall7f416cc2015-09-08 08:05:57 +00001474 Address Ptr = LV.getBitFieldAddress();
1475 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001476
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001477 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001478 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001479 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1480 if (HighBits)
1481 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1482 if (Info.Offset + HighBits)
1483 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1484 } else {
1485 if (Info.Offset)
1486 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001487 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001488 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1489 Info.Size),
1490 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001491 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001492 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001493
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001494 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001495}
1496
Nate Begemanb699c9b2009-01-18 06:42:49 +00001497// If this is a reference to a subset of the elements of a vector, create an
1498// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001499RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001500 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1501 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001502
Nate Begemanf322eab2008-05-09 06:41:27 +00001503 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001504
1505 // If the result of the expression is a non-vector type, we must be extracting
1506 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001507 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001508 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001509 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001510 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001511 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001512 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001513
1514 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001515 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001516
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001517 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001518 for (unsigned i = 0; i != NumResultElts; ++i)
1519 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001520
Chris Lattner91c08ad2011-02-15 00:14:06 +00001521 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1522 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001523 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001524 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001525}
1526
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001527/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001528Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1529 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001530 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1531 QualType EQT = ExprVT->getElementType();
1532 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001533
John McCall7f416cc2015-09-08 08:05:57 +00001534 Address CastToPointerElement =
1535 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1536 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001537
1538 const llvm::Constant *Elts = LV.getExtVectorElts();
1539 unsigned ix = getAccessedFieldNo(0, Elts);
1540
John McCall7f416cc2015-09-08 08:05:57 +00001541 Address VectorBasePtrPlusIx =
1542 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1543 getContext().getTypeSizeInChars(EQT),
1544 "vector.elt");
1545
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001546 return VectorBasePtrPlusIx;
1547}
1548
Renato Golin230c5eb2014-05-19 18:15:42 +00001549/// @brief Load of global gamed gegisters are always calls to intrinsics.
1550RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001551 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1552 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001553 llvm::MDNode *RegName = cast<llvm::MDNode>(
1554 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001555
1556 // We accept integer and pointer types only
1557 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1558 llvm::Type *Ty = OrigTy;
1559 if (OrigTy->isPointerTy())
1560 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1561 llvm::Type *Types[] = { Ty };
1562
Renato Golin230c5eb2014-05-19 18:15:42 +00001563 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001564 llvm::Value *Call = Builder.CreateCall(
1565 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001566 if (OrigTy->isPointerTy())
1567 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001568 return RValue::get(Call);
1569}
Chris Lattner40ff7012007-08-03 16:18:34 +00001570
Chris Lattner9369a562007-06-29 16:31:29 +00001571
Chris Lattner8394d792007-06-05 20:53:16 +00001572/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1573/// lvalue, where both are guaranteed to the have the same type, and that type
1574/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001575void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001576 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001577 if (!Dst.isSimple()) {
1578 if (Dst.isVectorElt()) {
1579 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001580 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1581 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001582 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001583 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001584 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1585 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001586 return;
1587 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001588
Nate Begemance4d7fc2008-04-18 23:10:10 +00001589 // If this is an update of extended vector elements, insert them as
1590 // appropriate.
1591 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001592 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001593
Renato Golin230c5eb2014-05-19 18:15:42 +00001594 if (Dst.isGlobalReg())
1595 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1596
John McCallc109a252011-11-07 03:59:57 +00001597 assert(Dst.isBitField() && "Unknown LValue type");
1598 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001599 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001600
John McCall31168b02011-06-15 23:02:42 +00001601 // There's special magic for assigning into an ARC-qualified l-value.
1602 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1603 switch (Lifetime) {
1604 case Qualifiers::OCL_None:
1605 llvm_unreachable("present but none");
1606
1607 case Qualifiers::OCL_ExplicitNone:
1608 // nothing special
1609 break;
1610
1611 case Qualifiers::OCL_Strong:
John McCall55e1fbc2011-06-25 02:11:03 +00001612 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001613 return;
1614
1615 case Qualifiers::OCL_Weak:
1616 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1617 return;
1618
1619 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001620 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1621 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001622 // fall into the normal path
1623 break;
1624 }
1625 }
1626
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001627 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001628 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001629 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001630 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001631 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001632 return;
1633 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001634
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001635 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001636 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001637 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001638 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001639 if (Dst.isObjCIvar()) {
1640 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001641 llvm::Type *ResultType = IntPtrTy;
1642 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1643 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001644 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001645 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001646 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1647 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001648 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001649 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001650 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001651 } else if (Dst.isGlobalObjCRef()) {
1652 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1653 Dst.isThreadLocalRef());
1654 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001655 else
1656 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001657 return;
1658 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001659
Chris Lattner6278e6a2007-08-11 00:04:45 +00001660 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001661 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001662}
1663
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001664void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001665 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001666 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001667 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001668 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001669
Daniel Dunbar67aba792010-04-15 03:47:33 +00001670 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001671 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001672
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001673 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001674 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001675 /*IsSigned=*/false);
1676 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001677
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001678 // See if there are other bits in the bitfield's storage we'll need to load
1679 // and mask together with source before storing.
1680 if (Info.StorageSize != Info.Size) {
1681 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001682 llvm::Value *Val =
1683 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001684
1685 // Mask the source value as needed.
1686 if (!hasBooleanRepresentation(Dst.getType()))
1687 SrcVal = Builder.CreateAnd(SrcVal,
1688 llvm::APInt::getLowBitsSet(Info.StorageSize,
1689 Info.Size),
1690 "bf.value");
1691 MaskedVal = SrcVal;
1692 if (Info.Offset)
1693 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1694
1695 // Mask out the original value.
1696 Val = Builder.CreateAnd(Val,
1697 ~llvm::APInt::getBitsSet(Info.StorageSize,
1698 Info.Offset,
1699 Info.Offset + Info.Size),
1700 "bf.clear");
1701
1702 // Or together the unchanged values and the source value.
1703 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1704 } else {
1705 assert(Info.Offset == 0);
1706 }
1707
1708 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001709 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001710
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001711 // Return the new value of the bit-field, if requested.
1712 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001713 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001714
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001715 // Sign extend the value if needed.
1716 if (Info.IsSigned) {
1717 assert(Info.Size <= Info.StorageSize);
1718 unsigned HighBits = Info.StorageSize - Info.Size;
1719 if (HighBits) {
1720 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1721 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1722 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001723 }
1724
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001725 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1726 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001727 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001728 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001729}
1730
Nate Begemance4d7fc2008-04-18 23:10:10 +00001731void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001732 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001733 // This access turns into a read/modify/write of the vector. Load the input
1734 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001735 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1736 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001737 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001738
Chris Lattner4647a212007-08-31 22:49:20 +00001739 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001740
John McCall55e1fbc2011-06-25 02:11:03 +00001741 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001742 unsigned NumSrcElts = VTy->getNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001743 unsigned NumDstElts =
1744 cast<llvm::VectorType>(Vec->getType())->getNumElements();
1745 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001746 // Use shuffle vector is the src and destination are the same number of
1747 // elements and restore the vector mask since it is on the side it will be
1748 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001749 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001750 for (unsigned i = 0; i != NumSrcElts; ++i)
1751 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001752
Chris Lattner91c08ad2011-02-15 00:14:06 +00001753 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001754 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001755 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001756 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001757 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001758 // Extended the source vector to the same length and then shuffle it
1759 // into the destination.
1760 // FIXME: since we're shuffling with undef, can we just use the indices
1761 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001762 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001763 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001764 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001765 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001766 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001767 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001768 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001769 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001770 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001771 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001772 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001773 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001774 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001775
Joey Goulycf4143b2013-11-21 17:09:05 +00001776 // When the vector size is odd and .odd or .hi is used, the last element
1777 // of the Elts constant array will be one past the size of the vector.
1778 // Ignore the last element here, if it is greater than the mask size.
1779 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1780 NumSrcElts--;
1781
Nate Begemanb699c9b2009-01-18 06:42:49 +00001782 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001783 for (unsigned i = 0; i != NumSrcElts; ++i)
1784 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001785 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001786 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001787 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001788 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001789 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001790 }
1791 } else {
1792 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001793 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001794 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001795 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001796 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001797
John McCall7f416cc2015-09-08 08:05:57 +00001798 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1799 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001800}
1801
Renato Golin230c5eb2014-05-19 18:15:42 +00001802/// @brief Store of global named registers are always calls to intrinsics.
1803void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001804 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1805 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001806 llvm::MDNode *RegName = cast<llvm::MDNode>(
1807 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00001808 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00001809
1810 // We accept integer and pointer types only
1811 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1812 llvm::Type *Ty = OrigTy;
1813 if (OrigTy->isPointerTy())
1814 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1815 llvm::Type *Types[] = { Ty };
1816
Renato Golin230c5eb2014-05-19 18:15:42 +00001817 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1818 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00001819 if (OrigTy->isPointerTy())
1820 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00001821 Builder.CreateCall(
1822 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00001823}
1824
Eric Christopherc9e2a682014-05-20 17:10:39 +00001825// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001826// generating write-barries API. It is currently a global, ivar,
1827// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001828static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001829 LValue &LV,
1830 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001831 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001832 return;
Craig Topper99e79272013-07-26 05:59:26 +00001833
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001834 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001835 QualType ExpTy = E->getType();
1836 if (IsMemberAccess && ExpTy->isPointerType()) {
1837 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00001838 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001839 // writer-barrier conservatively.
1840 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1841 if (ExpTy->isRecordType()) {
1842 LV.setObjCIvar(false);
1843 return;
1844 }
1845 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001846 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001847 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001848 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001849 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001850 return;
1851 }
Craig Topper99e79272013-07-26 05:59:26 +00001852
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001853 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1854 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001855 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001856 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00001857 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001858 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001859 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001860 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001861 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001862 }
Craig Topper99e79272013-07-26 05:59:26 +00001863
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001864 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001865 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001866 return;
1867 }
Craig Topper99e79272013-07-26 05:59:26 +00001868
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001869 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001870 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001871 if (LV.isObjCIvar()) {
1872 // If cast is to a structure pointer, follow gcc's behavior and make it
1873 // a non-ivar write-barrier.
1874 QualType ExpTy = E->getType();
1875 if (ExpTy->isPointerType())
1876 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1877 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00001878 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001879 }
1880 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001881 }
Peter Collingbourne91147592011-04-15 00:35:48 +00001882
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001883 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001884 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1885 return;
1886 }
1887
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001888 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001889 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001890 return;
1891 }
Craig Topper99e79272013-07-26 05:59:26 +00001892
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001893 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001894 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001895 return;
1896 }
John McCall31168b02011-06-15 23:02:42 +00001897
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001898 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001899 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00001900 return;
1901 }
1902
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001903 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001904 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00001905 if (LV.isObjCIvar() && !LV.isObjCArray())
1906 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001907 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00001908 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001909 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00001910 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001911 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001912 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001913 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001914 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001915
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001916 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001917 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001918 // We don't know if member is an 'ivar', but this flag is looked at
1919 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001920 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001921 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001922 }
1923}
1924
Chris Lattner3f32d692011-07-12 06:52:18 +00001925static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00001926EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00001927 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001928 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00001929 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00001930 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00001931}
1932
Alexey Bataev97720002014-11-11 04:05:39 +00001933static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00001934 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
1935 llvm::Type *RealVarTy, SourceLocation Loc) {
1936 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
1937 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
1938 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
1939}
1940
1941Address CodeGenFunction::EmitLoadOfReference(Address Addr,
1942 const ReferenceType *RefTy,
1943 AlignmentSource *Source) {
1944 llvm::Value *Ptr = Builder.CreateLoad(Addr);
1945 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
1946 Source, /*forPointee*/ true));
1947
1948}
1949
1950LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
1951 const ReferenceType *RefTy) {
1952 AlignmentSource Source;
1953 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &Source);
1954 return MakeAddrLValue(Addr, RefTy->getPointeeType(), Source);
Alexey Bataev97720002014-11-11 04:05:39 +00001955}
1956
Alexey Bataev31300ed2016-02-04 11:27:03 +00001957Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
1958 const PointerType *PtrTy,
1959 AlignmentSource *Source) {
1960 llvm::Value *Addr = Builder.CreateLoad(Ptr);
1961 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(), Source,
1962 /*forPointeeType=*/true));
1963}
1964
1965LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
1966 const PointerType *PtrTy) {
1967 AlignmentSource Source;
1968 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &Source);
1969 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), Source);
1970}
1971
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001972static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1973 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00001974 QualType T = E->getType();
1975
1976 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00001977 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1978 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00001979 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
1980
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001981 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001982 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
1983 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00001984 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00001985 Address Addr(V, Alignment);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001986 LValue LV;
Alexey Bataev97720002014-11-11 04:05:39 +00001987 // Emit reference to the private copy of the variable if it is an OpenMP
1988 // threadprivate variable.
1989 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001990 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001991 E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001992 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
1993 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001994 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001995 LV = CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001996 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001997 setObjCGCLValueClass(CGF.getContext(), E, LV);
1998 return LV;
1999}
2000
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002001static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
Chris Lattner13ee4f42011-07-10 05:34:54 +00002002 const Expr *E, const FunctionDecl *FD) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00002003 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002004 if (!FD->hasPrototype()) {
2005 if (const FunctionProtoType *Proto =
2006 FD->getType()->getAs<FunctionProtoType>()) {
2007 // Ugly case: for a K&R-style definition, the type of the definition
2008 // isn't the same as the type of a use. Correct for this with a
2009 // bitcast.
2010 QualType NoProtoType =
Alp Toker314cc812014-01-25 16:55:45 +00002011 CGF.getContext().getFunctionNoProtoType(Proto->getReturnType());
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002012 NoProtoType = CGF.getContext().getPointerType(NoProtoType);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002013 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002014 }
2015 }
Eli Friedmana0544d62011-12-03 04:14:32 +00002016 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
John McCall7f416cc2015-09-08 08:05:57 +00002017 return CGF.MakeAddrLValue(V, E->getType(), Alignment, AlignmentSource::Decl);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002018}
2019
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00002020static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2021 llvm::Value *ThisValue) {
2022 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2023 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2024 return CGF.EmitLValueForField(LV, FD);
2025}
2026
Renato Golin230c5eb2014-05-19 18:15:42 +00002027/// Named Registers are named metadata pointing to the register name
2028/// which will be read from/written to as an argument to the intrinsic
2029/// @llvm.read/write_register.
2030/// So far, only the name is being passed down, but other options such as
2031/// register type, allocation type or even optimization options could be
2032/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002033static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002034 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002035 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002036 assert(Asm->getLabel().size() < 64-Name.size() &&
2037 "Register name too big");
2038 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002039 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002040 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002041 if (M->getNumOperands() == 0) {
2042 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2043 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002044 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002045 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2046 }
John McCall7f416cc2015-09-08 08:05:57 +00002047
2048 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2049
2050 llvm::Value *Ptr =
2051 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2052 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002053}
2054
Chris Lattnerd7f58862007-06-02 05:24:33 +00002055LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002056 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002057 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002058
Renato Goline7b3d5d2014-05-27 16:46:27 +00002059 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2060 // Global Named registers access via intrinsics only
2061 if (VD->getStorageClass() == SC_Register &&
2062 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002063 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002064
Renato Goline7b3d5d2014-05-27 16:46:27 +00002065 // A DeclRefExpr for a reference initialized by a constant expression can
2066 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002067 const Expr *Init = VD->getAnyInitializer(VD);
2068 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2069 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002070 VD->checkInitIsICE() &&
2071 // Do not emit if it is private OpenMP variable.
2072 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2073 LocalDeclMap.count(VD))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002074 llvm::Constant *Val =
2075 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2076 assert(Val && "failed to emit reference constant expression");
2077 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002078
2079 // Should we be using the alignment of the constant pointer we emitted?
2080 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2081 /*pointee*/ true);
2082
2083 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
Richard Smith5a1104b2012-10-20 01:38:33 +00002084 }
David Majnemer602cfe72015-01-01 09:49:44 +00002085
2086 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002087 if (E->refersToEnclosingVariableOrCapture()) {
David Majnemer602cfe72015-01-01 09:49:44 +00002088 if (auto *FD = LambdaCaptureFields.lookup(VD))
2089 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2090 else if (CapturedStmtInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002091 auto it = LocalDeclMap.find(VD);
2092 if (it != LocalDeclMap.end()) {
2093 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2094 return EmitLoadOfReferenceLValue(it->second, RefTy);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002095 }
John McCall7f416cc2015-09-08 08:05:57 +00002096 return MakeAddrLValue(it->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002097 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002098 LValue CapLVal =
2099 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2100 CapturedStmtInfo->getContextValue());
2101 return MakeAddrLValue(
2102 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2103 CapLVal.getType(), AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002104 }
John McCall7f416cc2015-09-08 08:05:57 +00002105
David Majnemer602cfe72015-01-01 09:49:44 +00002106 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002107 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2108 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002109 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002110 }
2111
Eli Friedman5720e342012-01-21 04:52:58 +00002112 // FIXME: We should be able to assert this for FunctionDecls as well!
2113 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2114 // those with a valid source location.
2115 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2116 !E->getLocation().isValid()) &&
2117 "Should not use decl without marking it used!");
2118
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002119 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002120 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002121 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2122 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002123 }
2124
Renato Goline7b3d5d2014-05-27 16:46:27 +00002125 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002126 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002127 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002128 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002129
John McCall7f416cc2015-09-08 08:05:57 +00002130 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002131
John McCall7f416cc2015-09-08 08:05:57 +00002132 // The variable should generally be present in the local decl map.
2133 auto iter = LocalDeclMap.find(VD);
2134 if (iter != LocalDeclMap.end()) {
2135 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002136
John McCall7f416cc2015-09-08 08:05:57 +00002137 // Otherwise, it might be static local we haven't emitted yet for
2138 // some reason; most likely, because it's in an outer function.
2139 } else if (VD->isStaticLocal()) {
2140 addr = Address(CGM.getOrCreateStaticVarDecl(
2141 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2142 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002143
John McCall7f416cc2015-09-08 08:05:57 +00002144 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002145 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002146 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2147 }
2148
2149
2150 // Check for OpenMP threadprivate variables.
2151 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2152 return EmitThreadPrivateVarDeclLValue(
2153 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2154 E->getExprLoc());
2155 }
2156
2157 // Drill into block byref variables.
2158 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2159 if (isBlockByref) {
2160 addr = emitBlockByrefAddress(addr, VD);
2161 }
2162
2163 // Drill into reference types.
2164 LValue LV;
2165 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2166 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2167 } else {
2168 LV = MakeAddrLValue(addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002169 }
Chris Lattner3f32d692011-07-12 06:52:18 +00002170
John McCallcdda29c2013-03-13 03:10:54 +00002171 bool isLocalStorage = VD->hasLocalStorage();
2172
2173 bool NonGCable = isLocalStorage &&
2174 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002175 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002176 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002177 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002178 LV.setNonGC(true);
2179 }
John McCallcdda29c2013-03-13 03:10:54 +00002180
2181 bool isImpreciseLifetime =
2182 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2183 if (isImpreciseLifetime)
2184 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002185 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002186 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002187 }
John McCallf3a88602011-02-03 08:15:49 +00002188
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002189 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002190 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002191
David Blaikie83d382b2011-09-23 05:06:16 +00002192 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002193}
Chris Lattnere47e4402007-06-01 18:02:12 +00002194
Chris Lattner8394d792007-06-05 20:53:16 +00002195LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2196 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002197 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002198 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002199
Chris Lattner0f398c42008-07-26 22:37:01 +00002200 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002201 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002202 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002203 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002204 QualType T = E->getSubExpr()->getType()->getPointeeType();
2205 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002206
John McCall7f416cc2015-09-08 08:05:57 +00002207 AlignmentSource AlignSource;
2208 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &AlignSource);
2209 LValue LV = MakeAddrLValue(Addr, T, AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002210 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002211
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002212 // We should not generate __weak write barrier on indirect reference
2213 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2214 // But, we continue to generate __strong write barrier on indirect write
2215 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002216 if (getLangOpts().ObjC1 &&
2217 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002218 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002219 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002220 return LV;
2221 }
John McCalle3027922010-08-25 11:45:40 +00002222 case UO_Real:
2223 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002224 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002225 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002226
Richard Smith0b6b8e42012-02-18 20:53:32 +00002227 // __real is valid on scalars. This is a faster way of testing that.
2228 // __imag can only produce an rvalue on scalars.
2229 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002230 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002231 assert(E->getSubExpr()->getType()->isArithmeticType());
2232 return LV;
2233 }
2234
2235 assert(E->getSubExpr()->getType()->isAnyComplexType());
2236
John McCall7f416cc2015-09-08 08:05:57 +00002237 Address Component =
2238 (E->getOpcode() == UO_Real
2239 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2240 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
2241 return MakeAddrLValue(Component, ExprTy, LV.getAlignmentSource());
Chris Lattner595db862007-10-30 22:53:42 +00002242 }
John McCalle3027922010-08-25 11:45:40 +00002243 case UO_PreInc:
2244 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002245 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002246 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002247
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002248 if (E->getType()->isAnyComplexType())
2249 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2250 else
2251 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2252 return LV;
2253 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002254 }
Chris Lattner8394d792007-06-05 20:53:16 +00002255}
2256
Chris Lattner4347e3692007-06-06 04:54:52 +00002257LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002258 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
John McCall7f416cc2015-09-08 08:05:57 +00002259 E->getType(), AlignmentSource::Decl);
Chris Lattner4347e3692007-06-06 04:54:52 +00002260}
2261
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002262LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002263 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
John McCall7f416cc2015-09-08 08:05:57 +00002264 E->getType(), AlignmentSource::Decl);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002265}
2266
Mike Stump4a3999f2009-09-09 13:00:44 +00002267LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002268 auto SL = E->getFunctionName();
2269 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2270 StringRef FnName = CurFn->getName();
2271 if (FnName.startswith("\01"))
2272 FnName = FnName.substr(1);
2273 StringRef NameItems[] = {
2274 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2275 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002276 if (CurCodeDecl && isa<BlockDecl>(CurCodeDecl)) {
John McCall7f416cc2015-09-08 08:05:57 +00002277 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2278 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002279 }
Alexey Bataevec474782014-10-09 08:45:04 +00002280 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
John McCall7f416cc2015-09-08 08:05:57 +00002281 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002282}
2283
Richard Smithe30752c2012-10-09 19:52:38 +00002284/// Emit a type description suitable for use by a runtime sanitizer library. The
2285/// format of a type descriptor is
2286///
2287/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002288/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002289/// \endcode
2290///
Richard Smith683398a2012-10-09 23:55:19 +00002291/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2292/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002293llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002294 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002295 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002296 return C;
2297
Richard Smithe30752c2012-10-09 19:52:38 +00002298 uint16_t TypeKind = -1;
2299 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002300
Richard Smithe30752c2012-10-09 19:52:38 +00002301 if (T->isIntegerType()) {
2302 TypeKind = 0;
2303 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002304 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002305 } else if (T->isFloatingType()) {
2306 TypeKind = 1;
2307 TypeInfo = getContext().getTypeSize(T);
2308 }
2309
2310 // Format the type name as if for a diagnostic, including quotes and
2311 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002312 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002313 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2314 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002315 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002316 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002317
2318 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002319 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2320 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002321 };
2322 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2323
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002324 auto *GV = new llvm::GlobalVariable(
2325 CGM.getModule(), Descriptor->getType(),
2326 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Richard Smithe30752c2012-10-09 19:52:38 +00002327 GV->setUnnamedAddr(true);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002328 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002329
2330 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002331 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002332
Richard Smithe30752c2012-10-09 19:52:38 +00002333 return GV;
2334}
2335
2336llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2337 llvm::Type *TargetTy = IntPtrTy;
2338
Richard Smith48366f72013-03-22 00:47:07 +00002339 // Floating-point types which fit into intptr_t are bitcast to integers
2340 // and then passed directly (after zero-extension, if necessary).
2341 if (V->getType()->isFloatingPointTy()) {
2342 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2343 if (Bits <= TargetTy->getIntegerBitWidth())
2344 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2345 Bits));
2346 }
2347
Richard Smithe30752c2012-10-09 19:52:38 +00002348 // Integers which fit in intptr_t are zero-extended and passed directly.
2349 if (V->getType()->isIntegerTy() &&
2350 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2351 return Builder.CreateZExt(V, TargetTy);
2352
2353 // Pointers are passed directly, everything else is passed by address.
2354 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002355 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002356 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002357 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002358 }
2359 return Builder.CreatePtrToInt(V, TargetTy);
2360}
2361
2362/// \brief Emit a representation of a SourceLocation for passing to a handler
2363/// in a sanitizer runtime library. The format for this data is:
2364/// \code
2365/// struct SourceLocation {
2366/// const char *Filename;
2367/// int32_t Line, Column;
2368/// };
2369/// \endcode
2370/// For an invalid SourceLocation, the Filename pointer is null.
2371llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002372 llvm::Constant *Filename;
2373 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002374
Alexey Samsonov6c124142014-07-18 17:50:06 +00002375 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2376 if (PLoc.isValid()) {
Filipe Cabecinhasab731f72016-05-12 16:51:36 +00002377 StringRef FilenameString = PLoc.getFilename();
2378
2379 int PathComponentsToStrip =
2380 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2381 if (PathComponentsToStrip < 0) {
2382 assert(PathComponentsToStrip != INT_MIN);
2383 int PathComponentsToKeep = -PathComponentsToStrip;
2384 auto I = llvm::sys::path::rbegin(FilenameString);
2385 auto E = llvm::sys::path::rend(FilenameString);
2386 while (I != E && --PathComponentsToKeep)
2387 ++I;
2388
2389 FilenameString = FilenameString.substr(I - E);
2390 } else if (PathComponentsToStrip > 0) {
2391 auto I = llvm::sys::path::begin(FilenameString);
2392 auto E = llvm::sys::path::end(FilenameString);
2393 while (I != E && PathComponentsToStrip--)
2394 ++I;
2395
2396 if (I != E)
2397 FilenameString =
2398 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2399 else
2400 FilenameString = llvm::sys::path::filename(FilenameString);
2401 }
2402
2403 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002404 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2405 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2406 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002407 Line = PLoc.getLine();
2408 Column = PLoc.getColumn();
2409 } else {
2410 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2411 Line = Column = 0;
2412 }
2413
2414 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2415 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002416
2417 return llvm::ConstantStruct::getAnon(Data);
2418}
2419
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002420namespace {
2421/// \brief Specify under what conditions this check can be recovered
2422enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002423 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002424 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002425 /// Check supports recovering, runtime has both fatal (noreturn) and
2426 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002427 Recoverable,
2428 /// Runtime conditionally aborts, always need to support recovery.
2429 AlwaysRecoverable
2430};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002431}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002432
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002433static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2434 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002435 switch (Kind) {
2436 case SanitizerKind::Vptr:
2437 return CheckRecoverableKind::AlwaysRecoverable;
2438 case SanitizerKind::Return:
2439 case SanitizerKind::Unreachable:
2440 return CheckRecoverableKind::Unrecoverable;
2441 default:
2442 return CheckRecoverableKind::Recoverable;
2443 }
2444}
2445
Alexey Samsonov88459522015-01-12 22:39:12 +00002446static void emitCheckHandlerCall(CodeGenFunction &CGF,
2447 llvm::FunctionType *FnType,
2448 ArrayRef<llvm::Value *> FnArgs,
2449 StringRef CheckName,
2450 CheckRecoverableKind RecoverKind, bool IsFatal,
2451 llvm::BasicBlock *ContBB) {
2452 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2453 bool NeedsAbortSuffix =
2454 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2455 std::string FnName = ("__ubsan_handle_" + CheckName +
2456 (NeedsAbortSuffix ? "_abort" : "")).str();
2457 bool MayReturn =
2458 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2459
2460 llvm::AttrBuilder B;
2461 if (!MayReturn) {
2462 B.addAttribute(llvm::Attribute::NoReturn)
2463 .addAttribute(llvm::Attribute::NoUnwind);
2464 }
2465 B.addAttribute(llvm::Attribute::UWTable);
2466
2467 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2468 FnType, FnName,
2469 llvm::AttributeSet::get(CGF.getLLVMContext(),
2470 llvm::AttributeSet::FunctionIndex, B));
2471 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2472 if (!MayReturn) {
2473 HandlerCall->setDoesNotReturn();
2474 CGF.Builder.CreateUnreachable();
2475 } else {
2476 CGF.Builder.CreateBr(ContBB);
2477 }
2478}
2479
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002480void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002481 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002482 StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
2483 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002484 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002485 assert(Checked.size() > 0);
Alexey Samsonov88459522015-01-12 22:39:12 +00002486
2487 llvm::Value *FatalCond = nullptr;
2488 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002489 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002490 for (int i = 0, n = Checked.size(); i < n; ++i) {
2491 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002492 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002493 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002494 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2495 ? TrapCond
2496 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2497 ? RecoverableCond
2498 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002499 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2500 }
2501
Peter Collingbourne9881b782015-06-18 23:59:22 +00002502 if (TrapCond)
2503 EmitTrapCheck(TrapCond);
2504 if (!FatalCond && !RecoverableCond)
2505 return;
2506
Alexey Samsonov88459522015-01-12 22:39:12 +00002507 llvm::Value *JointCond;
2508 if (FatalCond && RecoverableCond)
2509 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2510 else
2511 JointCond = FatalCond ? FatalCond : RecoverableCond;
2512 assert(JointCond);
2513
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002514 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002515 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002516#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002517 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002518 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002519 "All recoverable kinds in a single check must be same!");
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002520 assert(SanOpts.has(Checked[i].second));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002521 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002522#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002523
Richard Smith4d1458e2012-09-08 02:08:36 +00002524 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002525 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2526 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002527 // Give hint that we very much don't expect to execute the handler
2528 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2529 llvm::MDBuilder MDHelper(getLLVMContext());
2530 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2531 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002532 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002533
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002534 // Handler functions take an i8* pointing to the (handler-specific) static
2535 // information block, followed by a sequence of intptr_t arguments
2536 // representing operand values.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002537 SmallVector<llvm::Value *, 4> Args;
2538 SmallVector<llvm::Type *, 4> ArgTypes;
Richard Smithe30752c2012-10-09 19:52:38 +00002539 Args.reserve(DynamicArgs.size() + 1);
2540 ArgTypes.reserve(DynamicArgs.size() + 1);
2541
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002542 // Emit handler arguments and create handler function type.
2543 if (!StaticArgs.empty()) {
2544 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2545 auto *InfoPtr =
2546 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2547 llvm::GlobalVariable::PrivateLinkage, Info);
2548 InfoPtr->setUnnamedAddr(true);
2549 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2550 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2551 ArgTypes.push_back(Int8PtrTy);
2552 }
2553
Richard Smithe30752c2012-10-09 19:52:38 +00002554 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2555 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2556 ArgTypes.push_back(IntPtrTy);
2557 }
2558
2559 llvm::FunctionType *FnType =
2560 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002561
Alexey Samsonov88459522015-01-12 22:39:12 +00002562 if (!FatalCond || !RecoverableCond) {
2563 // Simple case: we need to generate a single handler call, either
2564 // fatal, or non-fatal.
2565 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind,
2566 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002567 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002568 // Emit two handler calls: first one for set of unrecoverable checks,
2569 // another one for recoverable.
2570 llvm::BasicBlock *NonFatalHandlerBB =
2571 createBasicBlock("non_fatal." + CheckName);
2572 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2573 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2574 EmitBlock(FatalHandlerBB);
2575 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, true,
2576 NonFatalHandlerBB);
2577 EmitBlock(NonFatalHandlerBB);
2578 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, false,
2579 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002580 }
Richard Smithe30752c2012-10-09 19:52:38 +00002581
Richard Smith4d1458e2012-09-08 02:08:36 +00002582 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002583}
2584
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002585void CodeGenFunction::EmitCfiSlowPathCheck(
2586 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2587 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002588 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2589
2590 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2591 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2592
2593 llvm::MDBuilder MDHelper(getLLVMContext());
2594 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2595 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2596
2597 EmitBlock(CheckBB);
2598
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002599 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2600
2601 llvm::CallInst *CheckCall;
2602 if (WithDiag) {
2603 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2604 auto *InfoPtr =
2605 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2606 llvm::GlobalVariable::PrivateLinkage, Info);
2607 InfoPtr->setUnnamedAddr(true);
2608 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2609
2610 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2611 "__cfi_slowpath_diag",
2612 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2613 false));
2614 CheckCall = Builder.CreateCall(
2615 SlowPathDiagFn,
2616 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2617 } else {
2618 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2619 "__cfi_slowpath",
2620 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2621 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2622 }
2623
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002624 CheckCall->setDoesNotThrow();
2625
2626 EmitBlock(Cont);
2627}
2628
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002629// This function is basically a switch over the CFI failure kind, which is
2630// extracted from CFICheckFailData (1st function argument). Each case is either
2631// llvm.trap or a call to one of the two runtime handlers, based on
2632// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2633// failure kind) traps, but this should really never happen. CFICheckFailData
2634// can be nullptr if the calling module has -fsanitize-trap behavior for this
2635// check kind; in this case __cfi_check_fail traps as well.
2636void CodeGenFunction::EmitCfiCheckFail() {
2637 SanitizerScope SanScope(this);
2638 FunctionArgList Args;
2639 ImplicitParamDecl ArgData(getContext(), nullptr, SourceLocation(), nullptr,
2640 getContext().VoidPtrTy);
2641 ImplicitParamDecl ArgAddr(getContext(), nullptr, SourceLocation(), nullptr,
2642 getContext().VoidPtrTy);
2643 Args.push_back(&ArgData);
2644 Args.push_back(&ArgAddr);
2645
John McCallc56a8b32016-03-11 04:30:31 +00002646 const CGFunctionInfo &FI =
2647 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002648
2649 llvm::Function *F = llvm::Function::Create(
2650 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2651 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2652 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2653
2654 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2655 SourceLocation());
2656
2657 llvm::Value *Data =
2658 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2659 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2660 llvm::Value *Addr =
2661 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2662 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2663
2664 // Data == nullptr means the calling module has trap behaviour for this check.
2665 llvm::Value *DataIsNotNullPtr =
2666 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2667 EmitTrapCheck(DataIsNotNullPtr);
2668
2669 llvm::StructType *SourceLocationTy =
2670 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty, nullptr);
2671 llvm::StructType *CfiCheckFailDataTy =
2672 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy, nullptr);
2673
2674 llvm::Value *V = Builder.CreateConstGEP2_32(
2675 CfiCheckFailDataTy,
2676 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2677 0);
2678 Address CheckKindAddr(V, getIntAlign());
2679 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2680
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002681 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2682 CGM.getLLVMContext(),
2683 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2684 llvm::Value *ValidVtable = Builder.CreateZExt(
2685 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::bitset_test),
2686 {Addr, AllVtables}),
2687 IntPtrTy);
2688
Evgeniy Stepanov4d3b0872016-01-25 23:45:37 +00002689 const std::pair<int, SanitizerMask> CheckKinds[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002690 {CFITCK_VCall, SanitizerKind::CFIVCall},
2691 {CFITCK_NVCall, SanitizerKind::CFINVCall},
2692 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
2693 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
2694 {CFITCK_ICall, SanitizerKind::CFIICall}};
2695
2696 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
2697 for (auto CheckKindMaskPair : CheckKinds) {
2698 int Kind = CheckKindMaskPair.first;
2699 SanitizerMask Mask = CheckKindMaskPair.second;
2700 llvm::Value *Cond =
2701 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002702 if (CGM.getLangOpts().Sanitize.has(Mask))
2703 EmitCheck(std::make_pair(Cond, Mask), "cfi_check_fail", {},
2704 {Data, Addr, ValidVtable});
2705 else
2706 EmitTrapCheck(Cond);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002707 }
2708
2709 FinishFunction();
2710 // The only reference to this function will be created during LTO link.
2711 // Make sure it survives until then.
2712 CGM.addUsedGlobal(F);
2713}
2714
Chad Rosierae229d52013-01-29 23:31:22 +00002715void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00002716 llvm::BasicBlock *Cont = createBasicBlock("cont");
2717
2718 // If we're optimizing, collapse all calls to trap down to just one per
2719 // function to save on code size.
2720 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2721 TrapBB = createBasicBlock("trap");
2722 Builder.CreateCondBr(Checked, Cont, TrapBB);
2723 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002724 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00002725 TrapCall->setDoesNotReturn();
2726 TrapCall->setDoesNotThrow();
2727 Builder.CreateUnreachable();
2728 } else {
2729 Builder.CreateCondBr(Checked, Cont, TrapBB);
2730 }
2731
2732 EmitBlock(Cont);
2733}
2734
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002735llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00002736 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002737
2738 if (!CGM.getCodeGenOpts().TrapFuncName.empty())
2739 TrapCall->addAttribute(llvm::AttributeSet::FunctionIndex,
2740 "trap-func-name",
2741 CGM.getCodeGenOpts().TrapFuncName);
2742
2743 return TrapCall;
2744}
2745
John McCall7f416cc2015-09-08 08:05:57 +00002746Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
2747 AlignmentSource *AlignSource) {
2748 assert(E->getType()->isArrayType() &&
2749 "Array to pointer decay must have array source type!");
2750
2751 // Expressions of array type can't be bitfields or vector elements.
2752 LValue LV = EmitLValue(E);
2753 Address Addr = LV.getAddress();
2754 if (AlignSource) *AlignSource = LV.getAlignmentSource();
2755
2756 // If the array type was an incomplete type, we need to make sure
2757 // the decay ends up being the right type.
2758 llvm::Type *NewTy = ConvertType(E->getType());
2759 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2760
2761 // Note that VLA pointers are always decayed, so we don't need to do
2762 // anything here.
2763 if (!E->getType()->isVariableArrayType()) {
2764 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2765 "Expected pointer to array");
2766 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2767 }
2768
2769 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2770 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2771}
2772
Chris Lattner6c5abe82010-06-26 23:03:20 +00002773/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2774/// array to pointer, return the array subexpression.
2775static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2776 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002777 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00002778 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00002779 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002780
Chris Lattner6c5abe82010-06-26 23:03:20 +00002781 // If this is a decay from variable width array, bail out.
2782 const Expr *SubExpr = CE->getSubExpr();
2783 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00002784 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002785
Chris Lattner6c5abe82010-06-26 23:03:20 +00002786 return SubExpr;
2787}
2788
John McCall7f416cc2015-09-08 08:05:57 +00002789static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
2790 llvm::Value *ptr,
2791 ArrayRef<llvm::Value*> indices,
2792 bool inbounds,
2793 const llvm::Twine &name = "arrayidx") {
2794 if (inbounds) {
2795 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name);
2796 } else {
2797 return CGF.Builder.CreateGEP(ptr, indices, name);
2798 }
2799}
2800
2801static CharUnits getArrayElementAlign(CharUnits arrayAlign,
2802 llvm::Value *idx,
2803 CharUnits eltSize) {
2804 // If we have a constant index, we can use the exact offset of the
2805 // element we're accessing.
2806 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
2807 CharUnits offset = constantIdx->getZExtValue() * eltSize;
2808 return arrayAlign.alignmentAtOffset(offset);
2809
2810 // Otherwise, use the worst-case alignment for any element.
2811 } else {
2812 return arrayAlign.alignmentOfArrayElement(eltSize);
2813 }
2814}
2815
2816static QualType getFixedSizeElementType(const ASTContext &ctx,
2817 const VariableArrayType *vla) {
2818 QualType eltType;
2819 do {
2820 eltType = vla->getElementType();
2821 } while ((vla = ctx.getAsVariableArrayType(eltType)));
2822 return eltType;
2823}
2824
2825static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
2826 ArrayRef<llvm::Value*> indices,
2827 QualType eltType, bool inbounds,
2828 const llvm::Twine &name = "arrayidx") {
2829 // All the indices except that last must be zero.
2830#ifndef NDEBUG
2831 for (auto idx : indices.drop_back())
2832 assert(isa<llvm::ConstantInt>(idx) &&
2833 cast<llvm::ConstantInt>(idx)->isZero());
2834#endif
2835
2836 // Determine the element size of the statically-sized base. This is
2837 // the thing that the indices are expressed in terms of.
2838 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
2839 eltType = getFixedSizeElementType(CGF.getContext(), vla);
2840 }
2841
2842 // We can use that to compute the best alignment of the element.
2843 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
2844 CharUnits eltAlign =
2845 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
2846
2847 llvm::Value *eltPtr =
2848 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name);
2849 return Address(eltPtr, eltAlign);
2850}
2851
Richard Smith539e4a72013-02-23 02:53:19 +00002852LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2853 bool Accessed) {
Ted Kremenekc81614d2007-08-20 16:18:38 +00002854 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner2da04b32007-08-24 05:35:26 +00002855 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Eli Friedman07bbeca2009-06-06 19:09:26 +00002856 QualType IdxTy = E->getIdx()->getType();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002857 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Eli Friedman07bbeca2009-06-06 19:09:26 +00002858
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002859 if (SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00002860 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
2861
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002862 // If the base is a vector type, then we are forming a vector element lvalue
2863 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002864 if (E->getBase()->getType()->isVectorType() &&
2865 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002866 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00002867 LValue LHS = EmitLValue(E->getBase());
Ted Kremenekc81614d2007-08-20 16:18:38 +00002868 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Eli Friedman327944b2008-06-13 23:01:12 +00002869 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
John McCall7f416cc2015-09-08 08:05:57 +00002870 E->getBase()->getType(),
2871 LHS.getAlignmentSource());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002872 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002873
John McCall7f416cc2015-09-08 08:05:57 +00002874 // All the other cases basically behave like simple offsetting.
2875
Ted Kremenekc81614d2007-08-20 16:18:38 +00002876 // Extend or truncate the index type to 32 or 64-bits.
John McCalle3dc1702011-02-15 09:22:45 +00002877 if (Idx->getType() != IntPtrTy)
2878 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
Mike Stumpd9546382009-12-12 01:27:46 +00002879
John McCall7f416cc2015-09-08 08:05:57 +00002880 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002881 if (isa<ExtVectorElementExpr>(E->getBase())) {
2882 LValue LV = EmitLValue(E->getBase());
John McCall7f416cc2015-09-08 08:05:57 +00002883 Address Addr = EmitExtVectorElementLValue(LV);
2884
2885 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
2886 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true);
2887 return MakeAddrLValue(Addr, EltType, LV.getAlignmentSource());
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002888 }
John McCall7f416cc2015-09-08 08:05:57 +00002889
2890 AlignmentSource AlignSource;
2891 Address Addr = Address::invalid();
2892 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002893 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00002894 // The base must be a pointer, which is not an aggregate. Emit
2895 // it. It needs to be emitted first in case it's what captures
2896 // the VLA bounds.
John McCall7f416cc2015-09-08 08:05:57 +00002897 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00002898
John McCall23c29fe2011-06-24 21:55:10 +00002899 // The element count here is the total number of non-VLA elements.
2900 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00002901
John McCall77527a82011-06-25 01:32:37 +00002902 // Effectively, the multiply by the VLA size is part of the GEP.
2903 // GEP indexes are signed, and scaling an index isn't permitted to
2904 // signed-overflow, so we use the same semantics for our explicit
2905 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002906 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00002907 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00002908 } else {
2909 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00002910 }
John McCall7f416cc2015-09-08 08:05:57 +00002911
2912 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
2913 !getLangOpts().isSignedOverflowDefined());
2914
Chris Lattner6c5abe82010-06-26 23:03:20 +00002915 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
2916 // Indexing over an interface, as in "NSString *P; P[4];"
John McCall7f416cc2015-09-08 08:05:57 +00002917 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
2918 llvm::Value *InterfaceSizeVal =
2919 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());;
Mike Stump4a3999f2009-09-09 13:00:44 +00002920
John McCall7f416cc2015-09-08 08:05:57 +00002921 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002922
John McCall7f416cc2015-09-08 08:05:57 +00002923 // Emit the base pointer.
2924 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
2925
2926 // We don't necessarily build correct LLVM struct types for ObjC
2927 // interfaces, so we can't rely on GEP to do this scaling
2928 // correctly, so we need to cast to i8*. FIXME: is this actually
2929 // true? A lot of other things in the fragile ABI would break...
2930 llvm::Type *OrigBaseTy = Addr.getType();
2931 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
2932
2933 // Do the GEP.
2934 CharUnits EltAlign =
2935 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
2936 llvm::Value *EltPtr =
2937 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false);
2938 Addr = Address(EltPtr, EltAlign);
2939
2940 // Cast back.
2941 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00002942 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
2943 // If this is A[i] where A is an array, the frontend will have decayed the
2944 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
2945 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
2946 // "gep x, i" here. Emit one "gep A, 0, i".
2947 assert(Array->getType()->isArrayType() &&
2948 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00002949 LValue ArrayLV;
2950 // For simple multidimensional array indexing, set the 'accessed' flag for
2951 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002952 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00002953 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
2954 else
2955 ArrayLV = EmitLValue(Array);
Craig Topper99e79272013-07-26 05:59:26 +00002956
Daniel Dunbar82634272011-04-01 00:49:43 +00002957 // Propagate the alignment from the array itself to the result.
John McCall7f416cc2015-09-08 08:05:57 +00002958 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
2959 {CGM.getSize(CharUnits::Zero()), Idx},
2960 E->getType(),
2961 !getLangOpts().isSignedOverflowDefined());
2962 AlignSource = ArrayLV.getAlignmentSource();
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002963 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002964 // The base must be a pointer; emit it with an estimate of its alignment.
2965 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
2966 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
2967 !getLangOpts().isSignedOverflowDefined());
Anders Carlsson3d312f82008-12-21 00:11:23 +00002968 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002969
John McCall7f416cc2015-09-08 08:05:57 +00002970 LValue LV = MakeAddrLValue(Addr, E->getType(), AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00002971
John McCall7f416cc2015-09-08 08:05:57 +00002972 // TODO: Preserve/extend path TBAA metadata?
John McCall8ccfcb52009-09-24 19:53:00 +00002973
Richard Smith9c6890a2012-11-01 22:30:59 +00002974 if (getLangOpts().ObjC1 &&
2975 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00002976 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002977 setObjCGCLValueClass(getContext(), E, LV);
2978 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00002979 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00002980}
2981
Alexey Bataev31300ed2016-02-04 11:27:03 +00002982static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
2983 AlignmentSource &AlignSource,
2984 QualType BaseTy, QualType ElTy,
2985 bool IsLowerBound) {
2986 LValue BaseLVal;
2987 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
2988 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
2989 if (BaseTy->isArrayType()) {
2990 Address Addr = BaseLVal.getAddress();
2991 AlignSource = BaseLVal.getAlignmentSource();
2992
2993 // If the array type was an incomplete type, we need to make sure
2994 // the decay ends up being the right type.
2995 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
2996 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
2997
2998 // Note that VLA pointers are always decayed, so we don't need to do
2999 // anything here.
3000 if (!BaseTy->isVariableArrayType()) {
3001 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3002 "Expected pointer to array");
3003 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3004 "arraydecay");
3005 }
3006
3007 return CGF.Builder.CreateElementBitCast(Addr,
3008 CGF.ConvertTypeForMem(ElTy));
3009 }
3010 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &AlignSource);
3011 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3012 }
3013 return CGF.EmitPointerWithAlignment(Base, &AlignSource);
3014}
3015
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003016LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3017 bool IsLowerBound) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003018 QualType BaseTy;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003019 if (auto *ASE =
3020 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
Alexey Bataev31300ed2016-02-04 11:27:03 +00003021 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003022 else
Alexey Bataev31300ed2016-02-04 11:27:03 +00003023 BaseTy = E->getBase()->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003024 QualType ResultExprTy;
3025 if (auto *AT = getContext().getAsArrayType(BaseTy))
3026 ResultExprTy = AT->getElementType();
3027 else
3028 ResultExprTy = BaseTy->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003029 llvm::Value *Idx = nullptr;
Benjamin Kramer5ff67472016-04-11 08:26:13 +00003030 if (IsLowerBound || E->getColonLoc().isInvalid()) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003031 // Requesting lower bound or upper bound, but without provided length and
3032 // without ':' symbol for the default length -> length = 1.
3033 // Idx = LowerBound ?: 0;
3034 if (auto *LowerBound = E->getLowerBound()) {
3035 Idx = Builder.CreateIntCast(
3036 EmitScalarExpr(LowerBound), IntPtrTy,
3037 LowerBound->getType()->hasSignedIntegerRepresentation());
3038 } else
3039 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3040 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003041 // Try to emit length or lower bound as constant. If this is possible, 1
3042 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3043 // IR (LB + Len) - 1.
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003044 auto &C = CGM.getContext();
3045 auto *Length = E->getLength();
3046 llvm::APSInt ConstLength;
3047 if (Length) {
3048 // Idx = LowerBound + Length - 1;
3049 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3050 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3051 Length = nullptr;
3052 }
3053 auto *LowerBound = E->getLowerBound();
3054 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3055 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3056 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3057 LowerBound = nullptr;
3058 }
3059 if (!Length)
3060 --ConstLength;
3061 else if (!LowerBound)
3062 --ConstLowerBound;
3063
3064 if (Length || LowerBound) {
3065 auto *LowerBoundVal =
3066 LowerBound
3067 ? Builder.CreateIntCast(
3068 EmitScalarExpr(LowerBound), IntPtrTy,
3069 LowerBound->getType()->hasSignedIntegerRepresentation())
3070 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3071 auto *LengthVal =
3072 Length
3073 ? Builder.CreateIntCast(
3074 EmitScalarExpr(Length), IntPtrTy,
3075 Length->getType()->hasSignedIntegerRepresentation())
3076 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3077 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3078 /*HasNUW=*/false,
3079 !getLangOpts().isSignedOverflowDefined());
3080 if (Length && LowerBound) {
3081 Idx = Builder.CreateSub(
3082 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3083 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3084 }
3085 } else
3086 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3087 } else {
3088 // Idx = ArraySize - 1;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003089 QualType ArrayTy = BaseTy->isPointerType()
3090 ? E->getBase()->IgnoreParenImpCasts()->getType()
3091 : BaseTy;
3092 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003093 Length = VAT->getSizeExpr();
3094 if (Length->isIntegerConstantExpr(ConstLength, C))
3095 Length = nullptr;
3096 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003097 auto *CAT = C.getAsConstantArrayType(ArrayTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003098 ConstLength = CAT->getSize();
3099 }
3100 if (Length) {
3101 auto *LengthVal = Builder.CreateIntCast(
3102 EmitScalarExpr(Length), IntPtrTy,
3103 Length->getType()->hasSignedIntegerRepresentation());
3104 Idx = Builder.CreateSub(
3105 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3106 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3107 } else {
3108 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3109 --ConstLength;
3110 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3111 }
3112 }
3113 }
3114 assert(Idx);
3115
Alexey Bataev31300ed2016-02-04 11:27:03 +00003116 Address EltPtr = Address::invalid();
3117 AlignmentSource AlignSource;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003118 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003119 // The base must be a pointer, which is not an aggregate. Emit
3120 // it. It needs to be emitted first in case it's what captures
3121 // the VLA bounds.
3122 Address Base =
3123 emitOMPArraySectionBase(*this, E->getBase(), AlignSource, BaseTy,
3124 VLA->getElementType(), IsLowerBound);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003125 // The element count here is the total number of non-VLA elements.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003126 llvm::Value *NumElements = getVLASize(VLA).first;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003127
3128 // Effectively, the multiply by the VLA size is part of the GEP.
3129 // GEP indexes are signed, and scaling an index isn't permitted to
3130 // signed-overflow, so we use the same semantics for our explicit
3131 // multiply. We suppress this if overflow is not undefined behavior.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003132 if (getLangOpts().isSignedOverflowDefined())
3133 Idx = Builder.CreateMul(Idx, NumElements);
3134 else
3135 Idx = Builder.CreateNSWMul(Idx, NumElements);
3136 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3137 !getLangOpts().isSignedOverflowDefined());
3138 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3139 // If this is A[i] where A is an array, the frontend will have decayed the
3140 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3141 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3142 // "gep x, i" here. Emit one "gep A, 0, i".
3143 assert(Array->getType()->isArrayType() &&
3144 "Array to pointer decay must have array source type!");
3145 LValue ArrayLV;
3146 // For simple multidimensional array indexing, set the 'accessed' flag for
3147 // better bounds-checking of the base expression.
3148 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3149 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3150 else
3151 ArrayLV = EmitLValue(Array);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003152
Alexey Bataev31300ed2016-02-04 11:27:03 +00003153 // Propagate the alignment from the array itself to the result.
3154 EltPtr = emitArraySubscriptGEP(
3155 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3156 ResultExprTy, !getLangOpts().isSignedOverflowDefined());
3157 AlignSource = ArrayLV.getAlignmentSource();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003158 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003159 Address Base = emitOMPArraySectionBase(*this, E->getBase(), AlignSource,
3160 BaseTy, ResultExprTy, IsLowerBound);
3161 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3162 !getLangOpts().isSignedOverflowDefined());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003163 }
3164
Alexey Bataev31300ed2016-02-04 11:27:03 +00003165 return MakeAddrLValue(EltPtr, ResultExprTy, AlignSource);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003166}
3167
Chris Lattner9e751ca2007-08-02 23:37:31 +00003168LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00003169EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00003170 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003171 LValue Base;
3172
3173 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00003174 if (E->isArrow()) {
3175 // If it is a pointer to a vector, emit the address and form an lvalue with
3176 // it.
John McCall7f416cc2015-09-08 08:05:57 +00003177 AlignmentSource AlignSource;
3178 Address Ptr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003179 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
John McCall7f416cc2015-09-08 08:05:57 +00003180 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00003181 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00003182 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00003183 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3184 // emit the base as an lvalue.
3185 assert(E->getBase()->getType()->isVectorType());
3186 Base = EmitLValue(E->getBase());
3187 } else {
3188 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00003189 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00003190 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00003191 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00003192
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00003193 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00003194 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00003195 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00003196 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3197 AlignmentSource::Decl);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003198 }
John McCall1553b192011-06-16 04:16:24 +00003199
3200 QualType type =
3201 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00003202
Nate Begemand3862152008-05-13 21:03:02 +00003203 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00003204 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00003205 E->getEncodedElementAccess(Indices);
3206
3207 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00003208 llvm::Constant *CV =
3209 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00003210 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
John McCall7f416cc2015-09-08 08:05:57 +00003211 Base.getAlignmentSource());
Nate Begemand3862152008-05-13 21:03:02 +00003212 }
3213 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3214
3215 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003216 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00003217
Chris Lattner595ba3a2012-01-30 06:20:36 +00003218 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3219 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00003220 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00003221 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3222 Base.getAlignmentSource());
Chris Lattner9e751ca2007-08-02 23:37:31 +00003223}
3224
Devang Patel30efa2e2007-10-23 20:28:39 +00003225LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00003226 Expr *BaseExpr = E->getBase();
Eli Friedman327944b2008-06-13 23:01:12 +00003227
Chris Lattner4e4186b2007-12-02 18:52:07 +00003228 // 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 +00003229 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00003230 if (E->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00003231 AlignmentSource AlignSource;
3232 Address Addr = EmitPointerWithAlignment(BaseExpr, &AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003233 QualType PtrTy = BaseExpr->getType()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003234 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy);
3235 BaseLV = MakeAddrLValue(Addr, PtrTy, AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003236 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003237 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003238
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003239 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003240 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003241 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003242 setObjCGCLValueClass(getContext(), E, LV);
3243 return LV;
3244 }
Craig Topper99e79272013-07-26 05:59:26 +00003245
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003246 if (auto *VD = dyn_cast<VarDecl>(ND))
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00003247 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003248
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003249 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003250 return EmitFunctionDeclLValue(*this, E, FD);
3251
David Blaikie83d382b2011-09-23 05:06:16 +00003252 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003253}
Devang Patel30efa2e2007-10-23 20:28:39 +00003254
John McCalldec348f72013-05-03 07:33:41 +00003255/// Given that we are currently emitting a lambda, emit an l-value for
3256/// one of its members.
3257LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3258 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3259 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3260 QualType LambdaTagType =
3261 getContext().getTagDeclType(Field->getParent());
3262 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3263 return EmitLValueForField(LambdaLV, Field);
3264}
3265
John McCall7f416cc2015-09-08 08:05:57 +00003266/// Drill down to the storage of a field without walking into
3267/// reference types.
3268///
3269/// The resulting address doesn't necessarily have the right type.
3270static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3271 const FieldDecl *field) {
3272 const RecordDecl *rec = field->getParent();
3273
3274 unsigned idx =
3275 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3276
3277 CharUnits offset;
3278 // Adjust the alignment down to the given offset.
3279 // As a special case, if the LLVM field index is 0, we know that this
3280 // is zero.
3281 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3282 .getFieldOffset(field->getFieldIndex()) == 0) &&
3283 "LLVM field at index zero had non-zero offset?");
3284 if (idx != 0) {
3285 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3286 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3287 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3288 }
3289
3290 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3291}
3292
Eli Friedman7f1ff602012-04-16 03:54:45 +00003293LValue CodeGenFunction::EmitLValueForField(LValue base,
3294 const FieldDecl *field) {
John McCall7f416cc2015-09-08 08:05:57 +00003295 AlignmentSource fieldAlignSource =
3296 getFieldAlignmentSource(base.getAlignmentSource());
3297
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003298 if (field->isBitField()) {
3299 const CGRecordLayout &RL =
3300 CGM.getTypes().getCGRecordLayout(field->getParent());
3301 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003302 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003303 unsigned Idx = RL.getLLVMFieldNo(field);
3304 if (Idx != 0)
3305 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003306 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3307 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003308 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003309 llvm::Type *FieldIntTy =
3310 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3311 if (Addr.getElementType() != FieldIntTy)
3312 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003313
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003314 QualType fieldType =
3315 field->getType().withCVRQualifiers(base.getVRQualifiers());
John McCall7f416cc2015-09-08 08:05:57 +00003316 return LValue::MakeBitfield(Addr, Info, fieldType, fieldAlignSource);
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003317 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003318
John McCall53fcbd22011-02-26 08:07:02 +00003319 const RecordDecl *rec = field->getParent();
3320 QualType type = field->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003321
John McCall53fcbd22011-02-26 08:07:02 +00003322 bool mayAlias = rec->hasAttr<MayAliasAttr>();
3323
John McCall7f416cc2015-09-08 08:05:57 +00003324 Address addr = base.getAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003325 unsigned cvr = base.getVRQualifiers();
Manman Renc451e572013-04-04 21:53:22 +00003326 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
John McCall53fcbd22011-02-26 08:07:02 +00003327 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003328 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00003329 assert(!type->isReferenceType() && "union has reference member");
Manman Renc451e572013-04-04 21:53:22 +00003330 // TODO: handle path-aware TBAA for union.
3331 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003332 } else {
3333 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003334 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003335
3336 // If this is a reference field, load the reference right now.
3337 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3338 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3339 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3340
Manman Renc451e572013-04-04 21:53:22 +00003341 // Loading the reference will disable path-aware TBAA.
3342 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003343 if (CGM.shouldUseTBAA()) {
3344 llvm::MDNode *tbaa;
3345 if (mayAlias)
3346 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3347 else
3348 tbaa = CGM.getTBAAInfo(type);
Manman Ren4f755de2013-10-08 00:08:49 +00003349 if (tbaa)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00003350 CGM.DecorateInstructionWithTBAA(load, tbaa);
John McCall53fcbd22011-02-26 08:07:02 +00003351 }
3352
John McCall53fcbd22011-02-26 08:07:02 +00003353 mayAlias = false;
3354 type = refType->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003355
3356 CharUnits alignment =
3357 getNaturalTypeAlignment(type, &fieldAlignSource, /*pointee*/ true);
3358 addr = Address(load, alignment);
3359
3360 // Qualifiers on the struct don't apply to the referencee, and
3361 // we'll pick up CVR from the actual type later, so reset these
3362 // additional qualifiers now.
3363 cvr = 0;
John McCall53fcbd22011-02-26 08:07:02 +00003364 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003365 }
Craig Topper99e79272013-07-26 05:59:26 +00003366
Chris Lattner13ee4f42011-07-10 05:34:54 +00003367 // Make sure that the address is pointing to the right type. This is critical
3368 // for both unions and structs. A union needs a bitcast, a struct element
3369 // will need a bitcast if the LLVM type laid out doesn't match the desired
3370 // type.
John McCall7f416cc2015-09-08 08:05:57 +00003371 addr = Builder.CreateElementBitCast(addr,
3372 CGM.getTypes().ConvertTypeForMem(type),
3373 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003374
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003375 if (field->hasAttr<AnnotateAttr>())
3376 addr = EmitFieldAnnotations(field, addr);
3377
John McCall7f416cc2015-09-08 08:05:57 +00003378 LValue LV = MakeAddrLValue(addr, type, fieldAlignSource);
John McCall53fcbd22011-02-26 08:07:02 +00003379 LV.getQuals().addCVRQualifiers(cvr);
Manman Renc451e572013-04-04 21:53:22 +00003380 if (TBAAPath) {
3381 const ASTRecordLayout &Layout =
3382 getContext().getASTRecordLayout(field->getParent());
3383 // Set the base type to be the base type of the base LValue and
3384 // update offset to be relative to the base type.
Manman Ren0e521662013-04-27 00:39:37 +00003385 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3386 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
Manman Renc451e572013-04-04 21:53:22 +00003387 Layout.getFieldOffset(field->getFieldIndex()) /
3388 getContext().getCharWidth());
3389 }
Daniel Dunbarf166a522010-08-21 03:44:13 +00003390
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003391 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003392 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3393 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003394
3395 // Fields of may_alias structs act like 'char' for TBAA purposes.
3396 // FIXME: this should get propagated down through anonymous structs
3397 // and unions.
3398 if (mayAlias && LV.getTBAAInfo())
3399 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3400
Daniel Dunbarf166a522010-08-21 03:44:13 +00003401 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003402}
3403
Craig Topper99e79272013-07-26 05:59:26 +00003404LValue
3405CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003406 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003407 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003408
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003409 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003410 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003411
John McCall7f416cc2015-09-08 08:05:57 +00003412 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003413
John McCall7f416cc2015-09-08 08:05:57 +00003414 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003415 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003416 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003417
John McCall7f416cc2015-09-08 08:05:57 +00003418 // TODO: access-path TBAA?
3419 auto FieldAlignSource = getFieldAlignmentSource(Base.getAlignmentSource());
3420 return MakeAddrLValue(V, FieldType, FieldAlignSource);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003421}
3422
Chris Lattnerf53c0962010-09-06 00:11:41 +00003423LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00003424 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003425 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3426 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
Richard Smith2d988f02011-11-22 22:48:32 +00003427 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003428 if (E->getType()->isVariablyModifiedType())
3429 // make sure to emit the VLA size.
3430 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003431
John McCall7f416cc2015-09-08 08:05:57 +00003432 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003433 const Expr *InitExpr = E->getInitializer();
John McCall7f416cc2015-09-08 08:05:57 +00003434 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003435
Chad Rosier615ed1a2012-03-29 17:37:10 +00003436 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3437 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003438
3439 return Result;
3440}
3441
Richard Smithbb653bd2012-05-14 21:57:21 +00003442LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3443 if (!E->isGLValue())
3444 // Initializing an aggregate temporary in C++11: T{...}.
3445 return EmitAggExprToLValue(E);
3446
3447 // An lvalue initializer list must be initializing a reference.
3448 assert(E->getNumInits() == 1 && "reference init with multiple values");
3449 return EmitLValue(E->getInit(0));
3450}
3451
Richard Smithf3076ff2014-06-20 18:43:47 +00003452/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3453/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3454/// LValue is returned and the current block has been terminated.
3455static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3456 const Expr *Operand) {
3457 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3458 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3459 return None;
3460 }
3461
3462 return CGF.EmitLValue(Operand);
3463}
3464
John McCallc07a0c72011-02-17 10:25:35 +00003465LValue CodeGenFunction::
3466EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3467 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003468 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003469 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003470 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003471 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003472 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003473
Eli Friedman59954892012-01-25 05:04:17 +00003474 OpaqueValueMapping binding(*this, expr);
3475
John McCallc07a0c72011-02-17 10:25:35 +00003476 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003477 bool CondExprBool;
3478 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003479 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003480 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003481
Justin Bogneref512b92014-01-06 22:27:43 +00003482 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003483 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003484 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003485 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003486 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003487 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003488 }
3489
John McCallc07a0c72011-02-17 10:25:35 +00003490 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3491 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3492 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003493
3494 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003495 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003496
John McCall0a6bf2e2011-01-26 19:21:13 +00003497 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003498 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003499 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003500 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003501 Optional<LValue> lhs =
3502 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003503 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003504
Richard Smithf3076ff2014-06-20 18:43:47 +00003505 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003506 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003507
John McCallc07a0c72011-02-17 10:25:35 +00003508 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003509 if (lhs)
3510 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003511
John McCall0a6bf2e2011-01-26 19:21:13 +00003512 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003513 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003514 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003515 Optional<LValue> rhs =
3516 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003517 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003518 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003519 return EmitUnsupportedLValue(expr, "conditional operator");
3520 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003521
John McCallc07a0c72011-02-17 10:25:35 +00003522 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003523
Richard Smithf3076ff2014-06-20 18:43:47 +00003524 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003525 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003526 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003527 phi->addIncoming(lhs->getPointer(), lhsBlock);
3528 phi->addIncoming(rhs->getPointer(), rhsBlock);
3529 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3530 AlignmentSource alignSource =
3531 std::max(lhs->getAlignmentSource(), rhs->getAlignmentSource());
3532 return MakeAddrLValue(result, expr->getType(), alignSource);
Richard Smithf3076ff2014-06-20 18:43:47 +00003533 } else {
3534 assert((lhs || rhs) &&
3535 "both operands of glvalue conditional are throw-expressions?");
3536 return lhs ? *lhs : *rhs;
3537 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003538}
3539
Richard Smithbb653bd2012-05-14 21:57:21 +00003540/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3541/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003542/// otherwise if a cast is needed by the code generator in an lvalue context,
3543/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003544/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003545/// are permitted with aggregate result, including noop aggregate casts, and
3546/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003547LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003548 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003549 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003550 case CK_BitCast:
3551 case CK_ArrayToPointerDecay:
3552 case CK_FunctionToPointerDecay:
3553 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003554 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003555 case CK_IntegralToPointer:
3556 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003557 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003558 case CK_VectorSplat:
3559 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00003560 case CK_BooleanToSignedIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003561 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003562 case CK_IntegralToFloating:
3563 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003564 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003565 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003566 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003567 case CK_FloatingComplexToReal:
3568 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003569 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003570 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003571 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003572 case CK_IntegralComplexToReal:
3573 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003574 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003575 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003576 case CK_DerivedToBaseMemberPointer:
3577 case CK_BaseToDerivedMemberPointer:
3578 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003579 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003580 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003581 case CK_ARCProduceObject:
3582 case CK_ARCConsumeObject:
3583 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003584 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003585 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003586 case CK_AddressSpaceConversion:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003587 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3588
3589 case CK_Dependent:
3590 llvm_unreachable("dependent cast kind in IR gen!");
3591
3592 case CK_BuiltinFnToFnPtr:
3593 llvm_unreachable("builtin functions are handled elsewhere");
3594
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003595 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003596 case CK_NonAtomicToAtomic:
3597 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003598 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00003599
Anders Carlsson8a01a752011-04-11 02:03:26 +00003600 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00003601 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003602 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003603 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00003604 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00003605 }
3606
John McCalle3027922010-08-25 11:45:40 +00003607 case CK_ConstructorConversion:
3608 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00003609 case CK_CPointerToObjCPointerCast:
3610 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003611 case CK_NoOp:
3612 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003613 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00003614
John McCalle3027922010-08-25 11:45:40 +00003615 case CK_UncheckedDerivedToBase:
3616 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00003617 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00003618 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003619 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003620
Anders Carlssond95f9602009-09-12 16:16:49 +00003621 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003622 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00003623
Anders Carlssond95f9602009-09-12 16:16:49 +00003624 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00003625 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00003626 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3627 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00003628
John McCall7f416cc2015-09-08 08:05:57 +00003629 return MakeAddrLValue(Base, E->getType(), LV.getAlignmentSource());
Anders Carlssond95f9602009-09-12 16:16:49 +00003630 }
John McCalle3027922010-08-25 11:45:40 +00003631 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00003632 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00003633 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00003634 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003635 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003636
Anders Carlsson8c793172009-11-23 17:57:54 +00003637 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00003638
Anders Carlsson8c793172009-11-23 17:57:54 +00003639 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00003640 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00003641 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00003642 E->path_begin(), E->path_end(),
3643 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00003644
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003645 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3646 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00003647 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003648 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00003649 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003650
Peter Collingbourned2926c92015-03-14 02:42:25 +00003651 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003652 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3653 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003654 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003655
John McCall7f416cc2015-09-08 08:05:57 +00003656 return MakeAddrLValue(Derived, E->getType(), LV.getAlignmentSource());
Eli Friedman8c98dff2009-11-16 05:48:01 +00003657 }
John McCalle3027922010-08-25 11:45:40 +00003658 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00003659 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003660 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00003661
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00003662 CGM.EmitExplicitCastExprType(CE, this);
Anders Carlsson50cb3212009-11-14 21:21:42 +00003663 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003664 Address V = Builder.CreateBitCast(LV.getAddress(),
3665 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00003666
3667 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003668 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3669 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003670 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003671
John McCall7f416cc2015-09-08 08:05:57 +00003672 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Anders Carlsson50cb3212009-11-14 21:21:42 +00003673 }
John McCalle3027922010-08-25 11:45:40 +00003674 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003675 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003676 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3677 ConvertType(E->getType()));
3678 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003679 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003680 case CK_ZeroToOCLEvent:
3681 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00003682 }
Craig Topper99e79272013-07-26 05:59:26 +00003683
Douglas Gregorcdb466e2010-07-15 18:58:16 +00003684 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003685}
3686
John McCall1bf58462011-02-16 08:02:54 +00003687LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00003688 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00003689 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00003690}
3691
Eli Friedman7f1ff602012-04-16 03:54:45 +00003692RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003693 const FieldDecl *FD,
3694 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003695 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003696 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00003697 switch (getEvaluationKind(FT)) {
3698 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003699 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00003700 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00003701 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00003702 case TEK_Scalar:
Reid Kleckner9d031092016-05-02 22:42:34 +00003703 // This routine is used to load fields one-by-one to perform a copy, so
3704 // don't load reference fields.
3705 if (FD->getType()->isReferenceType())
3706 return RValue::get(FieldLV.getPointer());
Nick Lewycky2d84e842013-10-02 02:29:49 +00003707 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00003708 }
3709 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003710}
Douglas Gregorfe314812011-06-21 17:03:29 +00003711
Chris Lattnere47e4402007-06-01 18:02:12 +00003712//===--------------------------------------------------------------------===//
3713// Expression Emission
3714//===--------------------------------------------------------------------===//
3715
Craig Topper99e79272013-07-26 05:59:26 +00003716RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00003717 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003718 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003719 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00003720 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003721
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003722 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003723 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003724
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003725 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00003726 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3727
Douglas Gregore0e96302011-09-06 21:41:04 +00003728 const Decl *TargetDecl = E->getCalleeDecl();
3729 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
3730 if (unsigned builtinID = FD->getBuiltinID())
Peter Collingbournef7706832014-12-12 23:41:25 +00003731 return EmitBuiltinExpr(FD, builtinID, E, ReturnValue);
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003732 }
3733
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003734 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
Anders Carlsson4034a952009-05-27 04:18:27 +00003735 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003736 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003737
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003738 if (const auto *PseudoDtor =
3739 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
John McCall31168b02011-06-15 23:02:42 +00003740 QualType DestroyedType = PseudoDtor->getDestroyedType();
John McCall460ce582015-10-22 18:38:17 +00003741 if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003742 // Automatic Reference Counting:
3743 // If the pseudo-expression names a retainable object with weak or
3744 // strong lifetime, the object shall be released.
John McCall31168b02011-06-15 23:02:42 +00003745 Expr *BaseExpr = PseudoDtor->getBase();
John McCall7f416cc2015-09-08 08:05:57 +00003746 Address BaseValue = Address::invalid();
John McCall31168b02011-06-15 23:02:42 +00003747 Qualifiers BaseQuals;
Craig Topper99e79272013-07-26 05:59:26 +00003748
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003749 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
John McCall31168b02011-06-15 23:02:42 +00003750 if (PseudoDtor->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00003751 BaseValue = EmitPointerWithAlignment(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00003752 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
3753 BaseQuals = PTy->getPointeeType().getQualifiers();
3754 } else {
3755 LValue BaseLV = EmitLValue(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00003756 BaseValue = BaseLV.getAddress();
3757 QualType BaseTy = BaseExpr->getType();
3758 BaseQuals = BaseTy.getQualifiers();
3759 }
Craig Topper99e79272013-07-26 05:59:26 +00003760
John McCall460ce582015-10-22 18:38:17 +00003761 switch (DestroyedType.getObjCLifetime()) {
John McCall31168b02011-06-15 23:02:42 +00003762 case Qualifiers::OCL_None:
3763 case Qualifiers::OCL_ExplicitNone:
3764 case Qualifiers::OCL_Autoreleasing:
3765 break;
Craig Topper99e79272013-07-26 05:59:26 +00003766
John McCall31168b02011-06-15 23:02:42 +00003767 case Qualifiers::OCL_Strong:
Craig Topper99e79272013-07-26 05:59:26 +00003768 EmitARCRelease(Builder.CreateLoad(BaseValue,
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003769 PseudoDtor->getDestroyedType().isVolatileQualified()),
John McCallcdda29c2013-03-13 03:10:54 +00003770 ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00003771 break;
3772
3773 case Qualifiers::OCL_Weak:
3774 EmitARCDestroyWeak(BaseValue);
3775 break;
3776 }
3777 } else {
3778 // C++ [expr.pseudo]p1:
3779 // The result shall only be used as the operand for the function call
3780 // operator (), and the result of such a call has type void. The only
3781 // effect is the evaluation of the postfix-expression before the dot or
Craig Topper99e79272013-07-26 05:59:26 +00003782 // arrow.
John McCall31168b02011-06-15 23:02:42 +00003783 EmitScalarExpr(E->getCallee());
3784 }
Craig Topper99e79272013-07-26 05:59:26 +00003785
Craig Topper8a13c412014-05-21 05:09:00 +00003786 return RValue::get(nullptr);
Douglas Gregorad8a3362009-09-04 17:36:40 +00003787 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003788
Chris Lattner2da04b32007-08-24 05:35:26 +00003789 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003790 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
3791 TargetDecl);
Chris Lattner9e47ead2007-08-31 04:44:06 +00003792}
3793
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003794LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00003795 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00003796 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00003797 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00003798 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00003799 return EmitLValue(E->getRHS());
3800 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003801
John McCalle3027922010-08-25 11:45:40 +00003802 if (E->getOpcode() == BO_PtrMemD ||
3803 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003804 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003805
John McCalla2342eb2010-12-05 02:00:02 +00003806 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00003807
3808 // Note that in all of these cases, __block variables need the RHS
3809 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00003810
3811 switch (getEvaluationKind(E->getType())) {
3812 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00003813 switch (E->getLHS()->getType().getObjCLifetime()) {
3814 case Qualifiers::OCL_Strong:
3815 return EmitARCStoreStrong(E, /*ignored*/ false).first;
3816
3817 case Qualifiers::OCL_Autoreleasing:
3818 return EmitARCStoreAutoreleasing(E).first;
3819
3820 // No reason to do any of these differently.
3821 case Qualifiers::OCL_None:
3822 case Qualifiers::OCL_ExplicitNone:
3823 case Qualifiers::OCL_Weak:
3824 break;
3825 }
3826
John McCalld0a30012010-12-06 06:10:02 +00003827 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00003828 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
John McCall55e1fbc2011-06-25 02:11:03 +00003829 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00003830 return LV;
3831 }
John McCall4f29b492010-11-16 23:07:28 +00003832
John McCall47fb9502013-03-07 21:37:08 +00003833 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00003834 return EmitComplexAssignmentLValue(E);
3835
John McCall47fb9502013-03-07 21:37:08 +00003836 case TEK_Aggregate:
3837 return EmitAggExprToLValue(E);
3838 }
3839 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003840}
3841
Christopher Lambd91c3d42007-12-29 05:02:41 +00003842LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00003843 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00003844
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003845 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00003846 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3847 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00003848
David Majnemerced8bdf2015-02-25 17:36:15 +00003849 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003850 "Can't have a scalar return unless the return type is a "
3851 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00003852
John McCall7f416cc2015-09-08 08:05:57 +00003853 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00003854}
3855
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003856LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
3857 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00003858 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003859}
3860
Anders Carlsson3be22e22009-05-30 23:23:33 +00003861LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003862 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
3863 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00003864 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00003865 EmitCXXConstructExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003866 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3867 AlignmentSource::Decl);
Anders Carlsson3be22e22009-05-30 23:23:33 +00003868}
3869
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003870LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00003871CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003872 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00003873}
3874
John McCall7f416cc2015-09-08 08:05:57 +00003875Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
3876 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
3877 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00003878}
3879
3880LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003881 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
3882 AlignmentSource::Decl);
Nico Webercf4ff5862012-10-11 10:13:44 +00003883}
3884
Mike Stumpc9b231c2009-11-15 08:09:41 +00003885LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003886CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003887 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00003888 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00003889 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003890 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
3891 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3892 AlignmentSource::Decl);
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003893}
3894
Eli Friedman5bc17122012-02-08 05:34:55 +00003895LValue
3896CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00003897 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00003898 EmitLambdaExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003899 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3900 AlignmentSource::Decl);
Eli Friedman5bc17122012-02-08 05:34:55 +00003901}
3902
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003903LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003904 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00003905
Anders Carlsson280e61f12010-06-21 20:59:55 +00003906 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00003907 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3908 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00003909
Alp Toker314cc812014-01-25 16:55:45 +00003910 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00003911 "Can't have a scalar return unless the return type is a "
3912 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00003913
John McCall7f416cc2015-09-08 08:05:57 +00003914 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003915}
3916
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003917LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003918 Address V =
3919 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
3920 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003921}
3922
Daniel Dunbar722f4242009-04-22 05:08:15 +00003923llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003924 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00003925 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003926}
3927
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003928LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
3929 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003930 const ObjCIvarDecl *Ivar,
3931 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00003932 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00003933 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003934}
3935
3936LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003937 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00003938 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003939 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00003940 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003941 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003942 if (E->isArrow()) {
3943 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003944 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00003945 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003946 } else {
3947 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00003948 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003949 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00003950 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003951 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003952
Craig Topper99e79272013-07-26 05:59:26 +00003953 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00003954 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
3955 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00003956 setObjCGCLValueClass(getContext(), E, LV);
3957 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00003958}
3959
Chris Lattnera4185c52009-04-25 19:35:26 +00003960LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00003961 // Can only get l-value for message expression returning aggregate type
3962 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00003963 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3964 AlignmentSource::Decl);
Chris Lattnera4185c52009-04-25 19:35:26 +00003965}
3966
Anders Carlsson0435ed52009-12-24 19:08:58 +00003967RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003968 const CallExpr *E, ReturnValueSlot ReturnValue,
Samuel Antao798f11c2015-11-23 22:04:44 +00003969 CGCalleeInfo CalleeInfo, llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00003970 // Get the actual function type. The callee type will always be a pointer to
3971 // function type or a block pointer type.
3972 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00003973 "Call must have function pointer type!");
3974
Samuel Antao798f11c2015-11-23 22:04:44 +00003975 // Preserve the non-canonical function type because things like exception
3976 // specifications disappear in the canonical type. That information is useful
3977 // to drive the generation of more accurate code for this call later on.
3978 const FunctionProtoType *NonCanonicalFTP = CalleeType->getAs<PointerType>()
3979 ->getPointeeType()
3980 ->getAs<FunctionProtoType>();
3981
3982 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
3983
Eric Christopher2b2d56f2015-11-12 00:44:12 +00003984 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
Eric Christopher39db7262015-11-14 01:56:04 +00003985 // We can only guarantee that a function is called from the correct
3986 // context/function based on the appropriate target attributes,
3987 // so only check in the case where we have both always_inline and target
3988 // since otherwise we could be making a conditional call after a check for
3989 // the proper cpu features (and it won't cause code generation issues due to
3990 // function based code generation).
Eric Christopher2b2d56f2015-11-12 00:44:12 +00003991 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
3992 TargetDecl->hasAttr<TargetAttr>())
3993 checkTargetFeatures(E, FD);
3994
John McCall6fd4c232009-10-23 08:22:42 +00003995 CalleeType = getContext().getCanonicalType(CalleeType);
3996
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003997 const auto *FnType =
3998 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00003999
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004000 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004001 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4002 if (llvm::Constant *PrefixSig =
4003 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00004004 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004005 llvm::Constant *FTRTTIConst =
4006 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4007 llvm::Type *PrefixStructTyElems[] = {
4008 PrefixSig->getType(),
4009 FTRTTIConst->getType()
4010 };
4011 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4012 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4013
4014 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
4015 Callee, llvm::PointerType::getUnqual(PrefixStructTy));
4016 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004017 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00004018 llvm::Value *CalleeSig =
4019 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004020 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4021
4022 llvm::BasicBlock *Cont = createBasicBlock("cont");
4023 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4024 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4025
4026 EmitBlock(TypeCheck);
4027 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004028 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
John McCall7f416cc2015-09-08 08:05:57 +00004029 llvm::Value *CalleeRTTI =
4030 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004031 llvm::Value *CalleeRTTIMatch =
4032 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4033 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004034 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004035 EmitCheckTypeDescriptor(CalleeType)
4036 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00004037 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
4038 "function_type_mismatch", StaticData, Callee);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004039
4040 Builder.CreateBr(Cont);
4041 EmitBlock(Cont);
4042 }
4043 }
4044
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004045 // If we are checking indirect calls and this call is indirect, check that the
4046 // function pointer is a member of the bit set for the function type.
4047 if (SanOpts.has(SanitizerKind::CFIICall) &&
4048 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4049 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00004050 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004051
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004052 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
4053 llvm::Value *BitSetName = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004054
4055 llvm::Value *CastedCallee = Builder.CreateBitCast(Callee, Int8PtrTy);
4056 llvm::Value *BitSetTest =
4057 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::bitset_test),
4058 {CastedCallee, BitSetName});
4059
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004060 auto TypeId = CGM.CreateCfiIdForTypeMetadata(MD);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004061 llvm::Constant *StaticData[] = {
4062 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4063 EmitCheckSourceLocation(E->getLocStart()),
4064 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4065 };
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004066 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && TypeId) {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004067 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, BitSetTest, TypeId,
4068 CastedCallee, StaticData);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004069 } else {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004070 EmitCheck(std::make_pair(BitSetTest, SanitizerKind::CFIICall),
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004071 "cfi_check_fail", StaticData,
4072 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004073 }
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004074 }
4075
Daniel Dunbarc722b852008-08-30 03:02:31 +00004076 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00004077 if (Chain)
4078 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4079 CGM.getContext().VoidPtrTy);
David Blaikief05779e2015-07-21 18:37:18 +00004080 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
4081 E->getDirectCallee(), /*ParamsToSkip*/ 0);
Daniel Dunbarc722b852008-08-30 03:02:31 +00004082
Peter Collingbournef7706832014-12-12 23:41:25 +00004083 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4084 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00004085
4086 // C99 6.5.2.2p6:
4087 // If the expression that denotes the called function has a type
4088 // that does not include a prototype, [the default argument
4089 // promotions are performed]. If the number of arguments does not
4090 // equal the number of parameters, the behavior is undefined. If
4091 // the function is defined with a type that includes a prototype,
4092 // and either the prototype ends with an ellipsis (, ...) or the
4093 // types of the arguments after promotion are not compatible with
4094 // the types of the parameters, the behavior is undefined. If the
4095 // function is defined with a type that does not include a
4096 // prototype, and the types of the arguments after promotion are
4097 // not compatible with those of the parameters after promotion,
4098 // the behavior is undefined [except in some trivial cases].
4099 // That is, in the general case, we should assume that a call
4100 // through an unprototyped function type works like a *non-variadic*
4101 // call. The way we make this work is to cast to the exact type
4102 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00004103 //
4104 // Chain calls use this same code path to add the invisible chain parameter
4105 // to the function type.
4106 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00004107 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00004108 CalleeTy = CalleeTy->getPointerTo();
4109 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
4110 }
4111
Samuel Antao798f11c2015-11-23 22:04:44 +00004112 return EmitCall(FnInfo, Callee, ReturnValue, Args,
4113 CGCalleeInfo(NonCanonicalFTP, TargetDecl));
Daniel Dunbar97db84c2008-08-23 03:46:30 +00004114}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004115
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004116LValue CodeGenFunction::
4117EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004118 Address BaseAddr = Address::invalid();
4119 if (E->getOpcode() == BO_PtrMemI) {
4120 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4121 } else {
4122 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4123 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004124
John McCallc134eb52010-08-31 21:07:20 +00004125 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4126
4127 const MemberPointerType *MPT
4128 = E->getRHS()->getType()->getAs<MemberPointerType>();
4129
John McCall7f416cc2015-09-08 08:05:57 +00004130 AlignmentSource AlignSource;
4131 Address MemberAddr =
4132 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT,
4133 &AlignSource);
John McCallc134eb52010-08-31 21:07:20 +00004134
John McCall7f416cc2015-09-08 08:05:57 +00004135 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), AlignSource);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004136}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004137
John McCall47fb9502013-03-07 21:37:08 +00004138/// Given the address of a temporary variable, produce an r-value of
4139/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00004140RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004141 QualType type,
4142 SourceLocation loc) {
John McCall7f416cc2015-09-08 08:05:57 +00004143 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
John McCall47fb9502013-03-07 21:37:08 +00004144 switch (getEvaluationKind(type)) {
4145 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004146 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004147 case TEK_Aggregate:
4148 return lvalue.asAggregateRValue();
4149 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004150 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004151 }
4152 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004153}
4154
Duncan Sandse81111c2012-04-10 08:23:07 +00004155void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004156 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00004157 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004158 return;
4159
Duncan Sands65229ed2012-04-16 16:29:47 +00004160 llvm::MDBuilder MDHelper(getLLVMContext());
4161 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004162
Duncan Sands6fc46192012-04-14 12:37:26 +00004163 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004164}
John McCallfe96e0b2011-11-06 09:01:30 +00004165
4166namespace {
4167 struct LValueOrRValue {
4168 LValue LV;
4169 RValue RV;
4170 };
4171}
4172
4173static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4174 const PseudoObjectExpr *E,
4175 bool forLValue,
4176 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004177 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00004178
4179 // Find the result expression, if any.
4180 const Expr *resultExpr = E->getResultExpr();
4181 LValueOrRValue result;
4182
4183 for (PseudoObjectExpr::const_semantics_iterator
4184 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4185 const Expr *semantic = *i;
4186
4187 // If this semantic expression is an opaque value, bind it
4188 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004189 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00004190
4191 // If this is the result expression, we may need to evaluate
4192 // directly into the slot.
4193 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4194 OVMA opaqueData;
4195 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00004196 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00004197 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
4198
John McCall7f416cc2015-09-08 08:05:57 +00004199 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4200 AlignmentSource::Decl);
John McCallfe96e0b2011-11-06 09:01:30 +00004201 opaqueData = OVMA::bind(CGF, ov, LV);
4202 result.RV = slot.asRValue();
4203
4204 // Otherwise, emit as normal.
4205 } else {
4206 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4207
4208 // If this is the result, also evaluate the result now.
4209 if (ov == resultExpr) {
4210 if (forLValue)
4211 result.LV = CGF.EmitLValue(ov);
4212 else
4213 result.RV = CGF.EmitAnyExpr(ov, slot);
4214 }
4215 }
4216
4217 opaques.push_back(opaqueData);
4218
4219 // Otherwise, if the expression is the result, evaluate it
4220 // and remember the result.
4221 } else if (semantic == resultExpr) {
4222 if (forLValue)
4223 result.LV = CGF.EmitLValue(semantic);
4224 else
4225 result.RV = CGF.EmitAnyExpr(semantic, slot);
4226
4227 // Otherwise, evaluate the expression in an ignored context.
4228 } else {
4229 CGF.EmitIgnoredExpr(semantic);
4230 }
4231 }
4232
4233 // Unbind all the opaques now.
4234 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4235 opaques[i].unbind(CGF);
4236
4237 return result;
4238}
4239
4240RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4241 AggValueSlot slot) {
4242 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4243}
4244
4245LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4246 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4247}