blob: 1001a00b62e5a63d5e939c0d4200d4e4b9f58cde [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 Majnemera5b195a2015-02-14 01:35:12 +00001276 if (Ty->isAtomicType() || typeIsSuitableForInlineAtomic(Ty, Volatile)) {
John McCall7f416cc2015-09-08 08:05:57 +00001277 LValue lvalue =
1278 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
David Majnemereeaec262015-02-14 02:18:14 +00001279 return EmitAtomicLoad(lvalue, 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 Majnemera5b195a2015-02-14 01:35:12 +00001387 if (Ty->isAtomicType() ||
1388 (!isInit && typeIsSuitableForInlineAtomic(Ty, Volatile))) {
John McCalla8ec7eb2013-03-07 21:37:17 +00001389 EmitAtomicStore(RValue::get(Value),
John McCall7f416cc2015-09-08 08:05:57 +00001390 LValue::MakeAddr(Addr, Ty, getContext(),
1391 AlignSource, TBAAInfo),
John McCalla8ec7eb2013-03-07 21:37:17 +00001392 isInit);
1393 return;
1394 }
1395
Daniel Dunbar03816342010-08-21 02:24:36 +00001396 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001397 if (isNontemporal) {
1398 llvm::MDNode *Node =
1399 llvm::MDNode::get(Store->getContext(),
1400 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1401 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1402 }
Manman Renc451e572013-04-04 21:53:22 +00001403 if (TBAAInfo) {
1404 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1405 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001406 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001407 CGM.DecorateInstructionWithTBAA(Store, TBAAPath,
1408 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001409 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001410}
1411
David Chisnallfa35df62012-01-16 17:27:18 +00001412void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001413 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001414 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001415 lvalue.getType(), lvalue.getAlignmentSource(),
Manman Renc451e572013-04-04 21:53:22 +00001416 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001417 lvalue.getTBAAOffset(), lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001418}
1419
Mike Stump4a3999f2009-09-09 13:00:44 +00001420/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1421/// method emits the address of the lvalue, then loads the result as an rvalue,
1422/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001423RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001424 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001425 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001426 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001427 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1428 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001429 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001430 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001431 // In MRC mode, we do a load+autorelease.
1432 if (!getLangOpts().ObjCAutoRefCount) {
1433 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1434 }
1435
1436 // In ARC mode, we load retained and then consume the value.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001437 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1438 Object = EmitObjCConsumeObject(LV.getType(), Object);
1439 return RValue::get(Object);
1440 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001441
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001442 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001443 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001444
John McCalla1dee5302010-08-22 10:59:02 +00001445 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001446 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001447 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001448
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001449 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001450 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001451 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001452 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001453 "vecext"));
1454 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001455
1456 // If this is a reference to a subset of the elements of a vector, either
1457 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001458 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001459 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001460
Renato Golin230c5eb2014-05-19 18:15:42 +00001461 // Global Register variables always invoke intrinsics
1462 if (LV.isGlobalReg())
1463 return EmitLoadOfGlobalRegLValue(LV);
1464
John McCallc109a252011-11-07 03:59:57 +00001465 assert(LV.isBitField() && "Unknown LValue type!");
1466 return EmitLoadOfBitfieldLValue(LV);
Chris Lattner8394d792007-06-05 20:53:16 +00001467}
1468
John McCall55e1fbc2011-06-25 02:11:03 +00001469RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001470 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001471
Daniel Dunbar3447a022010-04-13 23:34:15 +00001472 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001473 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001474
John McCall7f416cc2015-09-08 08:05:57 +00001475 Address Ptr = LV.getBitFieldAddress();
1476 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001477
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001478 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001479 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001480 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1481 if (HighBits)
1482 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1483 if (Info.Offset + HighBits)
1484 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1485 } else {
1486 if (Info.Offset)
1487 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001488 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001489 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1490 Info.Size),
1491 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001492 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001493 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001494
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001495 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001496}
1497
Nate Begemanb699c9b2009-01-18 06:42:49 +00001498// If this is a reference to a subset of the elements of a vector, create an
1499// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001500RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001501 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1502 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001503
Nate Begemanf322eab2008-05-09 06:41:27 +00001504 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001505
1506 // If the result of the expression is a non-vector type, we must be extracting
1507 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001508 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001509 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001510 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001511 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001512 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001513 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001514
1515 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001516 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001517
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001518 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001519 for (unsigned i = 0; i != NumResultElts; ++i)
1520 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001521
Chris Lattner91c08ad2011-02-15 00:14:06 +00001522 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1523 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001524 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001525 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001526}
1527
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001528/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001529Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1530 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001531 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1532 QualType EQT = ExprVT->getElementType();
1533 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001534
John McCall7f416cc2015-09-08 08:05:57 +00001535 Address CastToPointerElement =
1536 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1537 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001538
1539 const llvm::Constant *Elts = LV.getExtVectorElts();
1540 unsigned ix = getAccessedFieldNo(0, Elts);
1541
John McCall7f416cc2015-09-08 08:05:57 +00001542 Address VectorBasePtrPlusIx =
1543 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1544 getContext().getTypeSizeInChars(EQT),
1545 "vector.elt");
1546
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001547 return VectorBasePtrPlusIx;
1548}
1549
Renato Golin230c5eb2014-05-19 18:15:42 +00001550/// @brief Load of global gamed gegisters are always calls to intrinsics.
1551RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001552 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1553 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001554 llvm::MDNode *RegName = cast<llvm::MDNode>(
1555 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001556
1557 // We accept integer and pointer types only
1558 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1559 llvm::Type *Ty = OrigTy;
1560 if (OrigTy->isPointerTy())
1561 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1562 llvm::Type *Types[] = { Ty };
1563
Renato Golin230c5eb2014-05-19 18:15:42 +00001564 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001565 llvm::Value *Call = Builder.CreateCall(
1566 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001567 if (OrigTy->isPointerTy())
1568 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001569 return RValue::get(Call);
1570}
Chris Lattner40ff7012007-08-03 16:18:34 +00001571
Chris Lattner9369a562007-06-29 16:31:29 +00001572
Chris Lattner8394d792007-06-05 20:53:16 +00001573/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1574/// lvalue, where both are guaranteed to the have the same type, and that type
1575/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001576void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001577 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001578 if (!Dst.isSimple()) {
1579 if (Dst.isVectorElt()) {
1580 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001581 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1582 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001583 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001584 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001585 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1586 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001587 return;
1588 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001589
Nate Begemance4d7fc2008-04-18 23:10:10 +00001590 // If this is an update of extended vector elements, insert them as
1591 // appropriate.
1592 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001593 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001594
Renato Golin230c5eb2014-05-19 18:15:42 +00001595 if (Dst.isGlobalReg())
1596 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1597
John McCallc109a252011-11-07 03:59:57 +00001598 assert(Dst.isBitField() && "Unknown LValue type");
1599 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001600 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001601
John McCall31168b02011-06-15 23:02:42 +00001602 // There's special magic for assigning into an ARC-qualified l-value.
1603 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1604 switch (Lifetime) {
1605 case Qualifiers::OCL_None:
1606 llvm_unreachable("present but none");
1607
1608 case Qualifiers::OCL_ExplicitNone:
1609 // nothing special
1610 break;
1611
1612 case Qualifiers::OCL_Strong:
John McCall55e1fbc2011-06-25 02:11:03 +00001613 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001614 return;
1615
1616 case Qualifiers::OCL_Weak:
1617 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1618 return;
1619
1620 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001621 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1622 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001623 // fall into the normal path
1624 break;
1625 }
1626 }
1627
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001628 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001629 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001630 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001631 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001632 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001633 return;
1634 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001635
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001636 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001637 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001638 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001639 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001640 if (Dst.isObjCIvar()) {
1641 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001642 llvm::Type *ResultType = IntPtrTy;
1643 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1644 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001645 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001646 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001647 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1648 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001649 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001650 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001651 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001652 } else if (Dst.isGlobalObjCRef()) {
1653 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1654 Dst.isThreadLocalRef());
1655 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001656 else
1657 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001658 return;
1659 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001660
Chris Lattner6278e6a2007-08-11 00:04:45 +00001661 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001662 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001663}
1664
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001665void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001666 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001667 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001668 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001669 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001670
Daniel Dunbar67aba792010-04-15 03:47:33 +00001671 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001672 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001673
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001674 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001675 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001676 /*IsSigned=*/false);
1677 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001678
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001679 // See if there are other bits in the bitfield's storage we'll need to load
1680 // and mask together with source before storing.
1681 if (Info.StorageSize != Info.Size) {
1682 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001683 llvm::Value *Val =
1684 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001685
1686 // Mask the source value as needed.
1687 if (!hasBooleanRepresentation(Dst.getType()))
1688 SrcVal = Builder.CreateAnd(SrcVal,
1689 llvm::APInt::getLowBitsSet(Info.StorageSize,
1690 Info.Size),
1691 "bf.value");
1692 MaskedVal = SrcVal;
1693 if (Info.Offset)
1694 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1695
1696 // Mask out the original value.
1697 Val = Builder.CreateAnd(Val,
1698 ~llvm::APInt::getBitsSet(Info.StorageSize,
1699 Info.Offset,
1700 Info.Offset + Info.Size),
1701 "bf.clear");
1702
1703 // Or together the unchanged values and the source value.
1704 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1705 } else {
1706 assert(Info.Offset == 0);
1707 }
1708
1709 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001710 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001711
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001712 // Return the new value of the bit-field, if requested.
1713 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001714 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001715
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001716 // Sign extend the value if needed.
1717 if (Info.IsSigned) {
1718 assert(Info.Size <= Info.StorageSize);
1719 unsigned HighBits = Info.StorageSize - Info.Size;
1720 if (HighBits) {
1721 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1722 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1723 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001724 }
1725
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001726 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1727 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001728 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001729 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001730}
1731
Nate Begemance4d7fc2008-04-18 23:10:10 +00001732void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001733 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001734 // This access turns into a read/modify/write of the vector. Load the input
1735 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001736 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1737 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001738 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001739
Chris Lattner4647a212007-08-31 22:49:20 +00001740 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001741
John McCall55e1fbc2011-06-25 02:11:03 +00001742 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001743 unsigned NumSrcElts = VTy->getNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001744 unsigned NumDstElts =
1745 cast<llvm::VectorType>(Vec->getType())->getNumElements();
1746 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001747 // Use shuffle vector is the src and destination are the same number of
1748 // elements and restore the vector mask since it is on the side it will be
1749 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001750 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001751 for (unsigned i = 0; i != NumSrcElts; ++i)
1752 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001753
Chris Lattner91c08ad2011-02-15 00:14:06 +00001754 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001755 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001756 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001757 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001758 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001759 // Extended the source vector to the same length and then shuffle it
1760 // into the destination.
1761 // FIXME: since we're shuffling with undef, can we just use the indices
1762 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001763 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001764 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001765 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001766 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001767 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001768 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001769 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001770 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001771 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001772 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001773 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001774 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001775 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001776
Joey Goulycf4143b2013-11-21 17:09:05 +00001777 // When the vector size is odd and .odd or .hi is used, the last element
1778 // of the Elts constant array will be one past the size of the vector.
1779 // Ignore the last element here, if it is greater than the mask size.
1780 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1781 NumSrcElts--;
1782
Nate Begemanb699c9b2009-01-18 06:42:49 +00001783 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001784 for (unsigned i = 0; i != NumSrcElts; ++i)
1785 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001786 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001787 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001788 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001789 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001790 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001791 }
1792 } else {
1793 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001794 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001795 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001796 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001797 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001798
John McCall7f416cc2015-09-08 08:05:57 +00001799 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1800 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001801}
1802
Renato Golin230c5eb2014-05-19 18:15:42 +00001803/// @brief Store of global named registers are always calls to intrinsics.
1804void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001805 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1806 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001807 llvm::MDNode *RegName = cast<llvm::MDNode>(
1808 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00001809 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00001810
1811 // We accept integer and pointer types only
1812 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1813 llvm::Type *Ty = OrigTy;
1814 if (OrigTy->isPointerTy())
1815 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1816 llvm::Type *Types[] = { Ty };
1817
Renato Golin230c5eb2014-05-19 18:15:42 +00001818 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1819 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00001820 if (OrigTy->isPointerTy())
1821 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00001822 Builder.CreateCall(
1823 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00001824}
1825
Eric Christopherc9e2a682014-05-20 17:10:39 +00001826// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001827// generating write-barries API. It is currently a global, ivar,
1828// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001829static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001830 LValue &LV,
1831 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001832 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001833 return;
Craig Topper99e79272013-07-26 05:59:26 +00001834
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001835 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001836 QualType ExpTy = E->getType();
1837 if (IsMemberAccess && ExpTy->isPointerType()) {
1838 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00001839 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001840 // writer-barrier conservatively.
1841 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1842 if (ExpTy->isRecordType()) {
1843 LV.setObjCIvar(false);
1844 return;
1845 }
1846 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001847 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001848 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001849 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001850 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001851 return;
1852 }
Craig Topper99e79272013-07-26 05:59:26 +00001853
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001854 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1855 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001856 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001857 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00001858 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001859 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001860 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001861 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001862 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001863 }
Craig Topper99e79272013-07-26 05:59:26 +00001864
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001865 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001866 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001867 return;
1868 }
Craig Topper99e79272013-07-26 05:59:26 +00001869
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001870 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001871 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001872 if (LV.isObjCIvar()) {
1873 // If cast is to a structure pointer, follow gcc's behavior and make it
1874 // a non-ivar write-barrier.
1875 QualType ExpTy = E->getType();
1876 if (ExpTy->isPointerType())
1877 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1878 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00001879 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001880 }
1881 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001882 }
Peter Collingbourne91147592011-04-15 00:35:48 +00001883
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001884 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001885 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1886 return;
1887 }
1888
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001889 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001890 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001891 return;
1892 }
Craig Topper99e79272013-07-26 05:59:26 +00001893
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001894 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001895 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001896 return;
1897 }
John McCall31168b02011-06-15 23:02:42 +00001898
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001899 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001900 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00001901 return;
1902 }
1903
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001904 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001905 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00001906 if (LV.isObjCIvar() && !LV.isObjCArray())
1907 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001908 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00001909 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001910 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00001911 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001912 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001913 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001914 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001915 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001916
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001917 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001918 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001919 // We don't know if member is an 'ivar', but this flag is looked at
1920 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001921 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001922 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001923 }
1924}
1925
Chris Lattner3f32d692011-07-12 06:52:18 +00001926static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00001927EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00001928 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001929 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00001930 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00001931 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00001932}
1933
Alexey Bataev97720002014-11-11 04:05:39 +00001934static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00001935 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
1936 llvm::Type *RealVarTy, SourceLocation Loc) {
1937 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
1938 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
1939 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
1940}
1941
1942Address CodeGenFunction::EmitLoadOfReference(Address Addr,
1943 const ReferenceType *RefTy,
1944 AlignmentSource *Source) {
1945 llvm::Value *Ptr = Builder.CreateLoad(Addr);
1946 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
1947 Source, /*forPointee*/ true));
1948
1949}
1950
1951LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
1952 const ReferenceType *RefTy) {
1953 AlignmentSource Source;
1954 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &Source);
1955 return MakeAddrLValue(Addr, RefTy->getPointeeType(), Source);
Alexey Bataev97720002014-11-11 04:05:39 +00001956}
1957
Alexey Bataev31300ed2016-02-04 11:27:03 +00001958Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
1959 const PointerType *PtrTy,
1960 AlignmentSource *Source) {
1961 llvm::Value *Addr = Builder.CreateLoad(Ptr);
1962 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(), Source,
1963 /*forPointeeType=*/true));
1964}
1965
1966LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
1967 const PointerType *PtrTy) {
1968 AlignmentSource Source;
1969 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &Source);
1970 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), Source);
1971}
1972
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001973static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1974 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00001975 QualType T = E->getType();
1976
1977 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00001978 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1979 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00001980 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
1981
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001982 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001983 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
1984 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00001985 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00001986 Address Addr(V, Alignment);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001987 LValue LV;
Alexey Bataev97720002014-11-11 04:05:39 +00001988 // Emit reference to the private copy of the variable if it is an OpenMP
1989 // threadprivate variable.
1990 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001991 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001992 E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001993 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
1994 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001995 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001996 LV = CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001997 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001998 setObjCGCLValueClass(CGF.getContext(), E, LV);
1999 return LV;
2000}
2001
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002002static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
Chris Lattner13ee4f42011-07-10 05:34:54 +00002003 const Expr *E, const FunctionDecl *FD) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00002004 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002005 if (!FD->hasPrototype()) {
2006 if (const FunctionProtoType *Proto =
2007 FD->getType()->getAs<FunctionProtoType>()) {
2008 // Ugly case: for a K&R-style definition, the type of the definition
2009 // isn't the same as the type of a use. Correct for this with a
2010 // bitcast.
2011 QualType NoProtoType =
Alp Toker314cc812014-01-25 16:55:45 +00002012 CGF.getContext().getFunctionNoProtoType(Proto->getReturnType());
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002013 NoProtoType = CGF.getContext().getPointerType(NoProtoType);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00002014 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002015 }
2016 }
Eli Friedmana0544d62011-12-03 04:14:32 +00002017 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
John McCall7f416cc2015-09-08 08:05:57 +00002018 return CGF.MakeAddrLValue(V, E->getType(), Alignment, AlignmentSource::Decl);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002019}
2020
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00002021static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2022 llvm::Value *ThisValue) {
2023 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2024 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2025 return CGF.EmitLValueForField(LV, FD);
2026}
2027
Renato Golin230c5eb2014-05-19 18:15:42 +00002028/// Named Registers are named metadata pointing to the register name
2029/// which will be read from/written to as an argument to the intrinsic
2030/// @llvm.read/write_register.
2031/// So far, only the name is being passed down, but other options such as
2032/// register type, allocation type or even optimization options could be
2033/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002034static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002035 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002036 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002037 assert(Asm->getLabel().size() < 64-Name.size() &&
2038 "Register name too big");
2039 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002040 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002041 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002042 if (M->getNumOperands() == 0) {
2043 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2044 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002045 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002046 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2047 }
John McCall7f416cc2015-09-08 08:05:57 +00002048
2049 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2050
2051 llvm::Value *Ptr =
2052 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2053 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002054}
2055
Chris Lattnerd7f58862007-06-02 05:24:33 +00002056LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002057 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002058 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002059
Renato Goline7b3d5d2014-05-27 16:46:27 +00002060 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2061 // Global Named registers access via intrinsics only
2062 if (VD->getStorageClass() == SC_Register &&
2063 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002064 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002065
Renato Goline7b3d5d2014-05-27 16:46:27 +00002066 // A DeclRefExpr for a reference initialized by a constant expression can
2067 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002068 const Expr *Init = VD->getAnyInitializer(VD);
2069 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2070 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002071 VD->checkInitIsICE() &&
2072 // Do not emit if it is private OpenMP variable.
2073 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2074 LocalDeclMap.count(VD))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002075 llvm::Constant *Val =
2076 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2077 assert(Val && "failed to emit reference constant expression");
2078 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002079
2080 // Should we be using the alignment of the constant pointer we emitted?
2081 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2082 /*pointee*/ true);
2083
2084 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
Richard Smith5a1104b2012-10-20 01:38:33 +00002085 }
David Majnemer602cfe72015-01-01 09:49:44 +00002086
2087 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002088 if (E->refersToEnclosingVariableOrCapture()) {
David Majnemer602cfe72015-01-01 09:49:44 +00002089 if (auto *FD = LambdaCaptureFields.lookup(VD))
2090 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2091 else if (CapturedStmtInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002092 auto it = LocalDeclMap.find(VD);
2093 if (it != LocalDeclMap.end()) {
2094 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2095 return EmitLoadOfReferenceLValue(it->second, RefTy);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002096 }
John McCall7f416cc2015-09-08 08:05:57 +00002097 return MakeAddrLValue(it->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002098 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002099 LValue CapLVal =
2100 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2101 CapturedStmtInfo->getContextValue());
2102 return MakeAddrLValue(
2103 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2104 CapLVal.getType(), AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002105 }
John McCall7f416cc2015-09-08 08:05:57 +00002106
David Majnemer602cfe72015-01-01 09:49:44 +00002107 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002108 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2109 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002110 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002111 }
2112
Eli Friedman5720e342012-01-21 04:52:58 +00002113 // FIXME: We should be able to assert this for FunctionDecls as well!
2114 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2115 // those with a valid source location.
2116 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2117 !E->getLocation().isValid()) &&
2118 "Should not use decl without marking it used!");
2119
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002120 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002121 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002122 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2123 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002124 }
2125
Renato Goline7b3d5d2014-05-27 16:46:27 +00002126 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002127 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002128 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002129 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002130
John McCall7f416cc2015-09-08 08:05:57 +00002131 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002132
John McCall7f416cc2015-09-08 08:05:57 +00002133 // The variable should generally be present in the local decl map.
2134 auto iter = LocalDeclMap.find(VD);
2135 if (iter != LocalDeclMap.end()) {
2136 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002137
John McCall7f416cc2015-09-08 08:05:57 +00002138 // Otherwise, it might be static local we haven't emitted yet for
2139 // some reason; most likely, because it's in an outer function.
2140 } else if (VD->isStaticLocal()) {
2141 addr = Address(CGM.getOrCreateStaticVarDecl(
2142 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2143 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002144
John McCall7f416cc2015-09-08 08:05:57 +00002145 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002146 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002147 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2148 }
2149
2150
2151 // Check for OpenMP threadprivate variables.
2152 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2153 return EmitThreadPrivateVarDeclLValue(
2154 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2155 E->getExprLoc());
2156 }
2157
2158 // Drill into block byref variables.
2159 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2160 if (isBlockByref) {
2161 addr = emitBlockByrefAddress(addr, VD);
2162 }
2163
2164 // Drill into reference types.
2165 LValue LV;
2166 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2167 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2168 } else {
2169 LV = MakeAddrLValue(addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002170 }
Chris Lattner3f32d692011-07-12 06:52:18 +00002171
John McCallcdda29c2013-03-13 03:10:54 +00002172 bool isLocalStorage = VD->hasLocalStorage();
2173
2174 bool NonGCable = isLocalStorage &&
2175 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002176 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002177 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002178 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002179 LV.setNonGC(true);
2180 }
John McCallcdda29c2013-03-13 03:10:54 +00002181
2182 bool isImpreciseLifetime =
2183 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2184 if (isImpreciseLifetime)
2185 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002186 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002187 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002188 }
John McCallf3a88602011-02-03 08:15:49 +00002189
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002190 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002191 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002192
David Blaikie83d382b2011-09-23 05:06:16 +00002193 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002194}
Chris Lattnere47e4402007-06-01 18:02:12 +00002195
Chris Lattner8394d792007-06-05 20:53:16 +00002196LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2197 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002198 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002199 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002200
Chris Lattner0f398c42008-07-26 22:37:01 +00002201 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002202 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002203 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002204 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002205 QualType T = E->getSubExpr()->getType()->getPointeeType();
2206 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002207
John McCall7f416cc2015-09-08 08:05:57 +00002208 AlignmentSource AlignSource;
2209 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &AlignSource);
2210 LValue LV = MakeAddrLValue(Addr, T, AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002211 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002212
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002213 // We should not generate __weak write barrier on indirect reference
2214 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2215 // But, we continue to generate __strong write barrier on indirect write
2216 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002217 if (getLangOpts().ObjC1 &&
2218 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002219 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002220 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002221 return LV;
2222 }
John McCalle3027922010-08-25 11:45:40 +00002223 case UO_Real:
2224 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002225 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002226 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002227
Richard Smith0b6b8e42012-02-18 20:53:32 +00002228 // __real is valid on scalars. This is a faster way of testing that.
2229 // __imag can only produce an rvalue on scalars.
2230 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002231 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002232 assert(E->getSubExpr()->getType()->isArithmeticType());
2233 return LV;
2234 }
2235
2236 assert(E->getSubExpr()->getType()->isAnyComplexType());
2237
John McCall7f416cc2015-09-08 08:05:57 +00002238 Address Component =
2239 (E->getOpcode() == UO_Real
2240 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2241 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
2242 return MakeAddrLValue(Component, ExprTy, LV.getAlignmentSource());
Chris Lattner595db862007-10-30 22:53:42 +00002243 }
John McCalle3027922010-08-25 11:45:40 +00002244 case UO_PreInc:
2245 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002246 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002247 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002248
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002249 if (E->getType()->isAnyComplexType())
2250 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2251 else
2252 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2253 return LV;
2254 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002255 }
Chris Lattner8394d792007-06-05 20:53:16 +00002256}
2257
Chris Lattner4347e3692007-06-06 04:54:52 +00002258LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002259 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
John McCall7f416cc2015-09-08 08:05:57 +00002260 E->getType(), AlignmentSource::Decl);
Chris Lattner4347e3692007-06-06 04:54:52 +00002261}
2262
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002263LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002264 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
John McCall7f416cc2015-09-08 08:05:57 +00002265 E->getType(), AlignmentSource::Decl);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002266}
2267
Mike Stump4a3999f2009-09-09 13:00:44 +00002268LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002269 auto SL = E->getFunctionName();
2270 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2271 StringRef FnName = CurFn->getName();
2272 if (FnName.startswith("\01"))
2273 FnName = FnName.substr(1);
2274 StringRef NameItems[] = {
2275 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2276 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002277 if (CurCodeDecl && isa<BlockDecl>(CurCodeDecl)) {
John McCall7f416cc2015-09-08 08:05:57 +00002278 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2279 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002280 }
Alexey Bataevec474782014-10-09 08:45:04 +00002281 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
John McCall7f416cc2015-09-08 08:05:57 +00002282 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002283}
2284
Richard Smithe30752c2012-10-09 19:52:38 +00002285/// Emit a type description suitable for use by a runtime sanitizer library. The
2286/// format of a type descriptor is
2287///
2288/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002289/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002290/// \endcode
2291///
Richard Smith683398a2012-10-09 23:55:19 +00002292/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2293/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002294llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002295 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002296 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002297 return C;
2298
Richard Smithe30752c2012-10-09 19:52:38 +00002299 uint16_t TypeKind = -1;
2300 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002301
Richard Smithe30752c2012-10-09 19:52:38 +00002302 if (T->isIntegerType()) {
2303 TypeKind = 0;
2304 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002305 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002306 } else if (T->isFloatingType()) {
2307 TypeKind = 1;
2308 TypeInfo = getContext().getTypeSize(T);
2309 }
2310
2311 // Format the type name as if for a diagnostic, including quotes and
2312 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002313 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002314 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2315 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002316 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002317 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002318
2319 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002320 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2321 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002322 };
2323 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2324
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002325 auto *GV = new llvm::GlobalVariable(
2326 CGM.getModule(), Descriptor->getType(),
2327 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Richard Smithe30752c2012-10-09 19:52:38 +00002328 GV->setUnnamedAddr(true);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002329 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002330
2331 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002332 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002333
Richard Smithe30752c2012-10-09 19:52:38 +00002334 return GV;
2335}
2336
2337llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2338 llvm::Type *TargetTy = IntPtrTy;
2339
Richard Smith48366f72013-03-22 00:47:07 +00002340 // Floating-point types which fit into intptr_t are bitcast to integers
2341 // and then passed directly (after zero-extension, if necessary).
2342 if (V->getType()->isFloatingPointTy()) {
2343 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2344 if (Bits <= TargetTy->getIntegerBitWidth())
2345 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2346 Bits));
2347 }
2348
Richard Smithe30752c2012-10-09 19:52:38 +00002349 // Integers which fit in intptr_t are zero-extended and passed directly.
2350 if (V->getType()->isIntegerTy() &&
2351 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2352 return Builder.CreateZExt(V, TargetTy);
2353
2354 // Pointers are passed directly, everything else is passed by address.
2355 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002356 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002357 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002358 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002359 }
2360 return Builder.CreatePtrToInt(V, TargetTy);
2361}
2362
2363/// \brief Emit a representation of a SourceLocation for passing to a handler
2364/// in a sanitizer runtime library. The format for this data is:
2365/// \code
2366/// struct SourceLocation {
2367/// const char *Filename;
2368/// int32_t Line, Column;
2369/// };
2370/// \endcode
2371/// For an invalid SourceLocation, the Filename pointer is null.
2372llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002373 llvm::Constant *Filename;
2374 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002375
Alexey Samsonov6c124142014-07-18 17:50:06 +00002376 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2377 if (PLoc.isValid()) {
Filipe Cabecinhasab731f72016-05-12 16:51:36 +00002378 StringRef FilenameString = PLoc.getFilename();
2379
2380 int PathComponentsToStrip =
2381 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2382 if (PathComponentsToStrip < 0) {
2383 assert(PathComponentsToStrip != INT_MIN);
2384 int PathComponentsToKeep = -PathComponentsToStrip;
2385 auto I = llvm::sys::path::rbegin(FilenameString);
2386 auto E = llvm::sys::path::rend(FilenameString);
2387 while (I != E && --PathComponentsToKeep)
2388 ++I;
2389
2390 FilenameString = FilenameString.substr(I - E);
2391 } else if (PathComponentsToStrip > 0) {
2392 auto I = llvm::sys::path::begin(FilenameString);
2393 auto E = llvm::sys::path::end(FilenameString);
2394 while (I != E && PathComponentsToStrip--)
2395 ++I;
2396
2397 if (I != E)
2398 FilenameString =
2399 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2400 else
2401 FilenameString = llvm::sys::path::filename(FilenameString);
2402 }
2403
2404 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002405 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2406 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2407 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002408 Line = PLoc.getLine();
2409 Column = PLoc.getColumn();
2410 } else {
2411 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2412 Line = Column = 0;
2413 }
2414
2415 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2416 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002417
2418 return llvm::ConstantStruct::getAnon(Data);
2419}
2420
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002421namespace {
2422/// \brief Specify under what conditions this check can be recovered
2423enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002424 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002425 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002426 /// Check supports recovering, runtime has both fatal (noreturn) and
2427 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002428 Recoverable,
2429 /// Runtime conditionally aborts, always need to support recovery.
2430 AlwaysRecoverable
2431};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002432}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002433
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002434static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2435 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002436 switch (Kind) {
2437 case SanitizerKind::Vptr:
2438 return CheckRecoverableKind::AlwaysRecoverable;
2439 case SanitizerKind::Return:
2440 case SanitizerKind::Unreachable:
2441 return CheckRecoverableKind::Unrecoverable;
2442 default:
2443 return CheckRecoverableKind::Recoverable;
2444 }
2445}
2446
Alexey Samsonov88459522015-01-12 22:39:12 +00002447static void emitCheckHandlerCall(CodeGenFunction &CGF,
2448 llvm::FunctionType *FnType,
2449 ArrayRef<llvm::Value *> FnArgs,
2450 StringRef CheckName,
2451 CheckRecoverableKind RecoverKind, bool IsFatal,
2452 llvm::BasicBlock *ContBB) {
2453 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2454 bool NeedsAbortSuffix =
2455 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2456 std::string FnName = ("__ubsan_handle_" + CheckName +
2457 (NeedsAbortSuffix ? "_abort" : "")).str();
2458 bool MayReturn =
2459 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2460
2461 llvm::AttrBuilder B;
2462 if (!MayReturn) {
2463 B.addAttribute(llvm::Attribute::NoReturn)
2464 .addAttribute(llvm::Attribute::NoUnwind);
2465 }
2466 B.addAttribute(llvm::Attribute::UWTable);
2467
2468 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2469 FnType, FnName,
2470 llvm::AttributeSet::get(CGF.getLLVMContext(),
2471 llvm::AttributeSet::FunctionIndex, B));
2472 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2473 if (!MayReturn) {
2474 HandlerCall->setDoesNotReturn();
2475 CGF.Builder.CreateUnreachable();
2476 } else {
2477 CGF.Builder.CreateBr(ContBB);
2478 }
2479}
2480
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002481void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002482 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002483 StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
2484 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002485 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002486 assert(Checked.size() > 0);
Alexey Samsonov88459522015-01-12 22:39:12 +00002487
2488 llvm::Value *FatalCond = nullptr;
2489 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002490 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002491 for (int i = 0, n = Checked.size(); i < n; ++i) {
2492 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002493 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002494 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002495 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2496 ? TrapCond
2497 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2498 ? RecoverableCond
2499 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002500 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2501 }
2502
Peter Collingbourne9881b782015-06-18 23:59:22 +00002503 if (TrapCond)
2504 EmitTrapCheck(TrapCond);
2505 if (!FatalCond && !RecoverableCond)
2506 return;
2507
Alexey Samsonov88459522015-01-12 22:39:12 +00002508 llvm::Value *JointCond;
2509 if (FatalCond && RecoverableCond)
2510 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2511 else
2512 JointCond = FatalCond ? FatalCond : RecoverableCond;
2513 assert(JointCond);
2514
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002515 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002516 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002517#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002518 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002519 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002520 "All recoverable kinds in a single check must be same!");
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002521 assert(SanOpts.has(Checked[i].second));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002522 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002523#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002524
Richard Smith4d1458e2012-09-08 02:08:36 +00002525 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002526 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2527 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002528 // Give hint that we very much don't expect to execute the handler
2529 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2530 llvm::MDBuilder MDHelper(getLLVMContext());
2531 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2532 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002533 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002534
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002535 // Handler functions take an i8* pointing to the (handler-specific) static
2536 // information block, followed by a sequence of intptr_t arguments
2537 // representing operand values.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002538 SmallVector<llvm::Value *, 4> Args;
2539 SmallVector<llvm::Type *, 4> ArgTypes;
Richard Smithe30752c2012-10-09 19:52:38 +00002540 Args.reserve(DynamicArgs.size() + 1);
2541 ArgTypes.reserve(DynamicArgs.size() + 1);
2542
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002543 // Emit handler arguments and create handler function type.
2544 if (!StaticArgs.empty()) {
2545 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2546 auto *InfoPtr =
2547 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2548 llvm::GlobalVariable::PrivateLinkage, Info);
2549 InfoPtr->setUnnamedAddr(true);
2550 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2551 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2552 ArgTypes.push_back(Int8PtrTy);
2553 }
2554
Richard Smithe30752c2012-10-09 19:52:38 +00002555 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2556 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2557 ArgTypes.push_back(IntPtrTy);
2558 }
2559
2560 llvm::FunctionType *FnType =
2561 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002562
Alexey Samsonov88459522015-01-12 22:39:12 +00002563 if (!FatalCond || !RecoverableCond) {
2564 // Simple case: we need to generate a single handler call, either
2565 // fatal, or non-fatal.
2566 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind,
2567 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002568 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002569 // Emit two handler calls: first one for set of unrecoverable checks,
2570 // another one for recoverable.
2571 llvm::BasicBlock *NonFatalHandlerBB =
2572 createBasicBlock("non_fatal." + CheckName);
2573 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2574 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2575 EmitBlock(FatalHandlerBB);
2576 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, true,
2577 NonFatalHandlerBB);
2578 EmitBlock(NonFatalHandlerBB);
2579 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, false,
2580 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002581 }
Richard Smithe30752c2012-10-09 19:52:38 +00002582
Richard Smith4d1458e2012-09-08 02:08:36 +00002583 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002584}
2585
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002586void CodeGenFunction::EmitCfiSlowPathCheck(
2587 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2588 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002589 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2590
2591 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2592 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2593
2594 llvm::MDBuilder MDHelper(getLLVMContext());
2595 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2596 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2597
2598 EmitBlock(CheckBB);
2599
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002600 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2601
2602 llvm::CallInst *CheckCall;
2603 if (WithDiag) {
2604 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2605 auto *InfoPtr =
2606 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2607 llvm::GlobalVariable::PrivateLinkage, Info);
2608 InfoPtr->setUnnamedAddr(true);
2609 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2610
2611 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2612 "__cfi_slowpath_diag",
2613 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2614 false));
2615 CheckCall = Builder.CreateCall(
2616 SlowPathDiagFn,
2617 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2618 } else {
2619 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2620 "__cfi_slowpath",
2621 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2622 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2623 }
2624
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002625 CheckCall->setDoesNotThrow();
2626
2627 EmitBlock(Cont);
2628}
2629
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002630// This function is basically a switch over the CFI failure kind, which is
2631// extracted from CFICheckFailData (1st function argument). Each case is either
2632// llvm.trap or a call to one of the two runtime handlers, based on
2633// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2634// failure kind) traps, but this should really never happen. CFICheckFailData
2635// can be nullptr if the calling module has -fsanitize-trap behavior for this
2636// check kind; in this case __cfi_check_fail traps as well.
2637void CodeGenFunction::EmitCfiCheckFail() {
2638 SanitizerScope SanScope(this);
2639 FunctionArgList Args;
2640 ImplicitParamDecl ArgData(getContext(), nullptr, SourceLocation(), nullptr,
2641 getContext().VoidPtrTy);
2642 ImplicitParamDecl ArgAddr(getContext(), nullptr, SourceLocation(), nullptr,
2643 getContext().VoidPtrTy);
2644 Args.push_back(&ArgData);
2645 Args.push_back(&ArgAddr);
2646
John McCallc56a8b32016-03-11 04:30:31 +00002647 const CGFunctionInfo &FI =
2648 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002649
2650 llvm::Function *F = llvm::Function::Create(
2651 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2652 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2653 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2654
2655 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2656 SourceLocation());
2657
2658 llvm::Value *Data =
2659 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2660 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2661 llvm::Value *Addr =
2662 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2663 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2664
2665 // Data == nullptr means the calling module has trap behaviour for this check.
2666 llvm::Value *DataIsNotNullPtr =
2667 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2668 EmitTrapCheck(DataIsNotNullPtr);
2669
2670 llvm::StructType *SourceLocationTy =
2671 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty, nullptr);
2672 llvm::StructType *CfiCheckFailDataTy =
2673 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy, nullptr);
2674
2675 llvm::Value *V = Builder.CreateConstGEP2_32(
2676 CfiCheckFailDataTy,
2677 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2678 0);
2679 Address CheckKindAddr(V, getIntAlign());
2680 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2681
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002682 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2683 CGM.getLLVMContext(),
2684 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2685 llvm::Value *ValidVtable = Builder.CreateZExt(
2686 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::bitset_test),
2687 {Addr, AllVtables}),
2688 IntPtrTy);
2689
Evgeniy Stepanov4d3b0872016-01-25 23:45:37 +00002690 const std::pair<int, SanitizerMask> CheckKinds[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002691 {CFITCK_VCall, SanitizerKind::CFIVCall},
2692 {CFITCK_NVCall, SanitizerKind::CFINVCall},
2693 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
2694 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
2695 {CFITCK_ICall, SanitizerKind::CFIICall}};
2696
2697 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
2698 for (auto CheckKindMaskPair : CheckKinds) {
2699 int Kind = CheckKindMaskPair.first;
2700 SanitizerMask Mask = CheckKindMaskPair.second;
2701 llvm::Value *Cond =
2702 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002703 if (CGM.getLangOpts().Sanitize.has(Mask))
2704 EmitCheck(std::make_pair(Cond, Mask), "cfi_check_fail", {},
2705 {Data, Addr, ValidVtable});
2706 else
2707 EmitTrapCheck(Cond);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002708 }
2709
2710 FinishFunction();
2711 // The only reference to this function will be created during LTO link.
2712 // Make sure it survives until then.
2713 CGM.addUsedGlobal(F);
2714}
2715
Chad Rosierae229d52013-01-29 23:31:22 +00002716void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00002717 llvm::BasicBlock *Cont = createBasicBlock("cont");
2718
2719 // If we're optimizing, collapse all calls to trap down to just one per
2720 // function to save on code size.
2721 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2722 TrapBB = createBasicBlock("trap");
2723 Builder.CreateCondBr(Checked, Cont, TrapBB);
2724 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002725 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00002726 TrapCall->setDoesNotReturn();
2727 TrapCall->setDoesNotThrow();
2728 Builder.CreateUnreachable();
2729 } else {
2730 Builder.CreateCondBr(Checked, Cont, TrapBB);
2731 }
2732
2733 EmitBlock(Cont);
2734}
2735
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002736llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00002737 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002738
2739 if (!CGM.getCodeGenOpts().TrapFuncName.empty())
2740 TrapCall->addAttribute(llvm::AttributeSet::FunctionIndex,
2741 "trap-func-name",
2742 CGM.getCodeGenOpts().TrapFuncName);
2743
2744 return TrapCall;
2745}
2746
John McCall7f416cc2015-09-08 08:05:57 +00002747Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
2748 AlignmentSource *AlignSource) {
2749 assert(E->getType()->isArrayType() &&
2750 "Array to pointer decay must have array source type!");
2751
2752 // Expressions of array type can't be bitfields or vector elements.
2753 LValue LV = EmitLValue(E);
2754 Address Addr = LV.getAddress();
2755 if (AlignSource) *AlignSource = LV.getAlignmentSource();
2756
2757 // If the array type was an incomplete type, we need to make sure
2758 // the decay ends up being the right type.
2759 llvm::Type *NewTy = ConvertType(E->getType());
2760 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2761
2762 // Note that VLA pointers are always decayed, so we don't need to do
2763 // anything here.
2764 if (!E->getType()->isVariableArrayType()) {
2765 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2766 "Expected pointer to array");
2767 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2768 }
2769
2770 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2771 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2772}
2773
Chris Lattner6c5abe82010-06-26 23:03:20 +00002774/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2775/// array to pointer, return the array subexpression.
2776static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2777 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002778 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00002779 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00002780 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002781
Chris Lattner6c5abe82010-06-26 23:03:20 +00002782 // If this is a decay from variable width array, bail out.
2783 const Expr *SubExpr = CE->getSubExpr();
2784 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00002785 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002786
Chris Lattner6c5abe82010-06-26 23:03:20 +00002787 return SubExpr;
2788}
2789
John McCall7f416cc2015-09-08 08:05:57 +00002790static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
2791 llvm::Value *ptr,
2792 ArrayRef<llvm::Value*> indices,
2793 bool inbounds,
2794 const llvm::Twine &name = "arrayidx") {
2795 if (inbounds) {
2796 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name);
2797 } else {
2798 return CGF.Builder.CreateGEP(ptr, indices, name);
2799 }
2800}
2801
2802static CharUnits getArrayElementAlign(CharUnits arrayAlign,
2803 llvm::Value *idx,
2804 CharUnits eltSize) {
2805 // If we have a constant index, we can use the exact offset of the
2806 // element we're accessing.
2807 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
2808 CharUnits offset = constantIdx->getZExtValue() * eltSize;
2809 return arrayAlign.alignmentAtOffset(offset);
2810
2811 // Otherwise, use the worst-case alignment for any element.
2812 } else {
2813 return arrayAlign.alignmentOfArrayElement(eltSize);
2814 }
2815}
2816
2817static QualType getFixedSizeElementType(const ASTContext &ctx,
2818 const VariableArrayType *vla) {
2819 QualType eltType;
2820 do {
2821 eltType = vla->getElementType();
2822 } while ((vla = ctx.getAsVariableArrayType(eltType)));
2823 return eltType;
2824}
2825
2826static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
2827 ArrayRef<llvm::Value*> indices,
2828 QualType eltType, bool inbounds,
2829 const llvm::Twine &name = "arrayidx") {
2830 // All the indices except that last must be zero.
2831#ifndef NDEBUG
2832 for (auto idx : indices.drop_back())
2833 assert(isa<llvm::ConstantInt>(idx) &&
2834 cast<llvm::ConstantInt>(idx)->isZero());
2835#endif
2836
2837 // Determine the element size of the statically-sized base. This is
2838 // the thing that the indices are expressed in terms of.
2839 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
2840 eltType = getFixedSizeElementType(CGF.getContext(), vla);
2841 }
2842
2843 // We can use that to compute the best alignment of the element.
2844 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
2845 CharUnits eltAlign =
2846 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
2847
2848 llvm::Value *eltPtr =
2849 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name);
2850 return Address(eltPtr, eltAlign);
2851}
2852
Richard Smith539e4a72013-02-23 02:53:19 +00002853LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2854 bool Accessed) {
Ted Kremenekc81614d2007-08-20 16:18:38 +00002855 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner2da04b32007-08-24 05:35:26 +00002856 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Eli Friedman07bbeca2009-06-06 19:09:26 +00002857 QualType IdxTy = E->getIdx()->getType();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002858 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Eli Friedman07bbeca2009-06-06 19:09:26 +00002859
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002860 if (SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00002861 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
2862
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002863 // If the base is a vector type, then we are forming a vector element lvalue
2864 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002865 if (E->getBase()->getType()->isVectorType() &&
2866 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002867 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00002868 LValue LHS = EmitLValue(E->getBase());
Ted Kremenekc81614d2007-08-20 16:18:38 +00002869 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Eli Friedman327944b2008-06-13 23:01:12 +00002870 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
John McCall7f416cc2015-09-08 08:05:57 +00002871 E->getBase()->getType(),
2872 LHS.getAlignmentSource());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002873 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002874
John McCall7f416cc2015-09-08 08:05:57 +00002875 // All the other cases basically behave like simple offsetting.
2876
Ted Kremenekc81614d2007-08-20 16:18:38 +00002877 // Extend or truncate the index type to 32 or 64-bits.
John McCalle3dc1702011-02-15 09:22:45 +00002878 if (Idx->getType() != IntPtrTy)
2879 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
Mike Stumpd9546382009-12-12 01:27:46 +00002880
John McCall7f416cc2015-09-08 08:05:57 +00002881 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002882 if (isa<ExtVectorElementExpr>(E->getBase())) {
2883 LValue LV = EmitLValue(E->getBase());
John McCall7f416cc2015-09-08 08:05:57 +00002884 Address Addr = EmitExtVectorElementLValue(LV);
2885
2886 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
2887 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true);
2888 return MakeAddrLValue(Addr, EltType, LV.getAlignmentSource());
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002889 }
John McCall7f416cc2015-09-08 08:05:57 +00002890
2891 AlignmentSource AlignSource;
2892 Address Addr = Address::invalid();
2893 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002894 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00002895 // The base must be a pointer, which is not an aggregate. Emit
2896 // it. It needs to be emitted first in case it's what captures
2897 // the VLA bounds.
John McCall7f416cc2015-09-08 08:05:57 +00002898 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00002899
John McCall23c29fe2011-06-24 21:55:10 +00002900 // The element count here is the total number of non-VLA elements.
2901 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00002902
John McCall77527a82011-06-25 01:32:37 +00002903 // Effectively, the multiply by the VLA size is part of the GEP.
2904 // GEP indexes are signed, and scaling an index isn't permitted to
2905 // signed-overflow, so we use the same semantics for our explicit
2906 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002907 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00002908 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00002909 } else {
2910 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00002911 }
John McCall7f416cc2015-09-08 08:05:57 +00002912
2913 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
2914 !getLangOpts().isSignedOverflowDefined());
2915
Chris Lattner6c5abe82010-06-26 23:03:20 +00002916 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
2917 // Indexing over an interface, as in "NSString *P; P[4];"
John McCall7f416cc2015-09-08 08:05:57 +00002918 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
2919 llvm::Value *InterfaceSizeVal =
2920 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());;
Mike Stump4a3999f2009-09-09 13:00:44 +00002921
John McCall7f416cc2015-09-08 08:05:57 +00002922 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002923
John McCall7f416cc2015-09-08 08:05:57 +00002924 // Emit the base pointer.
2925 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
2926
2927 // We don't necessarily build correct LLVM struct types for ObjC
2928 // interfaces, so we can't rely on GEP to do this scaling
2929 // correctly, so we need to cast to i8*. FIXME: is this actually
2930 // true? A lot of other things in the fragile ABI would break...
2931 llvm::Type *OrigBaseTy = Addr.getType();
2932 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
2933
2934 // Do the GEP.
2935 CharUnits EltAlign =
2936 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
2937 llvm::Value *EltPtr =
2938 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false);
2939 Addr = Address(EltPtr, EltAlign);
2940
2941 // Cast back.
2942 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00002943 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
2944 // If this is A[i] where A is an array, the frontend will have decayed the
2945 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
2946 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
2947 // "gep x, i" here. Emit one "gep A, 0, i".
2948 assert(Array->getType()->isArrayType() &&
2949 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00002950 LValue ArrayLV;
2951 // For simple multidimensional array indexing, set the 'accessed' flag for
2952 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002953 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00002954 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
2955 else
2956 ArrayLV = EmitLValue(Array);
Craig Topper99e79272013-07-26 05:59:26 +00002957
Daniel Dunbar82634272011-04-01 00:49:43 +00002958 // Propagate the alignment from the array itself to the result.
John McCall7f416cc2015-09-08 08:05:57 +00002959 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
2960 {CGM.getSize(CharUnits::Zero()), Idx},
2961 E->getType(),
2962 !getLangOpts().isSignedOverflowDefined());
2963 AlignSource = ArrayLV.getAlignmentSource();
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002964 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002965 // The base must be a pointer; emit it with an estimate of its alignment.
2966 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
2967 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
2968 !getLangOpts().isSignedOverflowDefined());
Anders Carlsson3d312f82008-12-21 00:11:23 +00002969 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002970
John McCall7f416cc2015-09-08 08:05:57 +00002971 LValue LV = MakeAddrLValue(Addr, E->getType(), AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00002972
John McCall7f416cc2015-09-08 08:05:57 +00002973 // TODO: Preserve/extend path TBAA metadata?
John McCall8ccfcb52009-09-24 19:53:00 +00002974
Richard Smith9c6890a2012-11-01 22:30:59 +00002975 if (getLangOpts().ObjC1 &&
2976 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00002977 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002978 setObjCGCLValueClass(getContext(), E, LV);
2979 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00002980 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00002981}
2982
Alexey Bataev31300ed2016-02-04 11:27:03 +00002983static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
2984 AlignmentSource &AlignSource,
2985 QualType BaseTy, QualType ElTy,
2986 bool IsLowerBound) {
2987 LValue BaseLVal;
2988 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
2989 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
2990 if (BaseTy->isArrayType()) {
2991 Address Addr = BaseLVal.getAddress();
2992 AlignSource = BaseLVal.getAlignmentSource();
2993
2994 // If the array type was an incomplete type, we need to make sure
2995 // the decay ends up being the right type.
2996 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
2997 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
2998
2999 // Note that VLA pointers are always decayed, so we don't need to do
3000 // anything here.
3001 if (!BaseTy->isVariableArrayType()) {
3002 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3003 "Expected pointer to array");
3004 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3005 "arraydecay");
3006 }
3007
3008 return CGF.Builder.CreateElementBitCast(Addr,
3009 CGF.ConvertTypeForMem(ElTy));
3010 }
3011 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &AlignSource);
3012 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3013 }
3014 return CGF.EmitPointerWithAlignment(Base, &AlignSource);
3015}
3016
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003017LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3018 bool IsLowerBound) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003019 QualType BaseTy;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003020 if (auto *ASE =
3021 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
Alexey Bataev31300ed2016-02-04 11:27:03 +00003022 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003023 else
Alexey Bataev31300ed2016-02-04 11:27:03 +00003024 BaseTy = E->getBase()->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003025 QualType ResultExprTy;
3026 if (auto *AT = getContext().getAsArrayType(BaseTy))
3027 ResultExprTy = AT->getElementType();
3028 else
3029 ResultExprTy = BaseTy->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003030 llvm::Value *Idx = nullptr;
Benjamin Kramer5ff67472016-04-11 08:26:13 +00003031 if (IsLowerBound || E->getColonLoc().isInvalid()) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003032 // Requesting lower bound or upper bound, but without provided length and
3033 // without ':' symbol for the default length -> length = 1.
3034 // Idx = LowerBound ?: 0;
3035 if (auto *LowerBound = E->getLowerBound()) {
3036 Idx = Builder.CreateIntCast(
3037 EmitScalarExpr(LowerBound), IntPtrTy,
3038 LowerBound->getType()->hasSignedIntegerRepresentation());
3039 } else
3040 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3041 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003042 // Try to emit length or lower bound as constant. If this is possible, 1
3043 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3044 // IR (LB + Len) - 1.
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003045 auto &C = CGM.getContext();
3046 auto *Length = E->getLength();
3047 llvm::APSInt ConstLength;
3048 if (Length) {
3049 // Idx = LowerBound + Length - 1;
3050 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3051 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3052 Length = nullptr;
3053 }
3054 auto *LowerBound = E->getLowerBound();
3055 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3056 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3057 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3058 LowerBound = nullptr;
3059 }
3060 if (!Length)
3061 --ConstLength;
3062 else if (!LowerBound)
3063 --ConstLowerBound;
3064
3065 if (Length || LowerBound) {
3066 auto *LowerBoundVal =
3067 LowerBound
3068 ? Builder.CreateIntCast(
3069 EmitScalarExpr(LowerBound), IntPtrTy,
3070 LowerBound->getType()->hasSignedIntegerRepresentation())
3071 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3072 auto *LengthVal =
3073 Length
3074 ? Builder.CreateIntCast(
3075 EmitScalarExpr(Length), IntPtrTy,
3076 Length->getType()->hasSignedIntegerRepresentation())
3077 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3078 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3079 /*HasNUW=*/false,
3080 !getLangOpts().isSignedOverflowDefined());
3081 if (Length && LowerBound) {
3082 Idx = Builder.CreateSub(
3083 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3084 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3085 }
3086 } else
3087 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3088 } else {
3089 // Idx = ArraySize - 1;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003090 QualType ArrayTy = BaseTy->isPointerType()
3091 ? E->getBase()->IgnoreParenImpCasts()->getType()
3092 : BaseTy;
3093 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003094 Length = VAT->getSizeExpr();
3095 if (Length->isIntegerConstantExpr(ConstLength, C))
3096 Length = nullptr;
3097 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003098 auto *CAT = C.getAsConstantArrayType(ArrayTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003099 ConstLength = CAT->getSize();
3100 }
3101 if (Length) {
3102 auto *LengthVal = Builder.CreateIntCast(
3103 EmitScalarExpr(Length), IntPtrTy,
3104 Length->getType()->hasSignedIntegerRepresentation());
3105 Idx = Builder.CreateSub(
3106 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3107 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3108 } else {
3109 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3110 --ConstLength;
3111 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3112 }
3113 }
3114 }
3115 assert(Idx);
3116
Alexey Bataev31300ed2016-02-04 11:27:03 +00003117 Address EltPtr = Address::invalid();
3118 AlignmentSource AlignSource;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003119 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003120 // The base must be a pointer, which is not an aggregate. Emit
3121 // it. It needs to be emitted first in case it's what captures
3122 // the VLA bounds.
3123 Address Base =
3124 emitOMPArraySectionBase(*this, E->getBase(), AlignSource, BaseTy,
3125 VLA->getElementType(), IsLowerBound);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003126 // The element count here is the total number of non-VLA elements.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003127 llvm::Value *NumElements = getVLASize(VLA).first;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003128
3129 // Effectively, the multiply by the VLA size is part of the GEP.
3130 // GEP indexes are signed, and scaling an index isn't permitted to
3131 // signed-overflow, so we use the same semantics for our explicit
3132 // multiply. We suppress this if overflow is not undefined behavior.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003133 if (getLangOpts().isSignedOverflowDefined())
3134 Idx = Builder.CreateMul(Idx, NumElements);
3135 else
3136 Idx = Builder.CreateNSWMul(Idx, NumElements);
3137 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3138 !getLangOpts().isSignedOverflowDefined());
3139 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3140 // If this is A[i] where A is an array, the frontend will have decayed the
3141 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3142 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3143 // "gep x, i" here. Emit one "gep A, 0, i".
3144 assert(Array->getType()->isArrayType() &&
3145 "Array to pointer decay must have array source type!");
3146 LValue ArrayLV;
3147 // For simple multidimensional array indexing, set the 'accessed' flag for
3148 // better bounds-checking of the base expression.
3149 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3150 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3151 else
3152 ArrayLV = EmitLValue(Array);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003153
Alexey Bataev31300ed2016-02-04 11:27:03 +00003154 // Propagate the alignment from the array itself to the result.
3155 EltPtr = emitArraySubscriptGEP(
3156 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3157 ResultExprTy, !getLangOpts().isSignedOverflowDefined());
3158 AlignSource = ArrayLV.getAlignmentSource();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003159 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003160 Address Base = emitOMPArraySectionBase(*this, E->getBase(), AlignSource,
3161 BaseTy, ResultExprTy, IsLowerBound);
3162 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3163 !getLangOpts().isSignedOverflowDefined());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003164 }
3165
Alexey Bataev31300ed2016-02-04 11:27:03 +00003166 return MakeAddrLValue(EltPtr, ResultExprTy, AlignSource);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003167}
3168
Chris Lattner9e751ca2007-08-02 23:37:31 +00003169LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00003170EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00003171 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003172 LValue Base;
3173
3174 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00003175 if (E->isArrow()) {
3176 // If it is a pointer to a vector, emit the address and form an lvalue with
3177 // it.
John McCall7f416cc2015-09-08 08:05:57 +00003178 AlignmentSource AlignSource;
3179 Address Ptr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003180 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
John McCall7f416cc2015-09-08 08:05:57 +00003181 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00003182 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00003183 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00003184 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3185 // emit the base as an lvalue.
3186 assert(E->getBase()->getType()->isVectorType());
3187 Base = EmitLValue(E->getBase());
3188 } else {
3189 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00003190 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00003191 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00003192 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00003193
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00003194 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00003195 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00003196 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00003197 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3198 AlignmentSource::Decl);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003199 }
John McCall1553b192011-06-16 04:16:24 +00003200
3201 QualType type =
3202 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00003203
Nate Begemand3862152008-05-13 21:03:02 +00003204 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00003205 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00003206 E->getEncodedElementAccess(Indices);
3207
3208 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00003209 llvm::Constant *CV =
3210 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00003211 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
John McCall7f416cc2015-09-08 08:05:57 +00003212 Base.getAlignmentSource());
Nate Begemand3862152008-05-13 21:03:02 +00003213 }
3214 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3215
3216 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003217 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00003218
Chris Lattner595ba3a2012-01-30 06:20:36 +00003219 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3220 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00003221 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00003222 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3223 Base.getAlignmentSource());
Chris Lattner9e751ca2007-08-02 23:37:31 +00003224}
3225
Devang Patel30efa2e2007-10-23 20:28:39 +00003226LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00003227 Expr *BaseExpr = E->getBase();
Eli Friedman327944b2008-06-13 23:01:12 +00003228
Chris Lattner4e4186b2007-12-02 18:52:07 +00003229 // 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 +00003230 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00003231 if (E->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00003232 AlignmentSource AlignSource;
3233 Address Addr = EmitPointerWithAlignment(BaseExpr, &AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003234 QualType PtrTy = BaseExpr->getType()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003235 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy);
3236 BaseLV = MakeAddrLValue(Addr, PtrTy, AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003237 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003238 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003239
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003240 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003241 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003242 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003243 setObjCGCLValueClass(getContext(), E, LV);
3244 return LV;
3245 }
Craig Topper99e79272013-07-26 05:59:26 +00003246
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003247 if (auto *VD = dyn_cast<VarDecl>(ND))
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00003248 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003249
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003250 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003251 return EmitFunctionDeclLValue(*this, E, FD);
3252
David Blaikie83d382b2011-09-23 05:06:16 +00003253 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003254}
Devang Patel30efa2e2007-10-23 20:28:39 +00003255
John McCalldec348f72013-05-03 07:33:41 +00003256/// Given that we are currently emitting a lambda, emit an l-value for
3257/// one of its members.
3258LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3259 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3260 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3261 QualType LambdaTagType =
3262 getContext().getTagDeclType(Field->getParent());
3263 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3264 return EmitLValueForField(LambdaLV, Field);
3265}
3266
John McCall7f416cc2015-09-08 08:05:57 +00003267/// Drill down to the storage of a field without walking into
3268/// reference types.
3269///
3270/// The resulting address doesn't necessarily have the right type.
3271static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3272 const FieldDecl *field) {
3273 const RecordDecl *rec = field->getParent();
3274
3275 unsigned idx =
3276 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3277
3278 CharUnits offset;
3279 // Adjust the alignment down to the given offset.
3280 // As a special case, if the LLVM field index is 0, we know that this
3281 // is zero.
3282 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3283 .getFieldOffset(field->getFieldIndex()) == 0) &&
3284 "LLVM field at index zero had non-zero offset?");
3285 if (idx != 0) {
3286 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3287 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3288 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3289 }
3290
3291 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3292}
3293
Eli Friedman7f1ff602012-04-16 03:54:45 +00003294LValue CodeGenFunction::EmitLValueForField(LValue base,
3295 const FieldDecl *field) {
John McCall7f416cc2015-09-08 08:05:57 +00003296 AlignmentSource fieldAlignSource =
3297 getFieldAlignmentSource(base.getAlignmentSource());
3298
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003299 if (field->isBitField()) {
3300 const CGRecordLayout &RL =
3301 CGM.getTypes().getCGRecordLayout(field->getParent());
3302 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003303 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003304 unsigned Idx = RL.getLLVMFieldNo(field);
3305 if (Idx != 0)
3306 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003307 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3308 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003309 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003310 llvm::Type *FieldIntTy =
3311 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3312 if (Addr.getElementType() != FieldIntTy)
3313 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003314
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003315 QualType fieldType =
3316 field->getType().withCVRQualifiers(base.getVRQualifiers());
John McCall7f416cc2015-09-08 08:05:57 +00003317 return LValue::MakeBitfield(Addr, Info, fieldType, fieldAlignSource);
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003318 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003319
John McCall53fcbd22011-02-26 08:07:02 +00003320 const RecordDecl *rec = field->getParent();
3321 QualType type = field->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003322
John McCall53fcbd22011-02-26 08:07:02 +00003323 bool mayAlias = rec->hasAttr<MayAliasAttr>();
3324
John McCall7f416cc2015-09-08 08:05:57 +00003325 Address addr = base.getAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003326 unsigned cvr = base.getVRQualifiers();
Manman Renc451e572013-04-04 21:53:22 +00003327 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
John McCall53fcbd22011-02-26 08:07:02 +00003328 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003329 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00003330 assert(!type->isReferenceType() && "union has reference member");
Manman Renc451e572013-04-04 21:53:22 +00003331 // TODO: handle path-aware TBAA for union.
3332 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003333 } else {
3334 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003335 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003336
3337 // If this is a reference field, load the reference right now.
3338 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3339 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3340 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3341
Manman Renc451e572013-04-04 21:53:22 +00003342 // Loading the reference will disable path-aware TBAA.
3343 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003344 if (CGM.shouldUseTBAA()) {
3345 llvm::MDNode *tbaa;
3346 if (mayAlias)
3347 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3348 else
3349 tbaa = CGM.getTBAAInfo(type);
Manman Ren4f755de2013-10-08 00:08:49 +00003350 if (tbaa)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00003351 CGM.DecorateInstructionWithTBAA(load, tbaa);
John McCall53fcbd22011-02-26 08:07:02 +00003352 }
3353
John McCall53fcbd22011-02-26 08:07:02 +00003354 mayAlias = false;
3355 type = refType->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003356
3357 CharUnits alignment =
3358 getNaturalTypeAlignment(type, &fieldAlignSource, /*pointee*/ true);
3359 addr = Address(load, alignment);
3360
3361 // Qualifiers on the struct don't apply to the referencee, and
3362 // we'll pick up CVR from the actual type later, so reset these
3363 // additional qualifiers now.
3364 cvr = 0;
John McCall53fcbd22011-02-26 08:07:02 +00003365 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003366 }
Craig Topper99e79272013-07-26 05:59:26 +00003367
Chris Lattner13ee4f42011-07-10 05:34:54 +00003368 // Make sure that the address is pointing to the right type. This is critical
3369 // for both unions and structs. A union needs a bitcast, a struct element
3370 // will need a bitcast if the LLVM type laid out doesn't match the desired
3371 // type.
John McCall7f416cc2015-09-08 08:05:57 +00003372 addr = Builder.CreateElementBitCast(addr,
3373 CGM.getTypes().ConvertTypeForMem(type),
3374 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003375
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003376 if (field->hasAttr<AnnotateAttr>())
3377 addr = EmitFieldAnnotations(field, addr);
3378
John McCall7f416cc2015-09-08 08:05:57 +00003379 LValue LV = MakeAddrLValue(addr, type, fieldAlignSource);
John McCall53fcbd22011-02-26 08:07:02 +00003380 LV.getQuals().addCVRQualifiers(cvr);
Manman Renc451e572013-04-04 21:53:22 +00003381 if (TBAAPath) {
3382 const ASTRecordLayout &Layout =
3383 getContext().getASTRecordLayout(field->getParent());
3384 // Set the base type to be the base type of the base LValue and
3385 // update offset to be relative to the base type.
Manman Ren0e521662013-04-27 00:39:37 +00003386 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3387 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
Manman Renc451e572013-04-04 21:53:22 +00003388 Layout.getFieldOffset(field->getFieldIndex()) /
3389 getContext().getCharWidth());
3390 }
Daniel Dunbarf166a522010-08-21 03:44:13 +00003391
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003392 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003393 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3394 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003395
3396 // Fields of may_alias structs act like 'char' for TBAA purposes.
3397 // FIXME: this should get propagated down through anonymous structs
3398 // and unions.
3399 if (mayAlias && LV.getTBAAInfo())
3400 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3401
Daniel Dunbarf166a522010-08-21 03:44:13 +00003402 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003403}
3404
Craig Topper99e79272013-07-26 05:59:26 +00003405LValue
3406CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003407 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003408 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003409
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003410 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003411 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003412
John McCall7f416cc2015-09-08 08:05:57 +00003413 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003414
John McCall7f416cc2015-09-08 08:05:57 +00003415 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003416 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003417 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003418
John McCall7f416cc2015-09-08 08:05:57 +00003419 // TODO: access-path TBAA?
3420 auto FieldAlignSource = getFieldAlignmentSource(Base.getAlignmentSource());
3421 return MakeAddrLValue(V, FieldType, FieldAlignSource);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003422}
3423
Chris Lattnerf53c0962010-09-06 00:11:41 +00003424LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00003425 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003426 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3427 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
Richard Smith2d988f02011-11-22 22:48:32 +00003428 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003429 if (E->getType()->isVariablyModifiedType())
3430 // make sure to emit the VLA size.
3431 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003432
John McCall7f416cc2015-09-08 08:05:57 +00003433 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003434 const Expr *InitExpr = E->getInitializer();
John McCall7f416cc2015-09-08 08:05:57 +00003435 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003436
Chad Rosier615ed1a2012-03-29 17:37:10 +00003437 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3438 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003439
3440 return Result;
3441}
3442
Richard Smithbb653bd2012-05-14 21:57:21 +00003443LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3444 if (!E->isGLValue())
3445 // Initializing an aggregate temporary in C++11: T{...}.
3446 return EmitAggExprToLValue(E);
3447
3448 // An lvalue initializer list must be initializing a reference.
3449 assert(E->getNumInits() == 1 && "reference init with multiple values");
3450 return EmitLValue(E->getInit(0));
3451}
3452
Richard Smithf3076ff2014-06-20 18:43:47 +00003453/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3454/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3455/// LValue is returned and the current block has been terminated.
3456static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3457 const Expr *Operand) {
3458 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3459 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3460 return None;
3461 }
3462
3463 return CGF.EmitLValue(Operand);
3464}
3465
John McCallc07a0c72011-02-17 10:25:35 +00003466LValue CodeGenFunction::
3467EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3468 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003469 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003470 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003471 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003472 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003473 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003474
Eli Friedman59954892012-01-25 05:04:17 +00003475 OpaqueValueMapping binding(*this, expr);
3476
John McCallc07a0c72011-02-17 10:25:35 +00003477 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003478 bool CondExprBool;
3479 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003480 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003481 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003482
Justin Bogneref512b92014-01-06 22:27:43 +00003483 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003484 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003485 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003486 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003487 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003488 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003489 }
3490
John McCallc07a0c72011-02-17 10:25:35 +00003491 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3492 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3493 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003494
3495 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003496 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003497
John McCall0a6bf2e2011-01-26 19:21:13 +00003498 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003499 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003500 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003501 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003502 Optional<LValue> lhs =
3503 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003504 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003505
Richard Smithf3076ff2014-06-20 18:43:47 +00003506 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003507 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003508
John McCallc07a0c72011-02-17 10:25:35 +00003509 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003510 if (lhs)
3511 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003512
John McCall0a6bf2e2011-01-26 19:21:13 +00003513 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003514 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003515 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003516 Optional<LValue> rhs =
3517 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003518 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003519 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003520 return EmitUnsupportedLValue(expr, "conditional operator");
3521 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003522
John McCallc07a0c72011-02-17 10:25:35 +00003523 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003524
Richard Smithf3076ff2014-06-20 18:43:47 +00003525 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003526 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003527 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003528 phi->addIncoming(lhs->getPointer(), lhsBlock);
3529 phi->addIncoming(rhs->getPointer(), rhsBlock);
3530 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3531 AlignmentSource alignSource =
3532 std::max(lhs->getAlignmentSource(), rhs->getAlignmentSource());
3533 return MakeAddrLValue(result, expr->getType(), alignSource);
Richard Smithf3076ff2014-06-20 18:43:47 +00003534 } else {
3535 assert((lhs || rhs) &&
3536 "both operands of glvalue conditional are throw-expressions?");
3537 return lhs ? *lhs : *rhs;
3538 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003539}
3540
Richard Smithbb653bd2012-05-14 21:57:21 +00003541/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3542/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003543/// otherwise if a cast is needed by the code generator in an lvalue context,
3544/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003545/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003546/// are permitted with aggregate result, including noop aggregate casts, and
3547/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003548LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003549 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003550 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003551 case CK_BitCast:
3552 case CK_ArrayToPointerDecay:
3553 case CK_FunctionToPointerDecay:
3554 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003555 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003556 case CK_IntegralToPointer:
3557 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003558 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003559 case CK_VectorSplat:
3560 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00003561 case CK_BooleanToSignedIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003562 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003563 case CK_IntegralToFloating:
3564 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003565 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003566 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003567 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003568 case CK_FloatingComplexToReal:
3569 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003570 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003571 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003572 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003573 case CK_IntegralComplexToReal:
3574 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003575 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003576 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003577 case CK_DerivedToBaseMemberPointer:
3578 case CK_BaseToDerivedMemberPointer:
3579 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003580 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003581 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003582 case CK_ARCProduceObject:
3583 case CK_ARCConsumeObject:
3584 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003585 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003586 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003587 case CK_AddressSpaceConversion:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003588 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3589
3590 case CK_Dependent:
3591 llvm_unreachable("dependent cast kind in IR gen!");
3592
3593 case CK_BuiltinFnToFnPtr:
3594 llvm_unreachable("builtin functions are handled elsewhere");
3595
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003596 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003597 case CK_NonAtomicToAtomic:
3598 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003599 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00003600
Anders Carlsson8a01a752011-04-11 02:03:26 +00003601 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00003602 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003603 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003604 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00003605 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00003606 }
3607
John McCalle3027922010-08-25 11:45:40 +00003608 case CK_ConstructorConversion:
3609 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00003610 case CK_CPointerToObjCPointerCast:
3611 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003612 case CK_NoOp:
3613 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003614 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00003615
John McCalle3027922010-08-25 11:45:40 +00003616 case CK_UncheckedDerivedToBase:
3617 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00003618 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00003619 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003620 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003621
Anders Carlssond95f9602009-09-12 16:16:49 +00003622 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003623 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00003624
Anders Carlssond95f9602009-09-12 16:16:49 +00003625 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00003626 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00003627 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3628 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00003629
John McCall7f416cc2015-09-08 08:05:57 +00003630 return MakeAddrLValue(Base, E->getType(), LV.getAlignmentSource());
Anders Carlssond95f9602009-09-12 16:16:49 +00003631 }
John McCalle3027922010-08-25 11:45:40 +00003632 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00003633 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00003634 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00003635 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003636 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003637
Anders Carlsson8c793172009-11-23 17:57:54 +00003638 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00003639
Anders Carlsson8c793172009-11-23 17:57:54 +00003640 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00003641 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00003642 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00003643 E->path_begin(), E->path_end(),
3644 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00003645
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003646 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3647 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00003648 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003649 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00003650 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003651
Peter Collingbourned2926c92015-03-14 02:42:25 +00003652 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003653 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3654 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003655 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003656
John McCall7f416cc2015-09-08 08:05:57 +00003657 return MakeAddrLValue(Derived, E->getType(), LV.getAlignmentSource());
Eli Friedman8c98dff2009-11-16 05:48:01 +00003658 }
John McCalle3027922010-08-25 11:45:40 +00003659 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00003660 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003661 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00003662
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00003663 CGM.EmitExplicitCastExprType(CE, this);
Anders Carlsson50cb3212009-11-14 21:21:42 +00003664 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003665 Address V = Builder.CreateBitCast(LV.getAddress(),
3666 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00003667
3668 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003669 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3670 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003671 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003672
John McCall7f416cc2015-09-08 08:05:57 +00003673 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Anders Carlsson50cb3212009-11-14 21:21:42 +00003674 }
John McCalle3027922010-08-25 11:45:40 +00003675 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003676 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003677 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3678 ConvertType(E->getType()));
3679 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003680 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003681 case CK_ZeroToOCLEvent:
3682 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00003683 }
Craig Topper99e79272013-07-26 05:59:26 +00003684
Douglas Gregorcdb466e2010-07-15 18:58:16 +00003685 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003686}
3687
John McCall1bf58462011-02-16 08:02:54 +00003688LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00003689 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00003690 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00003691}
3692
Eli Friedman7f1ff602012-04-16 03:54:45 +00003693RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003694 const FieldDecl *FD,
3695 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003696 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003697 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00003698 switch (getEvaluationKind(FT)) {
3699 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003700 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00003701 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00003702 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00003703 case TEK_Scalar:
Reid Kleckner9d031092016-05-02 22:42:34 +00003704 // This routine is used to load fields one-by-one to perform a copy, so
3705 // don't load reference fields.
3706 if (FD->getType()->isReferenceType())
3707 return RValue::get(FieldLV.getPointer());
Nick Lewycky2d84e842013-10-02 02:29:49 +00003708 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00003709 }
3710 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003711}
Douglas Gregorfe314812011-06-21 17:03:29 +00003712
Chris Lattnere47e4402007-06-01 18:02:12 +00003713//===--------------------------------------------------------------------===//
3714// Expression Emission
3715//===--------------------------------------------------------------------===//
3716
Craig Topper99e79272013-07-26 05:59:26 +00003717RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00003718 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003719 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003720 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00003721 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003722
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003723 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003724 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003725
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003726 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00003727 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3728
Douglas Gregore0e96302011-09-06 21:41:04 +00003729 const Decl *TargetDecl = E->getCalleeDecl();
3730 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
3731 if (unsigned builtinID = FD->getBuiltinID())
Peter Collingbournef7706832014-12-12 23:41:25 +00003732 return EmitBuiltinExpr(FD, builtinID, E, ReturnValue);
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003733 }
3734
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003735 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
Anders Carlsson4034a952009-05-27 04:18:27 +00003736 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003737 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003738
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003739 if (const auto *PseudoDtor =
3740 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
John McCall31168b02011-06-15 23:02:42 +00003741 QualType DestroyedType = PseudoDtor->getDestroyedType();
John McCall460ce582015-10-22 18:38:17 +00003742 if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003743 // Automatic Reference Counting:
3744 // If the pseudo-expression names a retainable object with weak or
3745 // strong lifetime, the object shall be released.
John McCall31168b02011-06-15 23:02:42 +00003746 Expr *BaseExpr = PseudoDtor->getBase();
John McCall7f416cc2015-09-08 08:05:57 +00003747 Address BaseValue = Address::invalid();
John McCall31168b02011-06-15 23:02:42 +00003748 Qualifiers BaseQuals;
Craig Topper99e79272013-07-26 05:59:26 +00003749
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003750 // 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 +00003751 if (PseudoDtor->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00003752 BaseValue = EmitPointerWithAlignment(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00003753 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
3754 BaseQuals = PTy->getPointeeType().getQualifiers();
3755 } else {
3756 LValue BaseLV = EmitLValue(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00003757 BaseValue = BaseLV.getAddress();
3758 QualType BaseTy = BaseExpr->getType();
3759 BaseQuals = BaseTy.getQualifiers();
3760 }
Craig Topper99e79272013-07-26 05:59:26 +00003761
John McCall460ce582015-10-22 18:38:17 +00003762 switch (DestroyedType.getObjCLifetime()) {
John McCall31168b02011-06-15 23:02:42 +00003763 case Qualifiers::OCL_None:
3764 case Qualifiers::OCL_ExplicitNone:
3765 case Qualifiers::OCL_Autoreleasing:
3766 break;
Craig Topper99e79272013-07-26 05:59:26 +00003767
John McCall31168b02011-06-15 23:02:42 +00003768 case Qualifiers::OCL_Strong:
Craig Topper99e79272013-07-26 05:59:26 +00003769 EmitARCRelease(Builder.CreateLoad(BaseValue,
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003770 PseudoDtor->getDestroyedType().isVolatileQualified()),
John McCallcdda29c2013-03-13 03:10:54 +00003771 ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00003772 break;
3773
3774 case Qualifiers::OCL_Weak:
3775 EmitARCDestroyWeak(BaseValue);
3776 break;
3777 }
3778 } else {
3779 // C++ [expr.pseudo]p1:
3780 // The result shall only be used as the operand for the function call
3781 // operator (), and the result of such a call has type void. The only
3782 // effect is the evaluation of the postfix-expression before the dot or
Craig Topper99e79272013-07-26 05:59:26 +00003783 // arrow.
John McCall31168b02011-06-15 23:02:42 +00003784 EmitScalarExpr(E->getCallee());
3785 }
Craig Topper99e79272013-07-26 05:59:26 +00003786
Craig Topper8a13c412014-05-21 05:09:00 +00003787 return RValue::get(nullptr);
Douglas Gregorad8a3362009-09-04 17:36:40 +00003788 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003789
Chris Lattner2da04b32007-08-24 05:35:26 +00003790 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003791 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
3792 TargetDecl);
Chris Lattner9e47ead2007-08-31 04:44:06 +00003793}
3794
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003795LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00003796 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00003797 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00003798 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00003799 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00003800 return EmitLValue(E->getRHS());
3801 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003802
John McCalle3027922010-08-25 11:45:40 +00003803 if (E->getOpcode() == BO_PtrMemD ||
3804 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003805 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003806
John McCalla2342eb2010-12-05 02:00:02 +00003807 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00003808
3809 // Note that in all of these cases, __block variables need the RHS
3810 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00003811
3812 switch (getEvaluationKind(E->getType())) {
3813 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00003814 switch (E->getLHS()->getType().getObjCLifetime()) {
3815 case Qualifiers::OCL_Strong:
3816 return EmitARCStoreStrong(E, /*ignored*/ false).first;
3817
3818 case Qualifiers::OCL_Autoreleasing:
3819 return EmitARCStoreAutoreleasing(E).first;
3820
3821 // No reason to do any of these differently.
3822 case Qualifiers::OCL_None:
3823 case Qualifiers::OCL_ExplicitNone:
3824 case Qualifiers::OCL_Weak:
3825 break;
3826 }
3827
John McCalld0a30012010-12-06 06:10:02 +00003828 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00003829 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
John McCall55e1fbc2011-06-25 02:11:03 +00003830 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00003831 return LV;
3832 }
John McCall4f29b492010-11-16 23:07:28 +00003833
John McCall47fb9502013-03-07 21:37:08 +00003834 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00003835 return EmitComplexAssignmentLValue(E);
3836
John McCall47fb9502013-03-07 21:37:08 +00003837 case TEK_Aggregate:
3838 return EmitAggExprToLValue(E);
3839 }
3840 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003841}
3842
Christopher Lambd91c3d42007-12-29 05:02:41 +00003843LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00003844 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00003845
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003846 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00003847 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3848 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00003849
David Majnemerced8bdf2015-02-25 17:36:15 +00003850 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003851 "Can't have a scalar return unless the return type is a "
3852 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00003853
John McCall7f416cc2015-09-08 08:05:57 +00003854 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00003855}
3856
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003857LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
3858 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00003859 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003860}
3861
Anders Carlsson3be22e22009-05-30 23:23:33 +00003862LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003863 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
3864 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00003865 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00003866 EmitCXXConstructExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003867 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3868 AlignmentSource::Decl);
Anders Carlsson3be22e22009-05-30 23:23:33 +00003869}
3870
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003871LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00003872CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003873 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00003874}
3875
John McCall7f416cc2015-09-08 08:05:57 +00003876Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
3877 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
3878 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00003879}
3880
3881LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003882 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
3883 AlignmentSource::Decl);
Nico Webercf4ff5862012-10-11 10:13:44 +00003884}
3885
Mike Stumpc9b231c2009-11-15 08:09:41 +00003886LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003887CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003888 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00003889 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00003890 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003891 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
3892 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3893 AlignmentSource::Decl);
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003894}
3895
Eli Friedman5bc17122012-02-08 05:34:55 +00003896LValue
3897CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00003898 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00003899 EmitLambdaExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003900 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3901 AlignmentSource::Decl);
Eli Friedman5bc17122012-02-08 05:34:55 +00003902}
3903
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003904LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003905 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00003906
Anders Carlsson280e61f12010-06-21 20:59:55 +00003907 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00003908 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3909 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00003910
Alp Toker314cc812014-01-25 16:55:45 +00003911 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00003912 "Can't have a scalar return unless the return type is a "
3913 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00003914
John McCall7f416cc2015-09-08 08:05:57 +00003915 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003916}
3917
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003918LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003919 Address V =
3920 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
3921 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003922}
3923
Daniel Dunbar722f4242009-04-22 05:08:15 +00003924llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003925 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00003926 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003927}
3928
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003929LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
3930 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003931 const ObjCIvarDecl *Ivar,
3932 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00003933 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00003934 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003935}
3936
3937LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003938 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00003939 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003940 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00003941 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003942 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003943 if (E->isArrow()) {
3944 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003945 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00003946 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003947 } else {
3948 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00003949 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003950 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00003951 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003952 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003953
Craig Topper99e79272013-07-26 05:59:26 +00003954 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00003955 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
3956 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00003957 setObjCGCLValueClass(getContext(), E, LV);
3958 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00003959}
3960
Chris Lattnera4185c52009-04-25 19:35:26 +00003961LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00003962 // Can only get l-value for message expression returning aggregate type
3963 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00003964 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3965 AlignmentSource::Decl);
Chris Lattnera4185c52009-04-25 19:35:26 +00003966}
3967
Anders Carlsson0435ed52009-12-24 19:08:58 +00003968RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003969 const CallExpr *E, ReturnValueSlot ReturnValue,
Samuel Antao798f11c2015-11-23 22:04:44 +00003970 CGCalleeInfo CalleeInfo, llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00003971 // Get the actual function type. The callee type will always be a pointer to
3972 // function type or a block pointer type.
3973 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00003974 "Call must have function pointer type!");
3975
Samuel Antao798f11c2015-11-23 22:04:44 +00003976 // Preserve the non-canonical function type because things like exception
3977 // specifications disappear in the canonical type. That information is useful
3978 // to drive the generation of more accurate code for this call later on.
3979 const FunctionProtoType *NonCanonicalFTP = CalleeType->getAs<PointerType>()
3980 ->getPointeeType()
3981 ->getAs<FunctionProtoType>();
3982
3983 const Decl *TargetDecl = CalleeInfo.getCalleeDecl();
3984
Eric Christopher2b2d56f2015-11-12 00:44:12 +00003985 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
Eric Christopher39db7262015-11-14 01:56:04 +00003986 // We can only guarantee that a function is called from the correct
3987 // context/function based on the appropriate target attributes,
3988 // so only check in the case where we have both always_inline and target
3989 // since otherwise we could be making a conditional call after a check for
3990 // the proper cpu features (and it won't cause code generation issues due to
3991 // function based code generation).
Eric Christopher2b2d56f2015-11-12 00:44:12 +00003992 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
3993 TargetDecl->hasAttr<TargetAttr>())
3994 checkTargetFeatures(E, FD);
3995
John McCall6fd4c232009-10-23 08:22:42 +00003996 CalleeType = getContext().getCanonicalType(CalleeType);
3997
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003998 const auto *FnType =
3999 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00004000
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004001 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004002 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4003 if (llvm::Constant *PrefixSig =
4004 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00004005 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004006 llvm::Constant *FTRTTIConst =
4007 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4008 llvm::Type *PrefixStructTyElems[] = {
4009 PrefixSig->getType(),
4010 FTRTTIConst->getType()
4011 };
4012 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4013 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4014
4015 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
4016 Callee, llvm::PointerType::getUnqual(PrefixStructTy));
4017 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004018 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00004019 llvm::Value *CalleeSig =
4020 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004021 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4022
4023 llvm::BasicBlock *Cont = createBasicBlock("cont");
4024 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4025 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4026
4027 EmitBlock(TypeCheck);
4028 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004029 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
John McCall7f416cc2015-09-08 08:05:57 +00004030 llvm::Value *CalleeRTTI =
4031 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004032 llvm::Value *CalleeRTTIMatch =
4033 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4034 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004035 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004036 EmitCheckTypeDescriptor(CalleeType)
4037 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00004038 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
4039 "function_type_mismatch", StaticData, Callee);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004040
4041 Builder.CreateBr(Cont);
4042 EmitBlock(Cont);
4043 }
4044 }
4045
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004046 // If we are checking indirect calls and this call is indirect, check that the
4047 // function pointer is a member of the bit set for the function type.
4048 if (SanOpts.has(SanitizerKind::CFIICall) &&
4049 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4050 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00004051 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004052
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004053 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
4054 llvm::Value *BitSetName = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004055
4056 llvm::Value *CastedCallee = Builder.CreateBitCast(Callee, Int8PtrTy);
4057 llvm::Value *BitSetTest =
4058 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::bitset_test),
4059 {CastedCallee, BitSetName});
4060
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004061 auto TypeId = CGM.CreateCfiIdForTypeMetadata(MD);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004062 llvm::Constant *StaticData[] = {
4063 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4064 EmitCheckSourceLocation(E->getLocStart()),
4065 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4066 };
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004067 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && TypeId) {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004068 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, BitSetTest, TypeId,
4069 CastedCallee, StaticData);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004070 } else {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004071 EmitCheck(std::make_pair(BitSetTest, SanitizerKind::CFIICall),
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004072 "cfi_check_fail", StaticData,
4073 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004074 }
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004075 }
4076
Daniel Dunbarc722b852008-08-30 03:02:31 +00004077 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00004078 if (Chain)
4079 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4080 CGM.getContext().VoidPtrTy);
David Blaikief05779e2015-07-21 18:37:18 +00004081 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
4082 E->getDirectCallee(), /*ParamsToSkip*/ 0);
Daniel Dunbarc722b852008-08-30 03:02:31 +00004083
Peter Collingbournef7706832014-12-12 23:41:25 +00004084 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4085 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00004086
4087 // C99 6.5.2.2p6:
4088 // If the expression that denotes the called function has a type
4089 // that does not include a prototype, [the default argument
4090 // promotions are performed]. If the number of arguments does not
4091 // equal the number of parameters, the behavior is undefined. If
4092 // the function is defined with a type that includes a prototype,
4093 // and either the prototype ends with an ellipsis (, ...) or the
4094 // types of the arguments after promotion are not compatible with
4095 // the types of the parameters, the behavior is undefined. If the
4096 // function is defined with a type that does not include a
4097 // prototype, and the types of the arguments after promotion are
4098 // not compatible with those of the parameters after promotion,
4099 // the behavior is undefined [except in some trivial cases].
4100 // That is, in the general case, we should assume that a call
4101 // through an unprototyped function type works like a *non-variadic*
4102 // call. The way we make this work is to cast to the exact type
4103 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00004104 //
4105 // Chain calls use this same code path to add the invisible chain parameter
4106 // to the function type.
4107 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00004108 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00004109 CalleeTy = CalleeTy->getPointerTo();
4110 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
4111 }
4112
Samuel Antao798f11c2015-11-23 22:04:44 +00004113 return EmitCall(FnInfo, Callee, ReturnValue, Args,
4114 CGCalleeInfo(NonCanonicalFTP, TargetDecl));
Daniel Dunbar97db84c2008-08-23 03:46:30 +00004115}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004116
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004117LValue CodeGenFunction::
4118EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004119 Address BaseAddr = Address::invalid();
4120 if (E->getOpcode() == BO_PtrMemI) {
4121 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4122 } else {
4123 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4124 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004125
John McCallc134eb52010-08-31 21:07:20 +00004126 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4127
4128 const MemberPointerType *MPT
4129 = E->getRHS()->getType()->getAs<MemberPointerType>();
4130
John McCall7f416cc2015-09-08 08:05:57 +00004131 AlignmentSource AlignSource;
4132 Address MemberAddr =
4133 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT,
4134 &AlignSource);
John McCallc134eb52010-08-31 21:07:20 +00004135
John McCall7f416cc2015-09-08 08:05:57 +00004136 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), AlignSource);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004137}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004138
John McCall47fb9502013-03-07 21:37:08 +00004139/// Given the address of a temporary variable, produce an r-value of
4140/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00004141RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004142 QualType type,
4143 SourceLocation loc) {
John McCall7f416cc2015-09-08 08:05:57 +00004144 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
John McCall47fb9502013-03-07 21:37:08 +00004145 switch (getEvaluationKind(type)) {
4146 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004147 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004148 case TEK_Aggregate:
4149 return lvalue.asAggregateRValue();
4150 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004151 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004152 }
4153 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004154}
4155
Duncan Sandse81111c2012-04-10 08:23:07 +00004156void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004157 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00004158 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004159 return;
4160
Duncan Sands65229ed2012-04-16 16:29:47 +00004161 llvm::MDBuilder MDHelper(getLLVMContext());
4162 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004163
Duncan Sands6fc46192012-04-14 12:37:26 +00004164 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004165}
John McCallfe96e0b2011-11-06 09:01:30 +00004166
4167namespace {
4168 struct LValueOrRValue {
4169 LValue LV;
4170 RValue RV;
4171 };
4172}
4173
4174static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4175 const PseudoObjectExpr *E,
4176 bool forLValue,
4177 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004178 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00004179
4180 // Find the result expression, if any.
4181 const Expr *resultExpr = E->getResultExpr();
4182 LValueOrRValue result;
4183
4184 for (PseudoObjectExpr::const_semantics_iterator
4185 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4186 const Expr *semantic = *i;
4187
4188 // If this semantic expression is an opaque value, bind it
4189 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004190 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00004191
4192 // If this is the result expression, we may need to evaluate
4193 // directly into the slot.
4194 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4195 OVMA opaqueData;
4196 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00004197 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00004198 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
4199
John McCall7f416cc2015-09-08 08:05:57 +00004200 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4201 AlignmentSource::Decl);
John McCallfe96e0b2011-11-06 09:01:30 +00004202 opaqueData = OVMA::bind(CGF, ov, LV);
4203 result.RV = slot.asRValue();
4204
4205 // Otherwise, emit as normal.
4206 } else {
4207 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4208
4209 // If this is the result, also evaluate the result now.
4210 if (ov == resultExpr) {
4211 if (forLValue)
4212 result.LV = CGF.EmitLValue(ov);
4213 else
4214 result.RV = CGF.EmitAnyExpr(ov, slot);
4215 }
4216 }
4217
4218 opaques.push_back(opaqueData);
4219
4220 // Otherwise, if the expression is the result, evaluate it
4221 // and remember the result.
4222 } else if (semantic == resultExpr) {
4223 if (forLValue)
4224 result.LV = CGF.EmitLValue(semantic);
4225 else
4226 result.RV = CGF.EmitAnyExpr(semantic, slot);
4227
4228 // Otherwise, evaluate the expression in an ignored context.
4229 } else {
4230 CGF.EmitIgnoredExpr(semantic);
4231 }
4232 }
4233
4234 // Unbind all the opaques now.
4235 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4236 opaques[i].unbind(CGF);
4237
4238 return result;
4239}
4240
4241RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4242 AggValueSlot slot) {
4243 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4244}
4245
4246LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4247 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4248}