blob: e5e34a5f3ed603d1c21e8e14d6fe90a928376b72 [file] [log] [blame]
Chris Lattnere47e4402007-06-01 18:02:12 +00001//===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnere47e4402007-06-01 18:02:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
John McCall5d865c322010-08-31 07:33:07 +000014#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CGCall.h"
Tim Shen421119f2016-07-01 21:08:47 +000016#include "CGCleanup.h"
Devang Pateld3a6b0f2011-03-04 18:54:42 +000017#include "CGDebugInfo.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Alexey Bataev97720002014-11-11 04:05:39 +000019#include "CGOpenMPRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "CGRecordLayout.h"
Tim Shen421119f2016-07-01 21:08:47 +000021#include "CodeGenFunction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "CodeGenModule.h"
John McCallcbc038a2011-09-21 08:08:30 +000023#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000024#include "clang/AST/ASTContext.h"
Renato Golin230c5eb2014-05-19 18:15:42 +000025#include "clang/AST/Attr.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000026#include "clang/AST/DeclObjC.h"
Vedant Kumar4593a462016-12-09 23:48:18 +000027#include "clang/AST/NSAPI.h"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +000028#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "llvm/ADT/Hashing.h"
Alexey Bataevec474782014-10-09 08:45:04 +000030#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000031#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/IR/MDBuilder.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000035#include "llvm/Support/ConvertUTF.h"
Peter Collingbourne3eea6772015-05-11 21:39:14 +000036#include "llvm/Support/MathExtras.h"
Filipe Cabecinhasab731f72016-05-12 16:51:36 +000037#include "llvm/Support/Path.h"
Peter Collingbournedc134532016-01-16 00:31:22 +000038#include "llvm/Transforms/Utils/SanitizerStats.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000039
Filipe Cabecinhas84171bd2016-12-12 16:43:40 +000040#include <string>
41
Chris Lattnere47e4402007-06-01 18:02:12 +000042using namespace clang;
43using namespace CodeGen;
44
Chris Lattnerd7f58862007-06-02 05:24:33 +000045//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000046// Miscellaneous Helper Methods
47//===--------------------------------------------------------------------===//
48
John McCallad7c5c12011-02-08 08:22:06 +000049llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
50 unsigned addressSpace =
51 cast<llvm::PointerType>(value->getType())->getAddressSpace();
52
Chris Lattner2192fe52011-07-18 04:24:23 +000053 llvm::PointerType *destType = Int8PtrTy;
John McCallad7c5c12011-02-08 08:22:06 +000054 if (addressSpace)
55 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
56
57 if (value->getType() == destType) return value;
58 return Builder.CreateBitCast(value, destType);
59}
60
Chris Lattnere9a64532007-06-22 21:44:33 +000061/// CreateTempAlloca - This creates a alloca and inserts it into the entry
62/// block.
John McCall7f416cc2015-09-08 08:05:57 +000063Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
64 const Twine &Name) {
65 auto Alloca = CreateTempAlloca(Ty, Name);
66 Alloca->setAlignment(Align.getQuantity());
67 return Address(Alloca, Align);
68}
69
70/// CreateTempAlloca - This creates a alloca and inserts it into the entry
71/// block.
Chris Lattner2192fe52011-07-18 04:24:23 +000072llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000073 const Twine &Name) {
Craig Topper8a13c412014-05-21 05:09:00 +000074 return new llvm::AllocaInst(Ty, nullptr, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +000075}
Chris Lattner8394d792007-06-05 20:53:16 +000076
John McCall7f416cc2015-09-08 08:05:57 +000077/// CreateDefaultAlignTempAlloca - This creates an alloca with the
78/// default alignment of the corresponding LLVM type, which is *not*
79/// guaranteed to be related in any way to the expected alignment of
80/// an AST type that might have been lowered to Ty.
81Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
82 const Twine &Name) {
83 CharUnits Align =
84 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
85 return CreateTempAlloca(Ty, Align, Name);
86}
87
88void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
89 assert(isa<llvm::AllocaInst>(Var.getPointer()));
90 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
91 Store->setAlignment(Var.getAlignment().getQuantity());
John McCall2e6567a2010-04-22 01:10:34 +000092 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
Duncan P. N. Exon Smith9f5260a2015-11-06 23:00:41 +000093 Block->getInstList().insertAfter(AllocaInsertPt->getIterator(), Store);
John McCall2e6567a2010-04-22 01:10:34 +000094}
95
John McCall7f416cc2015-09-08 08:05:57 +000096Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +000097 CharUnits Align = getContext().getTypeAlignInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +000098 return CreateTempAlloca(ConvertType(Ty), Align, Name);
Daniel Dunbard0049182010-02-16 19:44:13 +000099}
100
John McCall7f416cc2015-09-08 08:05:57 +0000101Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name) {
Daniel Dunbara7566f12010-02-09 02:48:28 +0000102 // FIXME: Should we prefer the preferred type alignment here?
John McCall7f416cc2015-09-08 08:05:57 +0000103 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name);
104}
105
106Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
107 const Twine &Name) {
108 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name);
Daniel Dunbara7566f12010-02-09 02:48:28 +0000109}
110
Chris Lattner8394d792007-06-05 20:53:16 +0000111/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
112/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000113llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000114 PGO.setCurrentStmt(E);
John McCall7a9aac22010-08-23 01:21:21 +0000115 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +0000116 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +0000117 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +0000118 }
John McCall7a9aac22010-08-23 01:21:21 +0000119
120 QualType BoolTy = getContext().BoolTy;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000121 SourceLocation Loc = E->getExprLoc();
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000122 if (!E->getType()->isAnyComplexType())
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000123 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +0000124
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000125 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
126 Loc);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000127}
128
John McCalla2342eb2010-12-05 02:00:02 +0000129/// EmitIgnoredExpr - Emit code to compute the specified expression,
130/// ignoring the result.
131void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
132 if (E->isRValue())
133 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
134
135 // Just emit it as an l-value and drop the result.
136 EmitLValue(E);
137}
138
John McCall7a626f62010-09-15 10:14:12 +0000139/// EmitAnyExpr - Emit code to compute the specified expression which
140/// can have any type. The result is returned as an RValue struct.
141/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000142/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000143RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
144 AggValueSlot aggSlot,
145 bool ignoreResult) {
John McCall47fb9502013-03-07 21:37:08 +0000146 switch (getEvaluationKind(E->getType())) {
147 case TEK_Scalar:
John McCall4e8ca4f2012-07-02 23:58:38 +0000148 return RValue::get(EmitScalarExpr(E, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000149 case TEK_Complex:
John McCall4e8ca4f2012-07-02 23:58:38 +0000150 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000151 case TEK_Aggregate:
152 if (!ignoreResult && aggSlot.isIgnored())
153 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
154 EmitAggExpr(E, aggSlot);
155 return aggSlot.asRValue();
156 }
157 llvm_unreachable("bad evaluation kind");
Chris Lattner4647a212007-08-31 22:49:20 +0000158}
159
Mike Stump4a3999f2009-09-09 13:00:44 +0000160/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
161/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000162RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
163 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000164
John McCall47fb9502013-03-07 21:37:08 +0000165 if (hasAggregateEvaluationKind(E->getType()))
John McCall7a626f62010-09-15 10:14:12 +0000166 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
167 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000168}
169
John McCall21886962010-04-21 10:05:39 +0000170/// EmitAnyExprToMem - Evaluate an expression into a given memory
171/// location.
172void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000173 Address Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000174 Qualifiers Quals,
175 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000176 // FIXME: This function should take an LValue as an argument.
John McCall47fb9502013-03-07 21:37:08 +0000177 switch (getEvaluationKind(E->getType())) {
178 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000179 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
John McCall47fb9502013-03-07 21:37:08 +0000180 /*isInit*/ false);
181 return;
182
183 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000184 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000185 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000186 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000187 AggValueSlot::IsAliased_t(!IsInit)));
John McCall47fb9502013-03-07 21:37:08 +0000188 return;
189 }
190
191 case TEK_Scalar: {
John McCall21886962010-04-21 10:05:39 +0000192 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000193 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000194 EmitStoreThroughLValue(RV, LV);
John McCall47fb9502013-03-07 21:37:08 +0000195 return;
John McCall21886962010-04-21 10:05:39 +0000196 }
John McCall47fb9502013-03-07 21:37:08 +0000197 }
198 llvm_unreachable("bad evaluation kind");
John McCall21886962010-04-21 10:05:39 +0000199}
200
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000201static void
202pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
John McCall7f416cc2015-09-08 08:05:57 +0000203 const Expr *E, Address ReferenceTemporary) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000204 // Objective-C++ ARC:
205 // If we are binding a reference to a temporary that has ownership, we
206 // need to perform retain/release operations on the temporary.
Richard Smith736a9472013-06-12 20:42:33 +0000207 //
208 // FIXME: This should be looking at E, not M.
John McCall460ce582015-10-22 18:38:17 +0000209 if (auto Lifetime = M->getType().getObjCLifetime()) {
210 switch (Lifetime) {
Richard Smith736a9472013-06-12 20:42:33 +0000211 case Qualifiers::OCL_None:
212 case Qualifiers::OCL_ExplicitNone:
213 // Carry on to normal cleanup handling.
214 break;
Sebastian Redl29526f02011-11-27 16:50:07 +0000215
Richard Smith736a9472013-06-12 20:42:33 +0000216 case Qualifiers::OCL_Autoreleasing:
217 // Nothing to do; cleaned up by an autorelease pool.
218 return;
219
220 case Qualifiers::OCL_Strong:
221 case Qualifiers::OCL_Weak:
222 switch (StorageDuration Duration = M->getStorageDuration()) {
223 case SD_Static:
224 // Note: we intentionally do not register a cleanup to release
225 // the object on program termination.
226 return;
227
228 case SD_Thread:
229 // FIXME: We should probably register a cleanup in this case.
230 return;
231
232 case SD_Automatic:
233 case SD_FullExpression:
Richard Smith736a9472013-06-12 20:42:33 +0000234 CodeGenFunction::Destroyer *Destroy;
235 CleanupKind CleanupKind;
236 if (Lifetime == Qualifiers::OCL_Strong) {
237 const ValueDecl *VD = M->getExtendingDecl();
238 bool Precise =
239 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
240 CleanupKind = CGF.getARCCleanupKind();
241 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
242 : &CodeGenFunction::destroyARCStrongImprecise;
243 } else {
244 // __weak objects always get EH cleanups; otherwise, exceptions
245 // could cause really nasty crashes instead of mere leaks.
246 CleanupKind = NormalAndEHCleanup;
247 Destroy = &CodeGenFunction::destroyARCWeak;
248 }
249 if (Duration == SD_FullExpression)
250 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000251 M->getType(), *Destroy,
Richard Smith736a9472013-06-12 20:42:33 +0000252 CleanupKind & EHCleanup);
253 else
254 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
John McCall460ce582015-10-22 18:38:17 +0000255 M->getType(),
Richard Smith736a9472013-06-12 20:42:33 +0000256 *Destroy, CleanupKind & EHCleanup);
257 return;
258
259 case SD_Dynamic:
260 llvm_unreachable("temporary cannot have dynamic storage duration");
261 }
262 llvm_unreachable("unknown storage duration");
263 }
264 }
265
Craig Topper8a13c412014-05-21 05:09:00 +0000266 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
Richard Smith736a9472013-06-12 20:42:33 +0000267 if (const RecordType *RT =
268 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
269 // Get the destructor for the reference temporary.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000270 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith736a9472013-06-12 20:42:33 +0000271 if (!ClassDecl->hasTrivialDestructor())
272 ReferenceTemporaryDtor = ClassDecl->getDestructor();
273 }
274
275 if (!ReferenceTemporaryDtor)
276 return;
277
278 // Call the destructor for the temporary.
279 switch (M->getStorageDuration()) {
280 case SD_Static:
281 case SD_Thread: {
282 llvm::Constant *CleanupFn;
283 llvm::Constant *CleanupArg;
284 if (E->getType()->isArrayType()) {
285 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
John McCall7f416cc2015-09-08 08:05:57 +0000286 ReferenceTemporary, E->getType(),
David Blaikieebe87e12013-08-27 23:57:18 +0000287 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
288 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
Richard Smith736a9472013-06-12 20:42:33 +0000289 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
290 } else {
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000291 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
292 StructorType::Complete);
John McCall7f416cc2015-09-08 08:05:57 +0000293 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
Richard Smith736a9472013-06-12 20:42:33 +0000294 }
295 CGF.CGM.getCXXABI().registerGlobalDtor(
296 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
297 break;
298 }
299
300 case SD_FullExpression:
301 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
302 CodeGenFunction::destroyCXXObject,
303 CGF.getLangOpts().Exceptions);
304 break;
305
306 case SD_Automatic:
307 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
308 ReferenceTemporary, E->getType(),
309 CodeGenFunction::destroyCXXObject,
310 CGF.getLangOpts().Exceptions);
311 break;
312
313 case SD_Dynamic:
314 llvm_unreachable("temporary cannot have dynamic storage duration");
315 }
316}
317
John McCall7f416cc2015-09-08 08:05:57 +0000318static Address
Richard Smith736a9472013-06-12 20:42:33 +0000319createReferenceTemporary(CodeGenFunction &CGF,
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000320 const MaterializeTemporaryExpr *M, const Expr *Inner) {
Richard Smith736a9472013-06-12 20:42:33 +0000321 switch (M->getStorageDuration()) {
322 case SD_FullExpression:
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000323 case SD_Automatic: {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000324 // If we have a constant temporary array or record try to promote it into a
325 // constant global under the same rules a normal constant would've been
326 // promoted. This is easier on the optimizer and generally emits fewer
327 // instructions.
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000328 QualType Ty = Inner->getType();
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000329 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000330 (Ty->isArrayType() || Ty->isRecordType()) &&
331 CGF.CGM.isTypeConstant(Ty, true))
332 if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000333 auto *GV = new llvm::GlobalVariable(
334 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
335 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp");
John McCall7f416cc2015-09-08 08:05:57 +0000336 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
337 GV->setAlignment(alignment.getQuantity());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000338 // FIXME: Should we put the new global into a COMDAT?
John McCall7f416cc2015-09-08 08:05:57 +0000339 return Address(GV, alignment);
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000340 }
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000341 return CGF.CreateMemTemp(Ty, "ref.tmp");
342 }
Richard Smith736a9472013-06-12 20:42:33 +0000343 case SD_Thread:
344 case SD_Static:
Hans Wennborgf9d865b2015-03-17 16:38:58 +0000345 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
Richard Smith736a9472013-06-12 20:42:33 +0000346
347 case SD_Dynamic:
348 llvm_unreachable("temporary can't have dynamic storage duration");
349 }
350 llvm_unreachable("unknown storage duration");
351}
352
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000353LValue CodeGenFunction::
354EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000355 const Expr *E = M->GetTemporaryExpr();
Richard Smith7c5d4dc2013-06-11 02:41:00 +0000356
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000357 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
358 // as that will cause the lifetime adjustment to be lost for ARC
John McCall460ce582015-10-22 18:38:17 +0000359 auto ownership = M->getType().getObjCLifetime();
360 if (ownership != Qualifiers::OCL_None &&
361 ownership != Qualifiers::OCL_ExplicitNone) {
John McCall7f416cc2015-09-08 08:05:57 +0000362 Address Object = createReferenceTemporary(*this, M, E);
363 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
364 Object = Address(llvm::ConstantExpr::getBitCast(Var,
365 ConvertTypeForMem(E->getType())
366 ->getPointerTo(Object.getAddressSpace())),
367 Object.getAlignment());
Akira Hatanakafdacb5c2016-05-13 01:21:23 +0000368
369 // createReferenceTemporary will promote the temporary to a global with a
370 // constant initializer if it can. It can only do this to a value of
371 // ARC-manageable type if the value is global and therefore "immune" to
372 // ref-counting operations. Therefore we have no need to emit either a
373 // dynamic initialization or a cleanup and we can just return the address
374 // of the temporary.
375 if (Var->hasInitializer())
376 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
377
Richard Smitha509f2f2013-06-14 03:07:01 +0000378 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
379 }
John McCall7f416cc2015-09-08 08:05:57 +0000380 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
381 AlignmentSource::Decl);
Richard Smitha509f2f2013-06-14 03:07:01 +0000382
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000383 switch (getEvaluationKind(E->getType())) {
384 default: llvm_unreachable("expected scalar or aggregate expression");
385 case TEK_Scalar:
386 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
387 break;
388 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000389 EmitAggExpr(E, AggValueSlot::forAddr(Object,
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000390 E->getType().getQualifiers(),
391 AggValueSlot::IsDestructed,
392 AggValueSlot::DoesNotNeedGCBarriers,
393 AggValueSlot::IsNotAliased));
394 break;
395 }
396 }
Richard Smith736a9472013-06-12 20:42:33 +0000397
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000398 pushTemporaryCleanup(*this, M, E, Object);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000399 return RefTempDst;
Jordan Roseb1312a52013-04-11 00:58:58 +0000400 }
401
Richard Smithf3fabd22013-06-03 00:17:11 +0000402 SmallVector<const Expr *, 2> CommaLHSs;
Jordan Roseb1312a52013-04-11 00:58:58 +0000403 SmallVector<SubobjectAdjustment, 2> Adjustments;
Richard Smithf3fabd22013-06-03 00:17:11 +0000404 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
405
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000406 for (const auto &Ignored : CommaLHSs)
407 EmitIgnoredExpr(Ignored);
Richard Smithf3fabd22013-06-03 00:17:11 +0000408
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000409 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
Richard Smith736a9472013-06-12 20:42:33 +0000410 if (opaque->getType()->isRecordType()) {
411 assert(Adjustments.empty());
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000412 return EmitOpaqueValueLValue(opaque);
Jordan Roseb1312a52013-04-11 00:58:58 +0000413 }
414 }
415
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000416 // Create and initialize the reference temporary.
John McCall7f416cc2015-09-08 08:05:57 +0000417 Address Object = createReferenceTemporary(*this, M, E);
418 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
419 Object = Address(llvm::ConstantExpr::getBitCast(
420 Var, ConvertTypeForMem(E->getType())->getPointerTo()),
421 Object.getAlignment());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000422 // If the temporary is a global and has a constant initializer or is a
423 // constant temporary that we promoted to a global, we may have already
424 // initialized it.
Richard Smitha509f2f2013-06-14 03:07:01 +0000425 if (!Var->hasInitializer()) {
426 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
427 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
428 }
429 } else {
Tim Shen421119f2016-07-01 21:08:47 +0000430 switch (M->getStorageDuration()) {
431 case SD_Automatic:
432 case SD_FullExpression:
433 if (auto *Size = EmitLifetimeStart(
434 CGM.getDataLayout().getTypeAllocSize(Object.getElementType()),
435 Object.getPointer())) {
436 if (M->getStorageDuration() == SD_Automatic)
437 pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
438 Object, Size);
439 else
440 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Object,
441 Size);
442 }
443 break;
444 default:
445 break;
446 }
Richard Smitha509f2f2013-06-14 03:07:01 +0000447 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
448 }
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000449 pushTemporaryCleanup(*this, M, E, Object);
Jordan Roseb1312a52013-04-11 00:58:58 +0000450
Richard Smith736a9472013-06-12 20:42:33 +0000451 // Perform derived-to-base casts and/or field accesses, to get from the
452 // temporary object we created (and, potentially, for which we extended
453 // the lifetime) to the subobject we're binding the reference to.
454 for (unsigned I = Adjustments.size(); I != 0; --I) {
455 SubobjectAdjustment &Adjustment = Adjustments[I-1];
456 switch (Adjustment.Kind) {
457 case SubobjectAdjustment::DerivedToBaseAdjustment:
458 Object =
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000459 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
460 Adjustment.DerivedToBase.BasePath->path_begin(),
461 Adjustment.DerivedToBase.BasePath->path_end(),
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000462 /*NullCheckValue=*/ false, E->getExprLoc());
Richard Smith736a9472013-06-12 20:42:33 +0000463 break;
Richard Smithf3fabd22013-06-03 00:17:11 +0000464
Richard Smith736a9472013-06-12 20:42:33 +0000465 case SubobjectAdjustment::FieldAdjustment: {
John McCall7f416cc2015-09-08 08:05:57 +0000466 LValue LV = MakeAddrLValue(Object, E->getType(),
467 AlignmentSource::Decl);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000468 LV = EmitLValueForField(LV, Adjustment.Field);
Richard Smith736a9472013-06-12 20:42:33 +0000469 assert(LV.isSimple() &&
470 "materialized temporary field is not a simple lvalue");
471 Object = LV.getAddress();
472 break;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000473 }
474
Richard Smith736a9472013-06-12 20:42:33 +0000475 case SubobjectAdjustment::MemberPointerAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000476 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
John McCall7f416cc2015-09-08 08:05:57 +0000477 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
478 Adjustment.Ptr.MPT);
Richard Smith736a9472013-06-12 20:42:33 +0000479 break;
480 }
481 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000482 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000483
John McCall7f416cc2015-09-08 08:05:57 +0000484 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000485}
486
487RValue
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000488CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
489 // Emit the expression as an lvalue.
490 LValue LV = EmitLValue(E);
491 assert(LV.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000492 llvm::Value *Value = LV.getPointer();
Richard Smith736a9472013-06-12 20:42:33 +0000493
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000494 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000495 // C++11 [dcl.ref]p5 (as amended by core issue 453):
496 // If a glvalue to which a reference is directly bound designates neither
497 // an existing object or function of an appropriate type nor a region of
498 // storage of suitable size and alignment to contain an object of the
499 // reference's type, the behavior is undefined.
500 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000501 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000502 }
John McCall8680f872010-07-21 06:29:51 +0000503
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000504 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000505}
506
507
Mike Stump4a3999f2009-09-09 13:00:44 +0000508/// getAccessedFieldNo - Given an encoded value and a result number, return the
509/// input field number being accessed.
510unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000511 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000512 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
513 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000514}
515
Richard Smith4d3110a2012-10-25 02:14:12 +0000516/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
517static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
518 llvm::Value *High) {
519 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
520 llvm::Value *K47 = Builder.getInt64(47);
521 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
522 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
523 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
524 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
525 return Builder.CreateMul(B1, KMul);
526}
527
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000528bool CodeGenFunction::sanitizePerformTypeCheck() const {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000529 return SanOpts.has(SanitizerKind::Null) |
530 SanOpts.has(SanitizerKind::Alignment) |
531 SanOpts.has(SanitizerKind::ObjectSize) |
532 SanOpts.has(SanitizerKind::Vptr);
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000533}
534
Richard Smithe30752c2012-10-09 19:52:38 +0000535void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +0000536 llvm::Value *Ptr, QualType Ty,
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000537 CharUnits Alignment, bool SkipNullCheck) {
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000538 if (!sanitizePerformTypeCheck())
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000539 return;
540
Richard Smith2d8b2942012-11-01 07:22:08 +0000541 // Don't check pointers outside the default address space. The null check
542 // isn't correct, the object-size check isn't supported by LLVM, and we can't
543 // communicate the addresses to the runtime handler for the vptr check.
John McCall7f416cc2015-09-08 08:05:57 +0000544 if (Ptr->getType()->getPointerAddressSpace())
Richard Smith2d8b2942012-11-01 07:22:08 +0000545 return;
546
Alexey Samsonov24cad992014-07-17 18:46:27 +0000547 SanitizerScope SanScope(this);
548
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000549 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
Craig Topper8a13c412014-05-21 05:09:00 +0000550 llvm::BasicBlock *Done = nullptr;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000551
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000552 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
553 TCK == TCK_UpcastToVirtualBase;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000554 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
555 !SkipNullCheck) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000556 // The glvalue must not be an empty glvalue.
John McCall7f416cc2015-09-08 08:05:57 +0000557 llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr);
Richard Smith2c5868c2013-02-13 21:18:23 +0000558
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000559 if (AllowNullPointers) {
560 // When performing pointer casts, it's OK if the value is null.
Richard Smith2c5868c2013-02-13 21:18:23 +0000561 // Skip the remaining checks in that case.
562 Done = createBasicBlock("null");
563 llvm::BasicBlock *Rest = createBasicBlock("not.null");
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000564 Builder.CreateCondBr(IsNonNull, Rest, Done);
Richard Smith2c5868c2013-02-13 21:18:23 +0000565 EmitBlock(Rest);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +0000566 } else {
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000567 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
Richard Smith2c5868c2013-02-13 21:18:23 +0000568 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000569 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000570
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000571 if (SanOpts.has(SanitizerKind::ObjectSize) && !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000572 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000573
Richard Smith69d0d262012-08-24 00:54:33 +0000574 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000575 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000576 // to check this.
Matt Arsenault2f152632013-10-07 19:00:18 +0000577 // FIXME: Get object address space
578 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
579 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smith69d0d262012-08-24 00:54:33 +0000580 llvm::Value *Min = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +0000581 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
Richard Smith69d0d262012-08-24 00:54:33 +0000582 llvm::Value *LargeEnough =
David Blaikie43f9bb72015-05-18 22:14:03 +0000583 Builder.CreateICmpUGE(Builder.CreateCall(F, {CastAddr, Min}),
Richard Smith69d0d262012-08-24 00:54:33 +0000584 llvm::ConstantInt::get(IntPtrTy, Size));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000585 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
Richard Smithe30752c2012-10-09 19:52:38 +0000586 }
Richard Smith69d0d262012-08-24 00:54:33 +0000587
Richard Smithb1b0ab42012-11-05 22:21:05 +0000588 uint64_t AlignVal = 0;
589
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000590 if (SanOpts.has(SanitizerKind::Alignment)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000591 AlignVal = Alignment.getQuantity();
592 if (!Ty->isIncompleteType() && !AlignVal)
593 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
594
Richard Smith69d0d262012-08-24 00:54:33 +0000595 // The glvalue must be suitably aligned.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000596 if (AlignVal) {
597 llvm::Value *Align =
John McCall7f416cc2015-09-08 08:05:57 +0000598 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
Richard Smithb1b0ab42012-11-05 22:21:05 +0000599 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
600 llvm::Value *Aligned =
601 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000602 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000603 }
Richard Smith69d0d262012-08-24 00:54:33 +0000604 }
605
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000606 if (Checks.size() > 0) {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000607 // Make sure we're not losing information. Alignment needs to be a power of
608 // 2
609 assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
Richard Smithe30752c2012-10-09 19:52:38 +0000610 llvm::Constant *StaticData[] = {
Filipe Cabecinhasfe5e5af2017-01-06 14:40:12 +0000611 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
612 llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
613 llvm::ConstantInt::get(Int8Ty, TCK)};
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000614 EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData, Ptr);
Richard Smithe30752c2012-10-09 19:52:38 +0000615 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000616
Richard Smithb1b0ab42012-11-05 22:21:05 +0000617 // If possible, check that the vptr indicates that there is a subobject of
618 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000619 //
620 // C++11 [basic.life]p5,6:
621 // [For storage which does not refer to an object within its lifetime]
622 // The program has undefined behavior if:
623 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000624 // or call a non-static member function
Richard Smith4d3110a2012-10-25 02:14:12 +0000625 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000626 if (SanOpts.has(SanitizerKind::Vptr) &&
Richard Smith2c5868c2013-02-13 21:18:23 +0000627 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000628 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
629 TCK == TCK_UpcastToVirtualBase) &&
Richard Smith4d3110a2012-10-25 02:14:12 +0000630 RD && RD->hasDefinition() && RD->isDynamicClass()) {
Richard Smith4d3110a2012-10-25 02:14:12 +0000631 // Compute a hash of the mangled name of the type.
632 //
633 // FIXME: This is not guaranteed to be deterministic! Move to a
634 // fingerprinting mechanism once LLVM provides one. For the time
635 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000636 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000637 llvm::raw_svector_ostream Out(MangledName);
638 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
639 Out);
Richard Smith4d3110a2012-10-25 02:14:12 +0000640
Alexey Samsonov84856012014-07-10 22:34:19 +0000641 // Blacklist based on the mangled type.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000642 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
643 Out.str())) {
Alexey Samsonov84856012014-07-10 22:34:19 +0000644 llvm::hash_code TypeHash = hash_value(Out.str());
Richard Smith4d3110a2012-10-25 02:14:12 +0000645
Alexey Samsonov84856012014-07-10 22:34:19 +0000646 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
647 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
648 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
John McCall7f416cc2015-09-08 08:05:57 +0000649 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000650 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
651 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
Richard Smith4d3110a2012-10-25 02:14:12 +0000652
Alexey Samsonov84856012014-07-10 22:34:19 +0000653 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
654 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
Richard Smith4d3110a2012-10-25 02:14:12 +0000655
Alexey Samsonov84856012014-07-10 22:34:19 +0000656 // Look the hash up in our cache.
657 const int CacheSize = 128;
658 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
659 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
660 "__ubsan_vptr_type_cache");
661 llvm::Value *Slot = Builder.CreateAnd(Hash,
662 llvm::ConstantInt::get(IntPtrTy,
663 CacheSize-1));
664 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
665 llvm::Value *CacheVal =
John McCall7f416cc2015-09-08 08:05:57 +0000666 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
667 getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000668
669 // If the hash isn't in the cache, call a runtime handler to perform the
670 // hard work of checking whether the vptr is for an object of the right
671 // type. This will either fill in the cache and return, or produce a
672 // diagnostic.
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000673 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
Alexey Samsonov84856012014-07-10 22:34:19 +0000674 llvm::Constant *StaticData[] = {
675 EmitCheckSourceLocation(Loc),
676 EmitCheckTypeDescriptor(Ty),
677 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
678 llvm::ConstantInt::get(Int8Ty, TCK)
679 };
John McCall7f416cc2015-09-08 08:05:57 +0000680 llvm::Value *DynamicData[] = { Ptr, Hash };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000681 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000682 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
683 DynamicData);
Alexey Samsonov84856012014-07-10 22:34:19 +0000684 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000685 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000686
687 if (Done) {
688 Builder.CreateBr(Done);
689 EmitBlock(Done);
690 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000691}
Chris Lattner4647a212007-08-31 22:49:20 +0000692
Richard Smith539e4a72013-02-23 02:53:19 +0000693/// Determine whether this expression refers to a flexible array member in a
694/// struct. We disable array bounds checks for such members.
695static bool isFlexibleArrayMemberExpr(const Expr *E) {
696 // For compatibility with existing code, we treat arrays of length 0 or
697 // 1 as flexible array members.
698 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000699 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000700 if (CAT->getSize().ugt(1))
701 return false;
702 } else if (!isa<IncompleteArrayType>(AT))
703 return false;
704
705 E = E->IgnoreParens();
706
707 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000708 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000709 // FIXME: If the base type of the member expr is not FD->getParent(),
710 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000711 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith539e4a72013-02-23 02:53:19 +0000712 RecordDecl::field_iterator FI(
713 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
714 return ++FI == FD->getParent()->field_end();
715 }
Vedant Kumare356f1a2016-10-04 20:36:04 +0000716 } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
717 return IRE->getDecl()->getNextIvar() == nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000718 }
719
720 return false;
721}
722
723/// If Base is known to point to the start of an array, return the length of
724/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000725static llvm::Value *getArrayIndexingBound(
726 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000727 // For the vector indexing extension, the bound is the number of elements.
728 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
729 IndexedType = Base->getType();
730 return CGF.Builder.getInt32(VT->getNumElements());
731 }
732
733 Base = Base->IgnoreParens();
734
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000735 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000736 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
737 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
738 IndexedType = CE->getSubExpr()->getType();
739 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000740 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000741 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000742 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000743 return CGF.getVLASize(VAT).first;
744 }
745 }
746
Craig Topper8a13c412014-05-21 05:09:00 +0000747 return nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000748}
749
750void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
751 llvm::Value *Index, QualType IndexType,
752 bool Accessed) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000753 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
Richard Smith6b53e222013-10-22 22:51:04 +0000754 "should not be called unless adding bounds checks");
Alexey Samsonov24cad992014-07-17 18:46:27 +0000755 SanitizerScope SanScope(this);
Richard Smith2847b222013-02-24 01:56:24 +0000756
Richard Smith539e4a72013-02-23 02:53:19 +0000757 QualType IndexedType;
758 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
759 if (!Bound)
760 return;
761
762 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
763 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
764 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
765
766 llvm::Constant *StaticData[] = {
767 EmitCheckSourceLocation(E->getExprLoc()),
768 EmitCheckTypeDescriptor(IndexedType),
769 EmitCheckTypeDescriptor(IndexType)
770 };
771 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
772 : Builder.CreateICmpULE(IndexVal, BoundVal);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000773 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
774 SanitizerHandler::OutOfBounds, StaticData, Index);
Richard Smith539e4a72013-02-23 02:53:19 +0000775}
776
Chris Lattner116ce8f2010-01-09 21:40:03 +0000777
Chris Lattner116ce8f2010-01-09 21:40:03 +0000778CodeGenFunction::ComplexPairTy CodeGenFunction::
779EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
780 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000781 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +0000782
Chris Lattner116ce8f2010-01-09 21:40:03 +0000783 llvm::Value *NextVal;
784 if (isa<llvm::IntegerType>(InVal.first->getType())) {
785 uint64_t AmountVal = isInc ? 1 : -1;
786 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +0000787
Chris Lattner116ce8f2010-01-09 21:40:03 +0000788 // Add the inc/dec to the real part.
789 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
790 } else {
791 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
792 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
793 if (!isInc)
794 FVal.changeSign();
795 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
Craig Topper99e79272013-07-26 05:59:26 +0000796
Chris Lattner116ce8f2010-01-09 21:40:03 +0000797 // Add the inc/dec to the real part.
798 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
799 }
Craig Topper99e79272013-07-26 05:59:26 +0000800
Chris Lattner116ce8f2010-01-09 21:40:03 +0000801 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +0000802
Chris Lattner116ce8f2010-01-09 21:40:03 +0000803 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +0000804 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Craig Topper99e79272013-07-26 05:59:26 +0000805
Chris Lattner116ce8f2010-01-09 21:40:03 +0000806 // If this is a postinc, return the value read from memory, otherwise use the
807 // updated value.
808 return isPre ? IncVal : InVal;
809}
810
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000811void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
812 CodeGenFunction *CGF) {
813 // Bind VLAs in the cast type.
814 if (CGF && E->getType()->isVariablyModifiedType())
815 CGF->EmitVariablyModifiedType(E->getType());
816
817 if (CGDebugInfo *DI = getModuleDebugInfo())
818 DI->EmitExplicitCastType(E->getType());
819}
820
Chris Lattnera45c5af2007-06-02 19:47:04 +0000821//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000822// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000823//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000824
John McCall7f416cc2015-09-08 08:05:57 +0000825/// EmitPointerWithAlignment - Given an expression of pointer type, try to
826/// derive a more accurate bound on the alignment of the pointer.
827Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
828 AlignmentSource *Source) {
829 // We allow this with ObjC object pointers because of fragile ABIs.
830 assert(E->getType()->isPointerType() ||
831 E->getType()->isObjCObjectPointerType());
832 E = E->IgnoreParens();
833
834 // Casts:
835 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000836 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
837 CGM.EmitExplicitCastExprType(ECE, this);
John McCall7f416cc2015-09-08 08:05:57 +0000838
839 switch (CE->getCastKind()) {
840 // Non-converting casts (but not C's implicit conversion from void*).
841 case CK_BitCast:
842 case CK_NoOp:
843 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
844 if (PtrTy->getPointeeType()->isVoidType())
845 break;
846
847 AlignmentSource InnerSource;
848 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerSource);
849 if (Source) *Source = InnerSource;
850
851 // If this is an explicit bitcast, and the source l-value is
852 // opaque, honor the alignment of the casted-to type.
853 if (isa<ExplicitCastExpr>(CE) &&
John McCall7f416cc2015-09-08 08:05:57 +0000854 InnerSource != AlignmentSource::Decl) {
855 Addr = Address(Addr.getPointer(),
856 getNaturalPointeeTypeAlignment(E->getType(), Source));
857 }
858
Peter Collingbourne574975e2016-01-14 02:49:48 +0000859 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
860 CE->getCastKind() == CK_BitCast) {
Peter Collingbourneee381ff2015-09-09 00:01:31 +0000861 if (auto PT = E->getType()->getAs<PointerType>())
862 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
863 /*MayBeNull=*/true,
864 CodeGenFunction::CFITCK_UnrelatedCast,
865 CE->getLocStart());
866 }
867
John McCall7f416cc2015-09-08 08:05:57 +0000868 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
869 }
870 break;
871
872 // Array-to-pointer decay.
873 case CK_ArrayToPointerDecay:
874 return EmitArrayToPointerDecay(CE->getSubExpr(), Source);
875
876 // Derived-to-base conversions.
877 case CK_UncheckedDerivedToBase:
878 case CK_DerivedToBase: {
879 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), Source);
880 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
881 return GetAddressOfBaseClass(Addr, Derived,
882 CE->path_begin(), CE->path_end(),
883 ShouldNullCheckClassCastValue(CE),
884 CE->getExprLoc());
885 }
886
887 // TODO: Is there any reason to treat base-to-derived conversions
888 // specially?
889 default:
890 break;
891 }
892 }
893
894 // Unary &.
895 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
896 if (UO->getOpcode() == UO_AddrOf) {
897 LValue LV = EmitLValue(UO->getSubExpr());
898 if (Source) *Source = LV.getAlignmentSource();
899 return LV.getAddress();
900 }
901 }
902
903 // TODO: conditional operators, comma.
904
905 // Otherwise, use the alignment of the type.
906 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), Source);
907 return Address(EmitScalarExpr(E), Align);
908}
909
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000910RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000911 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +0000912 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +0000913
914 switch (getEvaluationKind(Ty)) {
915 case TEK_Complex: {
916 llvm::Type *EltTy =
917 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +0000918 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000919 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000920 }
Craig Topper99e79272013-07-26 05:59:26 +0000921
Chris Lattner65526f02010-08-23 05:26:13 +0000922 // If this is a use of an undefined aggregate type, the aggregate must have an
923 // identifiable address. Just because the contents of the value are undefined
924 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +0000925 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000926 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +0000927 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000928 }
John McCall47fb9502013-03-07 21:37:08 +0000929
930 case TEK_Scalar:
931 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
932 }
933 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +0000934}
935
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000936RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
937 const char *Name) {
938 ErrorUnsupported(E, Name);
939 return GetUndefRValue(E->getType());
940}
941
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000942LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
943 const char *Name) {
944 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000945 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +0000946 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
947 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000948}
949
Richard Smith4d1458e2012-09-08 02:08:36 +0000950LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +0000951 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000952 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +0000953 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
954 else
955 LV = EmitLValue(E);
Daniel Dunbardc406b82010-04-05 21:36:35 +0000956 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
John McCall7f416cc2015-09-08 08:05:57 +0000957 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
Richard Smithe30752c2012-10-09 19:52:38 +0000958 E->getType(), LV.getAlignment());
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000959 return LV;
960}
961
Chris Lattner8394d792007-06-05 20:53:16 +0000962/// EmitLValue - Emit code to compute a designator that specifies the location
963/// of the expression.
964///
Mike Stump4a3999f2009-09-09 13:00:44 +0000965/// This can return one of two things: a simple address or a bitfield reference.
966/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
967/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +0000968///
Mike Stump4a3999f2009-09-09 13:00:44 +0000969/// If this returns a bitfield reference, nothing about the pointee type of the
970/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +0000971///
Mike Stump4a3999f2009-09-09 13:00:44 +0000972/// If this returns a normal address, and if the lvalue's C type is fixed size,
973/// this method guarantees that the returned pointer type will point to an LLVM
974/// type of the same size of the lvalue's type. If the lvalue has a variable
975/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +0000976///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000977LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +0000978 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +0000979 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000980 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000981
John McCallc109a252011-11-07 03:59:57 +0000982 case Expr::ObjCPropertyRefExprClass:
983 llvm_unreachable("cannot emit a property reference directly");
984
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000985 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +0000986 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000987 case Expr::ObjCIsaExprClass:
988 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000989 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +0000990 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +0000991 case Expr::CompoundAssignOperatorClass: {
992 QualType Ty = E->getType();
993 if (const AtomicType *AT = Ty->getAs<AtomicType>())
994 Ty = AT->getValueType();
995 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +0000996 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
997 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +0000998 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000999 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +00001000 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001001 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00001002 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001003 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00001004 case Expr::VAArgExprClass:
1005 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001006 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001007 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +00001008 case Expr::ParenExprClass:
1009 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +00001010 case Expr::GenericSelectionExprClass:
1011 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +00001012 case Expr::PredefinedExprClass:
1013 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +00001014 case Expr::StringLiteralClass:
1015 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001016 case Expr::ObjCEncodeExprClass:
1017 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +00001018 case Expr::PseudoObjectExprClass:
1019 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001020 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +00001021 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +00001022 case Expr::CXXTemporaryObjectExprClass:
1023 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001024 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1025 case Expr::CXXBindTemporaryExprClass:
1026 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +00001027 case Expr::CXXUuidofExprClass:
1028 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +00001029 case Expr::LambdaExprClass:
1030 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +00001031
1032 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001033 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +00001034 enterFullExpression(cleanups);
1035 RunCleanupsScope Scope(*this);
1036 return EmitLValue(cleanups->getSubExpr());
1037 }
1038
Anders Carlsson52ce3bb2009-11-14 01:51:50 +00001039 case Expr::CXXDefaultArgExprClass:
1040 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001041 case Expr::CXXDefaultInitExprClass: {
1042 CXXDefaultInitExprScope Scope(*this);
1043 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1044 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001045 case Expr::CXXTypeidExprClass:
1046 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001047
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001048 case Expr::ObjCMessageExprClass:
1049 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001050 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001051 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001052 case Expr::StmtExprClass:
1053 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001054 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001055 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001056 case Expr::ArraySubscriptExprClass:
1057 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001058 case Expr::OMPArraySectionExprClass:
1059 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001060 case Expr::ExtVectorElementExprClass:
1061 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001062 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001063 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001064 case Expr::CompoundLiteralExprClass:
1065 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001066 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001067 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001068 case Expr::BinaryConditionalOperatorClass:
1069 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001070 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001071 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001072 case Expr::OpaqueValueExprClass:
1073 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001074 case Expr::SubstNonTypeTemplateParmExprClass:
1075 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001076 case Expr::ImplicitCastExprClass:
1077 case Expr::CStyleCastExprClass:
1078 case Expr::CXXFunctionalCastExprClass:
1079 case Expr::CXXStaticCastExprClass:
1080 case Expr::CXXDynamicCastExprClass:
1081 case Expr::CXXReinterpretCastExprClass:
1082 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001083 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001084 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001085
Douglas Gregorfe314812011-06-21 17:03:29 +00001086 case Expr::MaterializeTemporaryExprClass:
1087 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001088 }
1089}
1090
John McCall71335052012-03-10 03:05:10 +00001091/// Given an object of the given canonical type, can we safely copy a
1092/// value out of it based on its initializer?
1093static bool isConstantEmittableObjectType(QualType type) {
1094 assert(type.isCanonical());
1095 assert(!type->isReferenceType());
1096
1097 // Must be const-qualified but non-volatile.
1098 Qualifiers qs = type.getLocalQualifiers();
1099 if (!qs.hasConst() || qs.hasVolatile()) return false;
1100
1101 // Otherwise, all object types satisfy this except C++ classes with
1102 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001103 if (const auto *RT = dyn_cast<RecordType>(type))
1104 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001105 if (RD->hasMutableFields() || !RD->isTrivial())
1106 return false;
1107
1108 return true;
1109}
1110
1111/// Can we constant-emit a load of a reference to a variable of the
1112/// given type? This is different from predicates like
1113/// Decl::isUsableInConstantExpressions because we do want it to apply
1114/// in situations that don't necessarily satisfy the language's rules
1115/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1116/// to do this with const float variables even if those variables
1117/// aren't marked 'constexpr'.
1118enum ConstantEmissionKind {
1119 CEK_None,
1120 CEK_AsReferenceOnly,
1121 CEK_AsValueOrReference,
1122 CEK_AsValueOnly
1123};
1124static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1125 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001126 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001127 if (isConstantEmittableObjectType(ref->getPointeeType()))
1128 return CEK_AsValueOrReference;
1129 return CEK_AsReferenceOnly;
1130 }
1131 if (isConstantEmittableObjectType(type))
1132 return CEK_AsValueOnly;
1133 return CEK_None;
1134}
1135
1136/// Try to emit a reference to the given value without producing it as
1137/// an l-value. This is actually more than an optimization: we can't
1138/// produce an l-value for variables that we never actually captured
1139/// in a block or lambda, which means const int variables or constexpr
1140/// literals or similar.
1141CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001142CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1143 ValueDecl *value = refExpr->getDecl();
1144
John McCall71335052012-03-10 03:05:10 +00001145 // The value needs to be an enum constant or a constant variable.
1146 ConstantEmissionKind CEK;
1147 if (isa<ParmVarDecl>(value)) {
1148 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001149 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001150 CEK = checkVarTypeForConstantEmission(var->getType());
1151 } else if (isa<EnumConstantDecl>(value)) {
1152 CEK = CEK_AsValueOnly;
1153 } else {
1154 CEK = CEK_None;
1155 }
1156 if (CEK == CEK_None) return ConstantEmission();
1157
John McCall71335052012-03-10 03:05:10 +00001158 Expr::EvalResult result;
1159 bool resultIsReference;
1160 QualType resultType;
1161
1162 // It's best to evaluate all the way as an r-value if that's permitted.
1163 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001164 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001165 resultIsReference = false;
1166 resultType = refExpr->getType();
1167
1168 // Otherwise, try to evaluate as an l-value.
1169 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001170 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001171 resultIsReference = true;
1172 resultType = value->getType();
1173
1174 // Failure.
1175 } else {
1176 return ConstantEmission();
1177 }
1178
1179 // In any case, if the initializer has side-effects, abandon ship.
1180 if (result.HasSideEffects)
1181 return ConstantEmission();
1182
1183 // Emit as a constant.
1184 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1185
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001186 // Make sure we emit a debug reference to the global variable.
1187 // This should probably fire even for
1188 if (isa<VarDecl>(value)) {
1189 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001190 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001191 } else {
1192 assert(isa<EnumConstantDecl>(value));
Peter Collingbourneeeb56ab2016-09-13 01:13:19 +00001193 EmitDeclRefExprDbgValue(refExpr, result.Val);
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001194 }
John McCall71335052012-03-10 03:05:10 +00001195
1196 // If we emitted a reference constant, we need to dereference that.
1197 if (resultIsReference)
1198 return ConstantEmission::forReference(C);
1199
1200 return ConstantEmission::forValue(C);
1201}
1202
Nick Lewycky2d84e842013-10-02 02:29:49 +00001203llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1204 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +00001205 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001206 lvalue.getType(), Loc, lvalue.getAlignmentSource(),
1207 lvalue.getTBAAInfo(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001208 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1209 lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001210}
1211
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001212static bool hasBooleanRepresentation(QualType Ty) {
1213 if (Ty->isBooleanType())
1214 return true;
1215
1216 if (const EnumType *ET = Ty->getAs<EnumType>())
1217 return ET->getDecl()->getIntegerType()->isBooleanType();
1218
Douglas Gregor298f43d2012-04-12 20:42:30 +00001219 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1220 return hasBooleanRepresentation(AT->getValueType());
1221
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001222 return false;
1223}
1224
Richard Smith1629da92012-12-13 07:11:50 +00001225static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1226 llvm::APInt &Min, llvm::APInt &End,
Vedant Kumar4593a462016-12-09 23:48:18 +00001227 bool StrictEnums, bool IsBool) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001228 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001229 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1230 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001231 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001232 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001233
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001234 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001235 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1236 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001237 } else {
1238 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001239 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001240 unsigned Bitwidth = LTy->getScalarSizeInBits();
1241 unsigned NumNegativeBits = ED->getNumNegativeBits();
1242 unsigned NumPositiveBits = ED->getNumPositiveBits();
1243
1244 if (NumNegativeBits) {
1245 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1246 assert(NumBits <= Bitwidth);
1247 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1248 Min = -End;
1249 } else {
1250 assert(NumPositiveBits <= Bitwidth);
1251 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1252 Min = llvm::APInt(Bitwidth, 0);
1253 }
1254 }
Richard Smith1629da92012-12-13 07:11:50 +00001255 return true;
1256}
1257
1258llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1259 llvm::APInt Min, End;
Vedant Kumar4593a462016-12-09 23:48:18 +00001260 if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1261 hasBooleanRepresentation(Ty)))
Craig Topper8a13c412014-05-21 05:09:00 +00001262 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001263
Duncan Sandsc720e782012-04-15 18:04:54 +00001264 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001265 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001266}
1267
John McCall7f416cc2015-09-08 08:05:57 +00001268llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1269 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001270 SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +00001271 AlignmentSource AlignSource,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001272 llvm::MDNode *TBAAInfo,
1273 QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001274 uint64_t TBAAOffset,
1275 bool isNontemporal) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001276 // For better performance, handle vector loads differently.
1277 if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001278 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001279
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001280 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001281
John McCall7f416cc2015-09-08 08:05:57 +00001282 // Handle vectors of size 3 like size 4 for better performance.
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001283 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001284
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001285 // Bitcast to vec4 type.
1286 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
1287 4);
John McCall7f416cc2015-09-08 08:05:57 +00001288 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001289 // Now load value.
John McCall7f416cc2015-09-08 08:05:57 +00001290 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001291
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001292 // Shuffle vector to get vec3.
John McCall7f416cc2015-09-08 08:05:57 +00001293 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
Benjamin Kramer99383102015-07-28 16:25:32 +00001294 {0, 1, 2}, "extractVec");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001295 return EmitFromMemory(V, Ty);
1296 }
1297 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001298
1299 // Atomic operations have to be done on integral types.
David Majnemera38c9f12016-05-24 16:09:25 +00001300 LValue AtomicLValue =
John McCall7f416cc2015-09-08 08:05:57 +00001301 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
David Majnemera38c9f12016-05-24 16:09:25 +00001302 if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1303 return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001304 }
Craig Topper99e79272013-07-26 05:59:26 +00001305
John McCall7f416cc2015-09-08 08:05:57 +00001306 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001307 if (isNontemporal) {
1308 llvm::MDNode *Node = llvm::MDNode::get(
1309 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1310 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1311 }
Manman Renc451e572013-04-04 21:53:22 +00001312 if (TBAAInfo) {
1313 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1314 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001315 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001316 CGM.DecorateInstructionWithTBAA(Load, TBAAPath,
1317 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001318 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001319
Vedant Kumar4593a462016-12-09 23:48:18 +00001320 bool IsBool = hasBooleanRepresentation(Ty) ||
1321 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1322 bool NeedsBoolCheck = SanOpts.has(SanitizerKind::Bool) && IsBool;
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00001323 bool NeedsEnumCheck =
1324 SanOpts.has(SanitizerKind::Enum) && Ty->getAs<EnumType>();
1325 if (NeedsBoolCheck || NeedsEnumCheck) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00001326 SanitizerScope SanScope(this);
Richard Smith1629da92012-12-13 07:11:50 +00001327 llvm::APInt Min, End;
Vedant Kumar4593a462016-12-09 23:48:18 +00001328 if (getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool)) {
Richard Smith1629da92012-12-13 07:11:50 +00001329 --End;
1330 llvm::Value *Check;
1331 if (!Min)
1332 Check = Builder.CreateICmpULE(
1333 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1334 else {
1335 llvm::Value *Upper = Builder.CreateICmpSLE(
1336 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1337 llvm::Value *Lower = Builder.CreateICmpSGE(
1338 Load, llvm::ConstantInt::get(getLLVMContext(), Min));
1339 Check = Builder.CreateAnd(Upper, Lower);
1340 }
Nick Lewycky2d84e842013-10-02 02:29:49 +00001341 llvm::Constant *StaticArgs[] = {
1342 EmitCheckSourceLocation(Loc),
1343 EmitCheckTypeDescriptor(Ty)
1344 };
Peter Collingbourne3eea6772015-05-11 21:39:14 +00001345 SanitizerMask Kind = NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001346 EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1347 StaticArgs, EmitCheckValue(Load));
Richard Smith1629da92012-12-13 07:11:50 +00001348 }
1349 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001350 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1351 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001352
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001353 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001354}
1355
John McCall3a7f6922010-10-27 20:58:56 +00001356llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1357 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001358 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001359 // This should really always be an i1, but sometimes it's already
1360 // an i8, and it's awkward to track those cases down.
1361 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001362 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1363 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1364 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001365 }
1366
1367 return Value;
1368}
1369
1370llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1371 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001372 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001373 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1374 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001375 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1376 }
1377
1378 return Value;
1379}
1380
John McCall7f416cc2015-09-08 08:05:57 +00001381void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1382 bool Volatile, QualType Ty,
1383 AlignmentSource AlignSource,
1384 llvm::MDNode *TBAAInfo,
Manman Renc451e572013-04-04 21:53:22 +00001385 bool isInit, QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001386 uint64_t TBAAOffset,
1387 bool isNontemporal) {
Craig Topper99e79272013-07-26 05:59:26 +00001388
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001389 // Handle vectors differently to get better performance.
1390 if (Ty->isVectorType()) {
1391 llvm::Type *SrcTy = Value->getType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001392 auto *VecTy = cast<llvm::VectorType>(SrcTy);
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001393 // Handle vec3 special.
1394 if (VecTy->getNumElements() == 3) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001395 // Our source is a vec3, do a shuffle vector to make it a vec4.
Benjamin Kramer99383102015-07-28 16:25:32 +00001396 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1397 Builder.getInt32(2),
1398 llvm::UndefValue::get(Builder.getInt32Ty())};
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001399 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1400 Value = Builder.CreateShuffleVector(Value,
1401 llvm::UndefValue::get(VecTy),
1402 MaskV, "extractVec");
1403 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1404 }
John McCall7f416cc2015-09-08 08:05:57 +00001405 if (Addr.getElementType() != SrcTy) {
1406 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001407 }
1408 }
Craig Topper99e79272013-07-26 05:59:26 +00001409
John McCall3a7f6922010-10-27 20:58:56 +00001410 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001411
David Majnemera38c9f12016-05-24 16:09:25 +00001412 LValue AtomicLValue =
1413 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
David Majnemera5b195a2015-02-14 01:35:12 +00001414 if (Ty->isAtomicType() ||
David Majnemera38c9f12016-05-24 16:09:25 +00001415 (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1416 EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
John McCalla8ec7eb2013-03-07 21:37:17 +00001417 return;
1418 }
1419
Daniel Dunbar03816342010-08-21 02:24:36 +00001420 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001421 if (isNontemporal) {
1422 llvm::MDNode *Node =
1423 llvm::MDNode::get(Store->getContext(),
1424 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1425 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1426 }
Manman Renc451e572013-04-04 21:53:22 +00001427 if (TBAAInfo) {
1428 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1429 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001430 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001431 CGM.DecorateInstructionWithTBAA(Store, TBAAPath,
1432 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001433 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001434}
1435
David Chisnallfa35df62012-01-16 17:27:18 +00001436void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001437 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001438 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001439 lvalue.getType(), lvalue.getAlignmentSource(),
Manman Renc451e572013-04-04 21:53:22 +00001440 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001441 lvalue.getTBAAOffset(), lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001442}
1443
Mike Stump4a3999f2009-09-09 13:00:44 +00001444/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1445/// method emits the address of the lvalue, then loads the result as an rvalue,
1446/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001447RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001448 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001449 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001450 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001451 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1452 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001453 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001454 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall460ce582015-10-22 18:38:17 +00001455 // In MRC mode, we do a load+autorelease.
1456 if (!getLangOpts().ObjCAutoRefCount) {
1457 return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1458 }
1459
1460 // In ARC mode, we load retained and then consume the value.
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001461 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1462 Object = EmitObjCConsumeObject(LV.getType(), Object);
1463 return RValue::get(Object);
1464 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001465
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001466 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001467 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001468
John McCalla1dee5302010-08-22 10:59:02 +00001469 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001470 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001471 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001472
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001473 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001474 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001475 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001476 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001477 "vecext"));
1478 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001479
1480 // If this is a reference to a subset of the elements of a vector, either
1481 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001482 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001483 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001484
Renato Golin230c5eb2014-05-19 18:15:42 +00001485 // Global Register variables always invoke intrinsics
1486 if (LV.isGlobalReg())
1487 return EmitLoadOfGlobalRegLValue(LV);
1488
John McCallc109a252011-11-07 03:59:57 +00001489 assert(LV.isBitField() && "Unknown LValue type!");
1490 return EmitLoadOfBitfieldLValue(LV);
Chris Lattner8394d792007-06-05 20:53:16 +00001491}
1492
John McCall55e1fbc2011-06-25 02:11:03 +00001493RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001494 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001495
Daniel Dunbar3447a022010-04-13 23:34:15 +00001496 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001497 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001498
John McCall7f416cc2015-09-08 08:05:57 +00001499 Address Ptr = LV.getBitFieldAddress();
1500 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001501
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001502 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001503 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001504 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1505 if (HighBits)
1506 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1507 if (Info.Offset + HighBits)
1508 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1509 } else {
1510 if (Info.Offset)
1511 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001512 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001513 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1514 Info.Size),
1515 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001516 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001517 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001518
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001519 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001520}
1521
Nate Begemanb699c9b2009-01-18 06:42:49 +00001522// If this is a reference to a subset of the elements of a vector, create an
1523// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001524RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001525 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1526 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001527
Nate Begemanf322eab2008-05-09 06:41:27 +00001528 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001529
1530 // If the result of the expression is a non-vector type, we must be extracting
1531 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001532 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001533 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001534 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001535 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001536 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001537 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001538
1539 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001540 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001541
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001542 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001543 for (unsigned i = 0; i != NumResultElts; ++i)
1544 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001545
Chris Lattner91c08ad2011-02-15 00:14:06 +00001546 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1547 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001548 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001549 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001550}
1551
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001552/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001553Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1554 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001555 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1556 QualType EQT = ExprVT->getElementType();
1557 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001558
John McCall7f416cc2015-09-08 08:05:57 +00001559 Address CastToPointerElement =
1560 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1561 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001562
1563 const llvm::Constant *Elts = LV.getExtVectorElts();
1564 unsigned ix = getAccessedFieldNo(0, Elts);
1565
John McCall7f416cc2015-09-08 08:05:57 +00001566 Address VectorBasePtrPlusIx =
1567 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1568 getContext().getTypeSizeInChars(EQT),
1569 "vector.elt");
1570
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001571 return VectorBasePtrPlusIx;
1572}
1573
Renato Golin230c5eb2014-05-19 18:15:42 +00001574/// @brief Load of global gamed gegisters are always calls to intrinsics.
1575RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001576 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1577 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001578 llvm::MDNode *RegName = cast<llvm::MDNode>(
1579 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001580
1581 // We accept integer and pointer types only
1582 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1583 llvm::Type *Ty = OrigTy;
1584 if (OrigTy->isPointerTy())
1585 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1586 llvm::Type *Types[] = { Ty };
1587
Renato Golin230c5eb2014-05-19 18:15:42 +00001588 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001589 llvm::Value *Call = Builder.CreateCall(
1590 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001591 if (OrigTy->isPointerTy())
1592 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001593 return RValue::get(Call);
1594}
Chris Lattner40ff7012007-08-03 16:18:34 +00001595
Chris Lattner9369a562007-06-29 16:31:29 +00001596
Chris Lattner8394d792007-06-05 20:53:16 +00001597/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1598/// lvalue, where both are guaranteed to the have the same type, and that type
1599/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001600void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001601 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001602 if (!Dst.isSimple()) {
1603 if (Dst.isVectorElt()) {
1604 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001605 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1606 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001607 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001608 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001609 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1610 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001611 return;
1612 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001613
Nate Begemance4d7fc2008-04-18 23:10:10 +00001614 // If this is an update of extended vector elements, insert them as
1615 // appropriate.
1616 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001617 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001618
Renato Golin230c5eb2014-05-19 18:15:42 +00001619 if (Dst.isGlobalReg())
1620 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1621
John McCallc109a252011-11-07 03:59:57 +00001622 assert(Dst.isBitField() && "Unknown LValue type");
1623 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001624 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001625
John McCall31168b02011-06-15 23:02:42 +00001626 // There's special magic for assigning into an ARC-qualified l-value.
1627 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1628 switch (Lifetime) {
1629 case Qualifiers::OCL_None:
1630 llvm_unreachable("present but none");
1631
1632 case Qualifiers::OCL_ExplicitNone:
1633 // nothing special
1634 break;
1635
1636 case Qualifiers::OCL_Strong:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001637 if (isInit) {
1638 Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1639 break;
1640 }
John McCall55e1fbc2011-06-25 02:11:03 +00001641 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001642 return;
1643
1644 case Qualifiers::OCL_Weak:
Akira Hatanaka642f7992016-10-18 19:05:41 +00001645 if (isInit)
1646 // Initialize and then skip the primitive store.
1647 EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1648 else
1649 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001650 return;
1651
1652 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001653 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1654 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001655 // fall into the normal path
1656 break;
1657 }
1658 }
1659
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001660 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001661 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001662 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001663 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001664 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001665 return;
1666 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001667
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001668 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001669 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001670 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001671 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001672 if (Dst.isObjCIvar()) {
1673 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001674 llvm::Type *ResultType = IntPtrTy;
1675 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1676 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001677 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001678 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001679 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1680 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001681 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001682 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001683 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001684 } else if (Dst.isGlobalObjCRef()) {
1685 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1686 Dst.isThreadLocalRef());
1687 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001688 else
1689 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001690 return;
1691 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001692
Chris Lattner6278e6a2007-08-11 00:04:45 +00001693 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001694 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001695}
1696
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001697void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001698 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001699 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001700 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001701 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001702
Daniel Dunbar67aba792010-04-15 03:47:33 +00001703 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001704 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001705
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001706 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001707 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001708 /*IsSigned=*/false);
1709 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001710
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001711 // See if there are other bits in the bitfield's storage we'll need to load
1712 // and mask together with source before storing.
1713 if (Info.StorageSize != Info.Size) {
1714 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001715 llvm::Value *Val =
1716 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001717
1718 // Mask the source value as needed.
1719 if (!hasBooleanRepresentation(Dst.getType()))
1720 SrcVal = Builder.CreateAnd(SrcVal,
1721 llvm::APInt::getLowBitsSet(Info.StorageSize,
1722 Info.Size),
1723 "bf.value");
1724 MaskedVal = SrcVal;
1725 if (Info.Offset)
1726 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1727
1728 // Mask out the original value.
1729 Val = Builder.CreateAnd(Val,
1730 ~llvm::APInt::getBitsSet(Info.StorageSize,
1731 Info.Offset,
1732 Info.Offset + Info.Size),
1733 "bf.clear");
1734
1735 // Or together the unchanged values and the source value.
1736 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1737 } else {
1738 assert(Info.Offset == 0);
1739 }
1740
1741 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001742 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001743
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001744 // Return the new value of the bit-field, if requested.
1745 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001746 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001747
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001748 // Sign extend the value if needed.
1749 if (Info.IsSigned) {
1750 assert(Info.Size <= Info.StorageSize);
1751 unsigned HighBits = Info.StorageSize - Info.Size;
1752 if (HighBits) {
1753 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1754 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1755 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001756 }
1757
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001758 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1759 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001760 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001761 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001762}
1763
Nate Begemance4d7fc2008-04-18 23:10:10 +00001764void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001765 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001766 // This access turns into a read/modify/write of the vector. Load the input
1767 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001768 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1769 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001770 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001771
Chris Lattner4647a212007-08-31 22:49:20 +00001772 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001773
John McCall55e1fbc2011-06-25 02:11:03 +00001774 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001775 unsigned NumSrcElts = VTy->getNumElements();
Craig Topperf2f1a092016-07-08 02:17:35 +00001776 unsigned NumDstElts = Vec->getType()->getVectorNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001777 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001778 // Use shuffle vector is the src and destination are the same number of
1779 // elements and restore the vector mask since it is on the side it will be
1780 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001781 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001782 for (unsigned i = 0; i != NumSrcElts; ++i)
1783 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001784
Chris Lattner91c08ad2011-02-15 00:14:06 +00001785 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001786 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001787 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001788 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001789 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001790 // Extended the source vector to the same length and then shuffle it
1791 // into the destination.
1792 // FIXME: since we're shuffling with undef, can we just use the indices
1793 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001794 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001795 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001796 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001797 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001798 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001799 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001800 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001801 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001802 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001803 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001804 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001805 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001806 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001807
Joey Goulycf4143b2013-11-21 17:09:05 +00001808 // When the vector size is odd and .odd or .hi is used, the last element
1809 // of the Elts constant array will be one past the size of the vector.
1810 // Ignore the last element here, if it is greater than the mask size.
1811 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1812 NumSrcElts--;
1813
Nate Begemanb699c9b2009-01-18 06:42:49 +00001814 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001815 for (unsigned i = 0; i != NumSrcElts; ++i)
1816 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001817 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001818 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001819 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001820 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001821 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001822 }
1823 } else {
1824 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001825 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001826 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001827 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001828 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001829
John McCall7f416cc2015-09-08 08:05:57 +00001830 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1831 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001832}
1833
Renato Golin230c5eb2014-05-19 18:15:42 +00001834/// @brief Store of global named registers are always calls to intrinsics.
1835void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001836 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1837 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001838 llvm::MDNode *RegName = cast<llvm::MDNode>(
1839 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00001840 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00001841
1842 // We accept integer and pointer types only
1843 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1844 llvm::Type *Ty = OrigTy;
1845 if (OrigTy->isPointerTy())
1846 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1847 llvm::Type *Types[] = { Ty };
1848
Renato Golin230c5eb2014-05-19 18:15:42 +00001849 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1850 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00001851 if (OrigTy->isPointerTy())
1852 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00001853 Builder.CreateCall(
1854 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00001855}
1856
Eric Christopherc9e2a682014-05-20 17:10:39 +00001857// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001858// generating write-barries API. It is currently a global, ivar,
1859// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001860static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001861 LValue &LV,
1862 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001863 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001864 return;
Craig Topper99e79272013-07-26 05:59:26 +00001865
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001866 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001867 QualType ExpTy = E->getType();
1868 if (IsMemberAccess && ExpTy->isPointerType()) {
1869 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00001870 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001871 // writer-barrier conservatively.
1872 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1873 if (ExpTy->isRecordType()) {
1874 LV.setObjCIvar(false);
1875 return;
1876 }
1877 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001878 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001879 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001880 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001881 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001882 return;
1883 }
Craig Topper99e79272013-07-26 05:59:26 +00001884
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001885 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1886 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001887 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001888 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00001889 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001890 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001891 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001892 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001893 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001894 }
Craig Topper99e79272013-07-26 05:59:26 +00001895
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001896 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001897 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001898 return;
1899 }
Craig Topper99e79272013-07-26 05:59:26 +00001900
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001901 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001902 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001903 if (LV.isObjCIvar()) {
1904 // If cast is to a structure pointer, follow gcc's behavior and make it
1905 // a non-ivar write-barrier.
1906 QualType ExpTy = E->getType();
1907 if (ExpTy->isPointerType())
1908 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1909 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00001910 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001911 }
1912 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001913 }
Peter Collingbourne91147592011-04-15 00:35:48 +00001914
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001915 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001916 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1917 return;
1918 }
1919
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001920 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001921 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001922 return;
1923 }
Craig Topper99e79272013-07-26 05:59:26 +00001924
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001925 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001926 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001927 return;
1928 }
John McCall31168b02011-06-15 23:02:42 +00001929
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001930 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001931 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00001932 return;
1933 }
1934
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001935 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001936 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00001937 if (LV.isObjCIvar() && !LV.isObjCArray())
1938 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001939 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00001940 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001941 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00001942 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001943 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001944 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001945 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001946 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001947
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001948 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001949 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001950 // We don't know if member is an 'ivar', but this flag is looked at
1951 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001952 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001953 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001954 }
1955}
1956
Chris Lattner3f32d692011-07-12 06:52:18 +00001957static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00001958EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00001959 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001960 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00001961 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00001962 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00001963}
1964
Alexey Bataev97720002014-11-11 04:05:39 +00001965static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00001966 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
1967 llvm::Type *RealVarTy, SourceLocation Loc) {
1968 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
1969 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
1970 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
1971}
1972
1973Address CodeGenFunction::EmitLoadOfReference(Address Addr,
1974 const ReferenceType *RefTy,
1975 AlignmentSource *Source) {
1976 llvm::Value *Ptr = Builder.CreateLoad(Addr);
1977 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
1978 Source, /*forPointee*/ true));
1979
1980}
1981
1982LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
1983 const ReferenceType *RefTy) {
1984 AlignmentSource Source;
1985 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &Source);
1986 return MakeAddrLValue(Addr, RefTy->getPointeeType(), Source);
Alexey Bataev97720002014-11-11 04:05:39 +00001987}
1988
Alexey Bataev31300ed2016-02-04 11:27:03 +00001989Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
1990 const PointerType *PtrTy,
1991 AlignmentSource *Source) {
1992 llvm::Value *Addr = Builder.CreateLoad(Ptr);
1993 return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(), Source,
1994 /*forPointeeType=*/true));
1995}
1996
1997LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
1998 const PointerType *PtrTy) {
1999 AlignmentSource Source;
2000 Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &Source);
2001 return MakeAddrLValue(Addr, PtrTy->getPointeeType(), Source);
2002}
2003
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002004static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2005 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00002006 QualType T = E->getType();
2007
2008 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00002009 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2010 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00002011 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2012
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002013 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002014 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2015 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00002016 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00002017 Address Addr(V, Alignment);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002018 LValue LV;
Alexey Bataev97720002014-11-11 04:05:39 +00002019 // Emit reference to the private copy of the variable if it is an OpenMP
2020 // threadprivate variable.
2021 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00002022 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00002023 E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00002024 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2025 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002026 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002027 LV = CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002028 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002029 setObjCGCLValueClass(CGF.getContext(), E, LV);
2030 return LV;
2031}
2032
John McCallb92ab1a2016-10-26 23:46:34 +00002033static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2034 const FunctionDecl *FD) {
2035 if (FD->hasAttr<WeakRefAttr>()) {
2036 ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2037 return aliasee.getPointer();
2038 }
2039
2040 llvm::Constant *V = CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002041 if (!FD->hasPrototype()) {
2042 if (const FunctionProtoType *Proto =
2043 FD->getType()->getAs<FunctionProtoType>()) {
2044 // Ugly case: for a K&R-style definition, the type of the definition
2045 // isn't the same as the type of a use. Correct for this with a
2046 // bitcast.
2047 QualType NoProtoType =
John McCallb92ab1a2016-10-26 23:46:34 +00002048 CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2049 NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2050 V = llvm::ConstantExpr::getBitCast(V,
2051 CGM.getTypes().ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002052 }
2053 }
John McCallb92ab1a2016-10-26 23:46:34 +00002054 return V;
2055}
2056
2057static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2058 const Expr *E, const FunctionDecl *FD) {
2059 llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
Eli Friedmana0544d62011-12-03 04:14:32 +00002060 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
John McCall7f416cc2015-09-08 08:05:57 +00002061 return CGF.MakeAddrLValue(V, E->getType(), Alignment, AlignmentSource::Decl);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00002062}
2063
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00002064static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2065 llvm::Value *ThisValue) {
2066 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2067 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2068 return CGF.EmitLValueForField(LV, FD);
2069}
2070
Renato Golin230c5eb2014-05-19 18:15:42 +00002071/// Named Registers are named metadata pointing to the register name
2072/// which will be read from/written to as an argument to the intrinsic
2073/// @llvm.read/write_register.
2074/// So far, only the name is being passed down, but other options such as
2075/// register type, allocation type or even optimization options could be
2076/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002077static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002078 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002079 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002080 assert(Asm->getLabel().size() < 64-Name.size() &&
2081 "Register name too big");
2082 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002083 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002084 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002085 if (M->getNumOperands() == 0) {
2086 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2087 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002088 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002089 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2090 }
John McCall7f416cc2015-09-08 08:05:57 +00002091
2092 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2093
2094 llvm::Value *Ptr =
2095 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2096 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002097}
2098
Chris Lattnerd7f58862007-06-02 05:24:33 +00002099LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002100 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002101 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002102
Renato Goline7b3d5d2014-05-27 16:46:27 +00002103 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2104 // Global Named registers access via intrinsics only
2105 if (VD->getStorageClass() == SC_Register &&
2106 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002107 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002108
Renato Goline7b3d5d2014-05-27 16:46:27 +00002109 // A DeclRefExpr for a reference initialized by a constant expression can
2110 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002111 const Expr *Init = VD->getAnyInitializer(VD);
2112 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2113 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002114 VD->checkInitIsICE() &&
2115 // Do not emit if it is private OpenMP variable.
2116 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2117 LocalDeclMap.count(VD))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002118 llvm::Constant *Val =
2119 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2120 assert(Val && "failed to emit reference constant expression");
2121 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002122
2123 // Should we be using the alignment of the constant pointer we emitted?
2124 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2125 /*pointee*/ true);
2126
2127 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
Richard Smith5a1104b2012-10-20 01:38:33 +00002128 }
David Majnemer602cfe72015-01-01 09:49:44 +00002129
2130 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002131 if (E->refersToEnclosingVariableOrCapture()) {
David Majnemer602cfe72015-01-01 09:49:44 +00002132 if (auto *FD = LambdaCaptureFields.lookup(VD))
2133 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2134 else if (CapturedStmtInfo) {
Alexey Bataevac5eabb2016-11-07 11:16:04 +00002135 auto I = LocalDeclMap.find(VD);
2136 if (I != LocalDeclMap.end()) {
2137 if (auto RefTy = VD->getType()->getAs<ReferenceType>())
2138 return EmitLoadOfReferenceLValue(I->second, RefTy);
2139 return MakeAddrLValue(I->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002140 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002141 LValue CapLVal =
2142 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2143 CapturedStmtInfo->getContextValue());
2144 return MakeAddrLValue(
2145 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2146 CapLVal.getType(), AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002147 }
John McCall7f416cc2015-09-08 08:05:57 +00002148
David Majnemer602cfe72015-01-01 09:49:44 +00002149 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002150 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2151 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002152 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002153 }
2154
Eli Friedman5720e342012-01-21 04:52:58 +00002155 // FIXME: We should be able to assert this for FunctionDecls as well!
2156 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2157 // those with a valid source location.
2158 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2159 !E->getLocation().isValid()) &&
2160 "Should not use decl without marking it used!");
2161
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002162 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002163 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002164 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2165 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002166 }
2167
Renato Goline7b3d5d2014-05-27 16:46:27 +00002168 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002169 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002170 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002171 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002172
John McCall7f416cc2015-09-08 08:05:57 +00002173 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002174
John McCall7f416cc2015-09-08 08:05:57 +00002175 // The variable should generally be present in the local decl map.
2176 auto iter = LocalDeclMap.find(VD);
2177 if (iter != LocalDeclMap.end()) {
2178 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002179
John McCall7f416cc2015-09-08 08:05:57 +00002180 // Otherwise, it might be static local we haven't emitted yet for
2181 // some reason; most likely, because it's in an outer function.
2182 } else if (VD->isStaticLocal()) {
2183 addr = Address(CGM.getOrCreateStaticVarDecl(
2184 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2185 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002186
John McCall7f416cc2015-09-08 08:05:57 +00002187 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002188 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002189 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2190 }
2191
2192
2193 // Check for OpenMP threadprivate variables.
2194 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2195 return EmitThreadPrivateVarDeclLValue(
2196 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2197 E->getExprLoc());
2198 }
2199
2200 // Drill into block byref variables.
2201 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2202 if (isBlockByref) {
2203 addr = emitBlockByrefAddress(addr, VD);
2204 }
2205
2206 // Drill into reference types.
2207 LValue LV;
2208 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2209 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2210 } else {
2211 LV = MakeAddrLValue(addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002212 }
Chris Lattner3f32d692011-07-12 06:52:18 +00002213
John McCallcdda29c2013-03-13 03:10:54 +00002214 bool isLocalStorage = VD->hasLocalStorage();
2215
2216 bool NonGCable = isLocalStorage &&
2217 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002218 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002219 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002220 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002221 LV.setNonGC(true);
2222 }
John McCallcdda29c2013-03-13 03:10:54 +00002223
2224 bool isImpreciseLifetime =
2225 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2226 if (isImpreciseLifetime)
2227 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002228 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002229 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002230 }
John McCallf3a88602011-02-03 08:15:49 +00002231
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002232 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002233 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002234
Richard Smithda383632016-08-15 01:33:41 +00002235 // FIXME: While we're emitting a binding from an enclosing scope, all other
2236 // DeclRefExprs we see should be implicitly treated as if they also refer to
2237 // an enclosing scope.
2238 if (const auto *BD = dyn_cast<BindingDecl>(ND))
2239 return EmitLValue(BD->getBinding());
2240
David Blaikie83d382b2011-09-23 05:06:16 +00002241 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002242}
Chris Lattnere47e4402007-06-01 18:02:12 +00002243
Chris Lattner8394d792007-06-05 20:53:16 +00002244LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2245 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002246 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002247 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002248
Chris Lattner0f398c42008-07-26 22:37:01 +00002249 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002250 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002251 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002252 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002253 QualType T = E->getSubExpr()->getType()->getPointeeType();
2254 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002255
John McCall7f416cc2015-09-08 08:05:57 +00002256 AlignmentSource AlignSource;
2257 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &AlignSource);
2258 LValue LV = MakeAddrLValue(Addr, T, AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002259 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002260
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002261 // We should not generate __weak write barrier on indirect reference
2262 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2263 // But, we continue to generate __strong write barrier on indirect write
2264 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002265 if (getLangOpts().ObjC1 &&
2266 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002267 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002268 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002269 return LV;
2270 }
John McCalle3027922010-08-25 11:45:40 +00002271 case UO_Real:
2272 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002273 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002274 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002275
Richard Smith0b6b8e42012-02-18 20:53:32 +00002276 // __real is valid on scalars. This is a faster way of testing that.
2277 // __imag can only produce an rvalue on scalars.
2278 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002279 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002280 assert(E->getSubExpr()->getType()->isArithmeticType());
2281 return LV;
2282 }
2283
Alexey Bataev611b0a12016-11-07 18:15:02 +00002284 QualType T = ExprTy->castAs<ComplexType>()->getElementType();
John McCalla2342eb2010-12-05 02:00:02 +00002285
John McCall7f416cc2015-09-08 08:05:57 +00002286 Address Component =
2287 (E->getOpcode() == UO_Real
2288 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2289 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
Alexey Bataev611b0a12016-11-07 18:15:02 +00002290 LValue ElemLV = MakeAddrLValue(Component, T, LV.getAlignmentSource());
2291 ElemLV.getQuals().addQualifiers(LV.getQuals());
2292 return ElemLV;
Chris Lattner595db862007-10-30 22:53:42 +00002293 }
John McCalle3027922010-08-25 11:45:40 +00002294 case UO_PreInc:
2295 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002296 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002297 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002298
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002299 if (E->getType()->isAnyComplexType())
2300 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2301 else
2302 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2303 return LV;
2304 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002305 }
Chris Lattner8394d792007-06-05 20:53:16 +00002306}
2307
Chris Lattner4347e3692007-06-06 04:54:52 +00002308LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002309 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
John McCall7f416cc2015-09-08 08:05:57 +00002310 E->getType(), AlignmentSource::Decl);
Chris Lattner4347e3692007-06-06 04:54:52 +00002311}
2312
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002313LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002314 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
John McCall7f416cc2015-09-08 08:05:57 +00002315 E->getType(), AlignmentSource::Decl);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002316}
2317
Mike Stump4a3999f2009-09-09 13:00:44 +00002318LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002319 auto SL = E->getFunctionName();
2320 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2321 StringRef FnName = CurFn->getName();
2322 if (FnName.startswith("\01"))
2323 FnName = FnName.substr(1);
2324 StringRef NameItems[] = {
2325 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2326 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Mehdi Aminidc9bf8f2016-11-16 07:07:28 +00002327 if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2328 std::string Name = SL->getString();
2329 if (!Name.empty()) {
2330 unsigned Discriminator =
2331 CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2332 if (Discriminator)
2333 Name += "_" + Twine(Discriminator + 1).str();
2334 auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
2335 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2336 } else {
2337 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2338 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2339 }
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002340 }
Alexey Bataevec474782014-10-09 08:45:04 +00002341 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
John McCall7f416cc2015-09-08 08:05:57 +00002342 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002343}
2344
Richard Smithe30752c2012-10-09 19:52:38 +00002345/// Emit a type description suitable for use by a runtime sanitizer library. The
2346/// format of a type descriptor is
2347///
2348/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002349/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002350/// \endcode
2351///
Richard Smith683398a2012-10-09 23:55:19 +00002352/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2353/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002354llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002355 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002356 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002357 return C;
2358
Richard Smithe30752c2012-10-09 19:52:38 +00002359 uint16_t TypeKind = -1;
2360 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002361
Richard Smithe30752c2012-10-09 19:52:38 +00002362 if (T->isIntegerType()) {
2363 TypeKind = 0;
2364 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002365 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002366 } else if (T->isFloatingType()) {
2367 TypeKind = 1;
2368 TypeInfo = getContext().getTypeSize(T);
2369 }
2370
2371 // Format the type name as if for a diagnostic, including quotes and
2372 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002373 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002374 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2375 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002376 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002377 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002378
2379 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002380 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2381 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002382 };
2383 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2384
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002385 auto *GV = new llvm::GlobalVariable(
2386 CGM.getModule(), Descriptor->getType(),
2387 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002388 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002389 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002390
2391 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002392 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002393
Richard Smithe30752c2012-10-09 19:52:38 +00002394 return GV;
2395}
2396
2397llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2398 llvm::Type *TargetTy = IntPtrTy;
2399
Richard Smith48366f72013-03-22 00:47:07 +00002400 // Floating-point types which fit into intptr_t are bitcast to integers
2401 // and then passed directly (after zero-extension, if necessary).
2402 if (V->getType()->isFloatingPointTy()) {
2403 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2404 if (Bits <= TargetTy->getIntegerBitWidth())
2405 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2406 Bits));
2407 }
2408
Richard Smithe30752c2012-10-09 19:52:38 +00002409 // Integers which fit in intptr_t are zero-extended and passed directly.
2410 if (V->getType()->isIntegerTy() &&
2411 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2412 return Builder.CreateZExt(V, TargetTy);
2413
2414 // Pointers are passed directly, everything else is passed by address.
2415 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002416 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002417 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002418 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002419 }
2420 return Builder.CreatePtrToInt(V, TargetTy);
2421}
2422
2423/// \brief Emit a representation of a SourceLocation for passing to a handler
2424/// in a sanitizer runtime library. The format for this data is:
2425/// \code
2426/// struct SourceLocation {
2427/// const char *Filename;
2428/// int32_t Line, Column;
2429/// };
2430/// \endcode
2431/// For an invalid SourceLocation, the Filename pointer is null.
2432llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002433 llvm::Constant *Filename;
2434 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002435
Alexey Samsonov6c124142014-07-18 17:50:06 +00002436 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2437 if (PLoc.isValid()) {
Filipe Cabecinhasab731f72016-05-12 16:51:36 +00002438 StringRef FilenameString = PLoc.getFilename();
2439
2440 int PathComponentsToStrip =
2441 CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2442 if (PathComponentsToStrip < 0) {
2443 assert(PathComponentsToStrip != INT_MIN);
2444 int PathComponentsToKeep = -PathComponentsToStrip;
2445 auto I = llvm::sys::path::rbegin(FilenameString);
2446 auto E = llvm::sys::path::rend(FilenameString);
2447 while (I != E && --PathComponentsToKeep)
2448 ++I;
2449
2450 FilenameString = FilenameString.substr(I - E);
2451 } else if (PathComponentsToStrip > 0) {
2452 auto I = llvm::sys::path::begin(FilenameString);
2453 auto E = llvm::sys::path::end(FilenameString);
2454 while (I != E && PathComponentsToStrip--)
2455 ++I;
2456
2457 if (I != E)
2458 FilenameString =
2459 FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2460 else
2461 FilenameString = llvm::sys::path::filename(FilenameString);
2462 }
2463
2464 auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002465 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2466 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2467 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002468 Line = PLoc.getLine();
2469 Column = PLoc.getColumn();
2470 } else {
2471 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2472 Line = Column = 0;
2473 }
2474
2475 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2476 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002477
2478 return llvm::ConstantStruct::getAnon(Data);
2479}
2480
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002481namespace {
2482/// \brief Specify under what conditions this check can be recovered
2483enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002484 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002485 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002486 /// Check supports recovering, runtime has both fatal (noreturn) and
2487 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002488 Recoverable,
2489 /// Runtime conditionally aborts, always need to support recovery.
2490 AlwaysRecoverable
2491};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002492}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002493
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002494static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2495 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002496 switch (Kind) {
2497 case SanitizerKind::Vptr:
2498 return CheckRecoverableKind::AlwaysRecoverable;
2499 case SanitizerKind::Return:
2500 case SanitizerKind::Unreachable:
2501 return CheckRecoverableKind::Unrecoverable;
2502 default:
2503 return CheckRecoverableKind::Recoverable;
2504 }
2505}
2506
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002507namespace {
2508struct SanitizerHandlerInfo {
2509 char const *const Name;
2510 unsigned Version;
2511};
Saleem Abdulrasoolca6e2b42016-12-13 03:27:35 +00002512}
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002513
2514const SanitizerHandlerInfo SanitizerHandlers[] = {
2515#define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2516 LIST_SANITIZER_CHECKS
2517#undef SANITIZER_CHECK
2518};
2519
Alexey Samsonov88459522015-01-12 22:39:12 +00002520static void emitCheckHandlerCall(CodeGenFunction &CGF,
2521 llvm::FunctionType *FnType,
2522 ArrayRef<llvm::Value *> FnArgs,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002523 SanitizerHandler CheckHandler,
Alexey Samsonov88459522015-01-12 22:39:12 +00002524 CheckRecoverableKind RecoverKind, bool IsFatal,
2525 llvm::BasicBlock *ContBB) {
2526 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2527 bool NeedsAbortSuffix =
2528 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002529 const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2530 const StringRef CheckName = CheckInfo.Name;
2531 std::string FnName =
2532 ("__ubsan_handle_" + CheckName +
Vedant Kumar4881bdf2016-12-12 18:47:33 +00002533 (CheckInfo.Version ? "_v" + llvm::utostr(CheckInfo.Version) : "") +
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002534 (NeedsAbortSuffix ? "_abort" : ""))
2535 .str();
Alexey Samsonov88459522015-01-12 22:39:12 +00002536 bool MayReturn =
2537 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2538
2539 llvm::AttrBuilder B;
2540 if (!MayReturn) {
2541 B.addAttribute(llvm::Attribute::NoReturn)
2542 .addAttribute(llvm::Attribute::NoUnwind);
2543 }
2544 B.addAttribute(llvm::Attribute::UWTable);
2545
2546 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2547 FnType, FnName,
2548 llvm::AttributeSet::get(CGF.getLLVMContext(),
Saleem Abdulrasool05b8fde2016-12-15 16:30:20 +00002549 llvm::AttributeSet::FunctionIndex, B),
2550 /*Local=*/true);
Alexey Samsonov88459522015-01-12 22:39:12 +00002551 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2552 if (!MayReturn) {
2553 HandlerCall->setDoesNotReturn();
2554 CGF.Builder.CreateUnreachable();
2555 } else {
2556 CGF.Builder.CreateBr(ContBB);
2557 }
2558}
2559
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002560void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002561 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002562 SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002563 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002564 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002565 assert(Checked.size() > 0);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002566 assert(CheckHandler >= 0 &&
2567 CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers));
2568 const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
Alexey Samsonov88459522015-01-12 22:39:12 +00002569
2570 llvm::Value *FatalCond = nullptr;
2571 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002572 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002573 for (int i = 0, n = Checked.size(); i < n; ++i) {
2574 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002575 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002576 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002577 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2578 ? TrapCond
2579 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2580 ? RecoverableCond
2581 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002582 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2583 }
2584
Peter Collingbourne9881b782015-06-18 23:59:22 +00002585 if (TrapCond)
2586 EmitTrapCheck(TrapCond);
2587 if (!FatalCond && !RecoverableCond)
2588 return;
2589
Alexey Samsonov88459522015-01-12 22:39:12 +00002590 llvm::Value *JointCond;
2591 if (FatalCond && RecoverableCond)
2592 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2593 else
2594 JointCond = FatalCond ? FatalCond : RecoverableCond;
2595 assert(JointCond);
2596
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002597 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002598 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002599#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002600 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002601 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002602 "All recoverable kinds in a single check must be same!");
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002603 assert(SanOpts.has(Checked[i].second));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002604 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002605#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002606
Richard Smith4d1458e2012-09-08 02:08:36 +00002607 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002608 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2609 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002610 // Give hint that we very much don't expect to execute the handler
2611 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2612 llvm::MDBuilder MDHelper(getLLVMContext());
2613 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2614 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002615 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002616
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002617 // Handler functions take an i8* pointing to the (handler-specific) static
2618 // information block, followed by a sequence of intptr_t arguments
2619 // representing operand values.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002620 SmallVector<llvm::Value *, 4> Args;
2621 SmallVector<llvm::Type *, 4> ArgTypes;
Richard Smithe30752c2012-10-09 19:52:38 +00002622 Args.reserve(DynamicArgs.size() + 1);
2623 ArgTypes.reserve(DynamicArgs.size() + 1);
2624
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002625 // Emit handler arguments and create handler function type.
2626 if (!StaticArgs.empty()) {
2627 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2628 auto *InfoPtr =
2629 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2630 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002631 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002632 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2633 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2634 ArgTypes.push_back(Int8PtrTy);
2635 }
2636
Richard Smithe30752c2012-10-09 19:52:38 +00002637 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2638 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2639 ArgTypes.push_back(IntPtrTy);
2640 }
2641
2642 llvm::FunctionType *FnType =
2643 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002644
Alexey Samsonov88459522015-01-12 22:39:12 +00002645 if (!FatalCond || !RecoverableCond) {
2646 // Simple case: we need to generate a single handler call, either
2647 // fatal, or non-fatal.
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002648 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
Alexey Samsonov88459522015-01-12 22:39:12 +00002649 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002650 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002651 // Emit two handler calls: first one for set of unrecoverable checks,
2652 // another one for recoverable.
2653 llvm::BasicBlock *NonFatalHandlerBB =
2654 createBasicBlock("non_fatal." + CheckName);
2655 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2656 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2657 EmitBlock(FatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002658 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
Alexey Samsonov88459522015-01-12 22:39:12 +00002659 NonFatalHandlerBB);
2660 EmitBlock(NonFatalHandlerBB);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002661 emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
Alexey Samsonov88459522015-01-12 22:39:12 +00002662 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002663 }
Richard Smithe30752c2012-10-09 19:52:38 +00002664
Richard Smith4d1458e2012-09-08 02:08:36 +00002665 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002666}
2667
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002668void CodeGenFunction::EmitCfiSlowPathCheck(
2669 SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2670 llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002671 llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2672
2673 llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2674 llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2675
2676 llvm::MDBuilder MDHelper(getLLVMContext());
2677 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2678 BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2679
2680 EmitBlock(CheckBB);
2681
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002682 bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2683
2684 llvm::CallInst *CheckCall;
2685 if (WithDiag) {
2686 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2687 auto *InfoPtr =
2688 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2689 llvm::GlobalVariable::PrivateLinkage, Info);
Peter Collingbournebcf909d2016-06-14 21:02:05 +00002690 InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002691 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2692
2693 llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2694 "__cfi_slowpath_diag",
2695 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2696 false));
2697 CheckCall = Builder.CreateCall(
2698 SlowPathDiagFn,
2699 {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2700 } else {
2701 llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2702 "__cfi_slowpath",
2703 llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2704 CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2705 }
2706
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00002707 CheckCall->setDoesNotThrow();
2708
2709 EmitBlock(Cont);
2710}
2711
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002712// This function is basically a switch over the CFI failure kind, which is
2713// extracted from CFICheckFailData (1st function argument). Each case is either
2714// llvm.trap or a call to one of the two runtime handlers, based on
2715// -fsanitize-trap and -fsanitize-recover settings. Default case (invalid
2716// failure kind) traps, but this should really never happen. CFICheckFailData
2717// can be nullptr if the calling module has -fsanitize-trap behavior for this
2718// check kind; in this case __cfi_check_fail traps as well.
2719void CodeGenFunction::EmitCfiCheckFail() {
2720 SanitizerScope SanScope(this);
2721 FunctionArgList Args;
2722 ImplicitParamDecl ArgData(getContext(), nullptr, SourceLocation(), nullptr,
2723 getContext().VoidPtrTy);
2724 ImplicitParamDecl ArgAddr(getContext(), nullptr, SourceLocation(), nullptr,
2725 getContext().VoidPtrTy);
2726 Args.push_back(&ArgData);
2727 Args.push_back(&ArgAddr);
2728
John McCallc56a8b32016-03-11 04:30:31 +00002729 const CGFunctionInfo &FI =
2730 CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002731
2732 llvm::Function *F = llvm::Function::Create(
2733 llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2734 llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2735 F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2736
2737 StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2738 SourceLocation());
2739
2740 llvm::Value *Data =
2741 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2742 CGM.getContext().VoidPtrTy, ArgData.getLocation());
2743 llvm::Value *Addr =
2744 EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2745 CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2746
2747 // Data == nullptr means the calling module has trap behaviour for this check.
2748 llvm::Value *DataIsNotNullPtr =
2749 Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2750 EmitTrapCheck(DataIsNotNullPtr);
2751
2752 llvm::StructType *SourceLocationTy =
2753 llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty, nullptr);
2754 llvm::StructType *CfiCheckFailDataTy =
2755 llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy, nullptr);
2756
2757 llvm::Value *V = Builder.CreateConstGEP2_32(
2758 CfiCheckFailDataTy,
2759 Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2760 0);
2761 Address CheckKindAddr(V, getIntAlign());
2762 llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2763
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002764 llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2765 CGM.getLLVMContext(),
2766 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2767 llvm::Value *ValidVtable = Builder.CreateZExt(
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00002768 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00002769 {Addr, AllVtables}),
2770 IntPtrTy);
2771
Evgeniy Stepanov4d3b0872016-01-25 23:45:37 +00002772 const std::pair<int, SanitizerMask> CheckKinds[] = {
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002773 {CFITCK_VCall, SanitizerKind::CFIVCall},
2774 {CFITCK_NVCall, SanitizerKind::CFINVCall},
2775 {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
2776 {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
2777 {CFITCK_ICall, SanitizerKind::CFIICall}};
2778
2779 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
2780 for (auto CheckKindMaskPair : CheckKinds) {
2781 int Kind = CheckKindMaskPair.first;
2782 SanitizerMask Mask = CheckKindMaskPair.second;
2783 llvm::Value *Cond =
2784 Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002785 if (CGM.getLangOpts().Sanitize.has(Mask))
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00002786 EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
Evgeniy Stepanov02279ed2016-03-15 20:19:29 +00002787 {Data, Addr, ValidVtable});
2788 else
2789 EmitTrapCheck(Cond);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00002790 }
2791
2792 FinishFunction();
2793 // The only reference to this function will be created during LTO link.
2794 // Make sure it survives until then.
2795 CGM.addUsedGlobal(F);
2796}
2797
Chad Rosierae229d52013-01-29 23:31:22 +00002798void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00002799 llvm::BasicBlock *Cont = createBasicBlock("cont");
2800
2801 // If we're optimizing, collapse all calls to trap down to just one per
2802 // function to save on code size.
2803 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2804 TrapBB = createBasicBlock("trap");
2805 Builder.CreateCondBr(Checked, Cont, TrapBB);
2806 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002807 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00002808 TrapCall->setDoesNotReturn();
2809 TrapCall->setDoesNotThrow();
2810 Builder.CreateUnreachable();
2811 } else {
2812 Builder.CreateCondBr(Checked, Cont, TrapBB);
2813 }
2814
2815 EmitBlock(Cont);
2816}
2817
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002818llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00002819 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002820
Amaury Sechet21f51b32016-09-09 04:42:49 +00002821 if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
2822 auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
2823 CGM.getCodeGenOpts().TrapFuncName);
2824 TrapCall->addAttribute(llvm::AttributeSet::FunctionIndex, A);
2825 }
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002826
2827 return TrapCall;
2828}
2829
John McCall7f416cc2015-09-08 08:05:57 +00002830Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
2831 AlignmentSource *AlignSource) {
2832 assert(E->getType()->isArrayType() &&
2833 "Array to pointer decay must have array source type!");
2834
2835 // Expressions of array type can't be bitfields or vector elements.
2836 LValue LV = EmitLValue(E);
2837 Address Addr = LV.getAddress();
2838 if (AlignSource) *AlignSource = LV.getAlignmentSource();
2839
2840 // If the array type was an incomplete type, we need to make sure
2841 // the decay ends up being the right type.
2842 llvm::Type *NewTy = ConvertType(E->getType());
2843 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2844
2845 // Note that VLA pointers are always decayed, so we don't need to do
2846 // anything here.
2847 if (!E->getType()->isVariableArrayType()) {
2848 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2849 "Expected pointer to array");
2850 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2851 }
2852
2853 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2854 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2855}
2856
Chris Lattner6c5abe82010-06-26 23:03:20 +00002857/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2858/// array to pointer, return the array subexpression.
2859static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2860 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002861 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00002862 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00002863 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002864
Chris Lattner6c5abe82010-06-26 23:03:20 +00002865 // If this is a decay from variable width array, bail out.
2866 const Expr *SubExpr = CE->getSubExpr();
2867 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00002868 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002869
Chris Lattner6c5abe82010-06-26 23:03:20 +00002870 return SubExpr;
2871}
2872
John McCall7f416cc2015-09-08 08:05:57 +00002873static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
2874 llvm::Value *ptr,
2875 ArrayRef<llvm::Value*> indices,
2876 bool inbounds,
2877 const llvm::Twine &name = "arrayidx") {
2878 if (inbounds) {
2879 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name);
2880 } else {
2881 return CGF.Builder.CreateGEP(ptr, indices, name);
2882 }
2883}
2884
2885static CharUnits getArrayElementAlign(CharUnits arrayAlign,
2886 llvm::Value *idx,
2887 CharUnits eltSize) {
2888 // If we have a constant index, we can use the exact offset of the
2889 // element we're accessing.
2890 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
2891 CharUnits offset = constantIdx->getZExtValue() * eltSize;
2892 return arrayAlign.alignmentAtOffset(offset);
2893
2894 // Otherwise, use the worst-case alignment for any element.
2895 } else {
2896 return arrayAlign.alignmentOfArrayElement(eltSize);
2897 }
2898}
2899
2900static QualType getFixedSizeElementType(const ASTContext &ctx,
2901 const VariableArrayType *vla) {
2902 QualType eltType;
2903 do {
2904 eltType = vla->getElementType();
2905 } while ((vla = ctx.getAsVariableArrayType(eltType)));
2906 return eltType;
2907}
2908
2909static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
2910 ArrayRef<llvm::Value*> indices,
2911 QualType eltType, bool inbounds,
2912 const llvm::Twine &name = "arrayidx") {
2913 // All the indices except that last must be zero.
2914#ifndef NDEBUG
2915 for (auto idx : indices.drop_back())
2916 assert(isa<llvm::ConstantInt>(idx) &&
2917 cast<llvm::ConstantInt>(idx)->isZero());
2918#endif
2919
2920 // Determine the element size of the statically-sized base. This is
2921 // the thing that the indices are expressed in terms of.
2922 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
2923 eltType = getFixedSizeElementType(CGF.getContext(), vla);
2924 }
2925
2926 // We can use that to compute the best alignment of the element.
2927 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
2928 CharUnits eltAlign =
2929 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
2930
2931 llvm::Value *eltPtr =
2932 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name);
2933 return Address(eltPtr, eltAlign);
2934}
2935
Richard Smith539e4a72013-02-23 02:53:19 +00002936LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2937 bool Accessed) {
Richard Smith9e67b992016-09-26 23:49:47 +00002938 // The index must always be an integer, which is not an aggregate. Emit it
2939 // in lexical order (this complexity is, sadly, required by C++17).
2940 llvm::Value *IdxPre =
2941 (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
Richard Smith40885712016-09-27 00:53:24 +00002942 auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
Richard Smith9e67b992016-09-26 23:49:47 +00002943 auto *Idx = IdxPre;
2944 if (E->getLHS() != E->getIdx()) {
2945 assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
2946 Idx = EmitScalarExpr(E->getIdx());
2947 }
Eli Friedman07bbeca2009-06-06 19:09:26 +00002948
Richard Smith9e67b992016-09-26 23:49:47 +00002949 QualType IdxTy = E->getIdx()->getType();
2950 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
2951
2952 if (SanOpts.has(SanitizerKind::ArrayBounds))
2953 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
2954
2955 // Extend or truncate the index type to 32 or 64-bits.
2956 if (Promote && Idx->getType() != IntPtrTy)
2957 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
2958
2959 return Idx;
2960 };
2961 IdxPre = nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +00002962
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002963 // If the base is a vector type, then we are forming a vector element lvalue
2964 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002965 if (E->getBase()->getType()->isVectorType() &&
2966 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002967 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00002968 LValue LHS = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00002969 auto *Idx = EmitIdxAfterBase(/*Promote*/false);
Ted Kremenekc81614d2007-08-20 16:18:38 +00002970 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Eli Friedman327944b2008-06-13 23:01:12 +00002971 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
John McCall7f416cc2015-09-08 08:05:57 +00002972 E->getBase()->getType(),
2973 LHS.getAlignmentSource());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002974 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002975
John McCall7f416cc2015-09-08 08:05:57 +00002976 // All the other cases basically behave like simple offsetting.
2977
John McCall7f416cc2015-09-08 08:05:57 +00002978 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002979 if (isa<ExtVectorElementExpr>(E->getBase())) {
2980 LValue LV = EmitLValue(E->getBase());
Richard Smith9e67b992016-09-26 23:49:47 +00002981 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00002982 Address Addr = EmitExtVectorElementLValue(LV);
2983
2984 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
2985 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true);
2986 return MakeAddrLValue(Addr, EltType, LV.getAlignmentSource());
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002987 }
John McCall7f416cc2015-09-08 08:05:57 +00002988
2989 AlignmentSource AlignSource;
2990 Address Addr = Address::invalid();
2991 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002992 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00002993 // The base must be a pointer, which is not an aggregate. Emit
2994 // it. It needs to be emitted first in case it's what captures
2995 // the VLA bounds.
John McCall7f416cc2015-09-08 08:05:57 +00002996 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Richard Smith9e67b992016-09-26 23:49:47 +00002997 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Mike Stump4a3999f2009-09-09 13:00:44 +00002998
John McCall23c29fe2011-06-24 21:55:10 +00002999 // The element count here is the total number of non-VLA elements.
3000 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00003001
John McCall77527a82011-06-25 01:32:37 +00003002 // Effectively, the multiply by the VLA size is part of the GEP.
3003 // GEP indexes are signed, and scaling an index isn't permitted to
3004 // signed-overflow, so we use the same semantics for our explicit
3005 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003006 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00003007 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003008 } else {
3009 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00003010 }
John McCall7f416cc2015-09-08 08:05:57 +00003011
3012 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3013 !getLangOpts().isSignedOverflowDefined());
3014
Chris Lattner6c5abe82010-06-26 23:03:20 +00003015 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3016 // Indexing over an interface, as in "NSString *P; P[4];"
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003017
John McCall7f416cc2015-09-08 08:05:57 +00003018 // Emit the base pointer.
3019 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Richard Smith9e67b992016-09-26 23:49:47 +00003020 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3021
3022 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3023 llvm::Value *InterfaceSizeVal =
3024 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3025
3026 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
John McCall7f416cc2015-09-08 08:05:57 +00003027
3028 // We don't necessarily build correct LLVM struct types for ObjC
3029 // interfaces, so we can't rely on GEP to do this scaling
3030 // correctly, so we need to cast to i8*. FIXME: is this actually
3031 // true? A lot of other things in the fragile ABI would break...
3032 llvm::Type *OrigBaseTy = Addr.getType();
3033 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3034
3035 // Do the GEP.
3036 CharUnits EltAlign =
3037 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
3038 llvm::Value *EltPtr =
3039 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false);
3040 Addr = Address(EltPtr, EltAlign);
3041
3042 // Cast back.
3043 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00003044 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3045 // If this is A[i] where A is an array, the frontend will have decayed the
3046 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3047 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3048 // "gep x, i" here. Emit one "gep A, 0, i".
3049 assert(Array->getType()->isArrayType() &&
3050 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00003051 LValue ArrayLV;
3052 // For simple multidimensional array indexing, set the 'accessed' flag for
3053 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003054 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00003055 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3056 else
3057 ArrayLV = EmitLValue(Array);
Richard Smith9e67b992016-09-26 23:49:47 +00003058 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
Craig Topper99e79272013-07-26 05:59:26 +00003059
Daniel Dunbar82634272011-04-01 00:49:43 +00003060 // Propagate the alignment from the array itself to the result.
John McCall7f416cc2015-09-08 08:05:57 +00003061 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
3062 {CGM.getSize(CharUnits::Zero()), Idx},
3063 E->getType(),
3064 !getLangOpts().isSignedOverflowDefined());
3065 AlignSource = ArrayLV.getAlignmentSource();
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003066 } else {
John McCall7f416cc2015-09-08 08:05:57 +00003067 // The base must be a pointer; emit it with an estimate of its alignment.
3068 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Richard Smith9e67b992016-09-26 23:49:47 +00003069 auto *Idx = EmitIdxAfterBase(/*Promote*/true);
John McCall7f416cc2015-09-08 08:05:57 +00003070 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3071 !getLangOpts().isSignedOverflowDefined());
Anders Carlsson3d312f82008-12-21 00:11:23 +00003072 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003073
John McCall7f416cc2015-09-08 08:05:57 +00003074 LValue LV = MakeAddrLValue(Addr, E->getType(), AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00003075
John McCall7f416cc2015-09-08 08:05:57 +00003076 // TODO: Preserve/extend path TBAA metadata?
John McCall8ccfcb52009-09-24 19:53:00 +00003077
Richard Smith9c6890a2012-11-01 22:30:59 +00003078 if (getLangOpts().ObjC1 &&
3079 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00003080 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00003081 setObjCGCLValueClass(getContext(), E, LV);
3082 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00003083 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00003084}
3085
Alexey Bataev31300ed2016-02-04 11:27:03 +00003086static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
3087 AlignmentSource &AlignSource,
3088 QualType BaseTy, QualType ElTy,
3089 bool IsLowerBound) {
3090 LValue BaseLVal;
3091 if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3092 BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3093 if (BaseTy->isArrayType()) {
3094 Address Addr = BaseLVal.getAddress();
3095 AlignSource = BaseLVal.getAlignmentSource();
3096
3097 // If the array type was an incomplete type, we need to make sure
3098 // the decay ends up being the right type.
3099 llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3100 Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3101
3102 // Note that VLA pointers are always decayed, so we don't need to do
3103 // anything here.
3104 if (!BaseTy->isVariableArrayType()) {
3105 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3106 "Expected pointer to array");
3107 Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3108 "arraydecay");
3109 }
3110
3111 return CGF.Builder.CreateElementBitCast(Addr,
3112 CGF.ConvertTypeForMem(ElTy));
3113 }
3114 CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &AlignSource);
3115 return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3116 }
3117 return CGF.EmitPointerWithAlignment(Base, &AlignSource);
3118}
3119
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003120LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3121 bool IsLowerBound) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003122 QualType BaseTy;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003123 if (auto *ASE =
3124 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
Alexey Bataev31300ed2016-02-04 11:27:03 +00003125 BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003126 else
Alexey Bataev31300ed2016-02-04 11:27:03 +00003127 BaseTy = E->getBase()->getType();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003128 QualType ResultExprTy;
3129 if (auto *AT = getContext().getAsArrayType(BaseTy))
3130 ResultExprTy = AT->getElementType();
3131 else
3132 ResultExprTy = BaseTy->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +00003133 llvm::Value *Idx = nullptr;
Benjamin Kramer5ff67472016-04-11 08:26:13 +00003134 if (IsLowerBound || E->getColonLoc().isInvalid()) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003135 // Requesting lower bound or upper bound, but without provided length and
3136 // without ':' symbol for the default length -> length = 1.
3137 // Idx = LowerBound ?: 0;
3138 if (auto *LowerBound = E->getLowerBound()) {
3139 Idx = Builder.CreateIntCast(
3140 EmitScalarExpr(LowerBound), IntPtrTy,
3141 LowerBound->getType()->hasSignedIntegerRepresentation());
3142 } else
3143 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3144 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003145 // Try to emit length or lower bound as constant. If this is possible, 1
3146 // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3147 // IR (LB + Len) - 1.
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003148 auto &C = CGM.getContext();
3149 auto *Length = E->getLength();
3150 llvm::APSInt ConstLength;
3151 if (Length) {
3152 // Idx = LowerBound + Length - 1;
3153 if (Length->isIntegerConstantExpr(ConstLength, C)) {
3154 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3155 Length = nullptr;
3156 }
3157 auto *LowerBound = E->getLowerBound();
3158 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3159 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3160 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3161 LowerBound = nullptr;
3162 }
3163 if (!Length)
3164 --ConstLength;
3165 else if (!LowerBound)
3166 --ConstLowerBound;
3167
3168 if (Length || LowerBound) {
3169 auto *LowerBoundVal =
3170 LowerBound
3171 ? Builder.CreateIntCast(
3172 EmitScalarExpr(LowerBound), IntPtrTy,
3173 LowerBound->getType()->hasSignedIntegerRepresentation())
3174 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3175 auto *LengthVal =
3176 Length
3177 ? Builder.CreateIntCast(
3178 EmitScalarExpr(Length), IntPtrTy,
3179 Length->getType()->hasSignedIntegerRepresentation())
3180 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3181 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3182 /*HasNUW=*/false,
3183 !getLangOpts().isSignedOverflowDefined());
3184 if (Length && LowerBound) {
3185 Idx = Builder.CreateSub(
3186 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3187 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3188 }
3189 } else
3190 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3191 } else {
3192 // Idx = ArraySize - 1;
Alexey Bataev31300ed2016-02-04 11:27:03 +00003193 QualType ArrayTy = BaseTy->isPointerType()
3194 ? E->getBase()->IgnoreParenImpCasts()->getType()
3195 : BaseTy;
3196 if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003197 Length = VAT->getSizeExpr();
3198 if (Length->isIntegerConstantExpr(ConstLength, C))
3199 Length = nullptr;
3200 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003201 auto *CAT = C.getAsConstantArrayType(ArrayTy);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003202 ConstLength = CAT->getSize();
3203 }
3204 if (Length) {
3205 auto *LengthVal = Builder.CreateIntCast(
3206 EmitScalarExpr(Length), IntPtrTy,
3207 Length->getType()->hasSignedIntegerRepresentation());
3208 Idx = Builder.CreateSub(
3209 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3210 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3211 } else {
3212 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3213 --ConstLength;
3214 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3215 }
3216 }
3217 }
3218 assert(Idx);
3219
Alexey Bataev31300ed2016-02-04 11:27:03 +00003220 Address EltPtr = Address::invalid();
3221 AlignmentSource AlignSource;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003222 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003223 // The base must be a pointer, which is not an aggregate. Emit
3224 // it. It needs to be emitted first in case it's what captures
3225 // the VLA bounds.
3226 Address Base =
3227 emitOMPArraySectionBase(*this, E->getBase(), AlignSource, BaseTy,
3228 VLA->getElementType(), IsLowerBound);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003229 // The element count here is the total number of non-VLA elements.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003230 llvm::Value *NumElements = getVLASize(VLA).first;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003231
3232 // Effectively, the multiply by the VLA size is part of the GEP.
3233 // GEP indexes are signed, and scaling an index isn't permitted to
3234 // signed-overflow, so we use the same semantics for our explicit
3235 // multiply. We suppress this if overflow is not undefined behavior.
Alexey Bataev31300ed2016-02-04 11:27:03 +00003236 if (getLangOpts().isSignedOverflowDefined())
3237 Idx = Builder.CreateMul(Idx, NumElements);
3238 else
3239 Idx = Builder.CreateNSWMul(Idx, NumElements);
3240 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3241 !getLangOpts().isSignedOverflowDefined());
3242 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3243 // If this is A[i] where A is an array, the frontend will have decayed the
3244 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
3245 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3246 // "gep x, i" here. Emit one "gep A, 0, i".
3247 assert(Array->getType()->isArrayType() &&
3248 "Array to pointer decay must have array source type!");
3249 LValue ArrayLV;
3250 // For simple multidimensional array indexing, set the 'accessed' flag for
3251 // better bounds-checking of the base expression.
3252 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3253 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3254 else
3255 ArrayLV = EmitLValue(Array);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003256
Alexey Bataev31300ed2016-02-04 11:27:03 +00003257 // Propagate the alignment from the array itself to the result.
3258 EltPtr = emitArraySubscriptGEP(
3259 *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3260 ResultExprTy, !getLangOpts().isSignedOverflowDefined());
3261 AlignSource = ArrayLV.getAlignmentSource();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003262 } else {
Alexey Bataev31300ed2016-02-04 11:27:03 +00003263 Address Base = emitOMPArraySectionBase(*this, E->getBase(), AlignSource,
3264 BaseTy, ResultExprTy, IsLowerBound);
3265 EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3266 !getLangOpts().isSignedOverflowDefined());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003267 }
3268
Alexey Bataev31300ed2016-02-04 11:27:03 +00003269 return MakeAddrLValue(EltPtr, ResultExprTy, AlignSource);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00003270}
3271
Chris Lattner9e751ca2007-08-02 23:37:31 +00003272LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00003273EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00003274 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00003275 LValue Base;
3276
3277 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00003278 if (E->isArrow()) {
3279 // If it is a pointer to a vector, emit the address and form an lvalue with
3280 // it.
John McCall7f416cc2015-09-08 08:05:57 +00003281 AlignmentSource AlignSource;
3282 Address Ptr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003283 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
John McCall7f416cc2015-09-08 08:05:57 +00003284 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00003285 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00003286 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00003287 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3288 // emit the base as an lvalue.
3289 assert(E->getBase()->getType()->isVectorType());
3290 Base = EmitLValue(E->getBase());
3291 } else {
3292 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00003293 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00003294 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00003295 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00003296
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00003297 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00003298 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00003299 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00003300 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3301 AlignmentSource::Decl);
Chris Lattner4e1a3232009-12-23 21:31:11 +00003302 }
John McCall1553b192011-06-16 04:16:24 +00003303
3304 QualType type =
3305 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00003306
Nate Begemand3862152008-05-13 21:03:02 +00003307 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00003308 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00003309 E->getEncodedElementAccess(Indices);
3310
3311 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00003312 llvm::Constant *CV =
3313 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00003314 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
John McCall7f416cc2015-09-08 08:05:57 +00003315 Base.getAlignmentSource());
Nate Begemand3862152008-05-13 21:03:02 +00003316 }
3317 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3318
3319 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003320 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00003321
Chris Lattner595ba3a2012-01-30 06:20:36 +00003322 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3323 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00003324 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00003325 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3326 Base.getAlignmentSource());
Chris Lattner9e751ca2007-08-02 23:37:31 +00003327}
3328
Devang Patel30efa2e2007-10-23 20:28:39 +00003329LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00003330 Expr *BaseExpr = E->getBase();
Eli Friedman327944b2008-06-13 23:01:12 +00003331
Chris Lattner4e4186b2007-12-02 18:52:07 +00003332 // 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 +00003333 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00003334 if (E->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00003335 AlignmentSource AlignSource;
3336 Address Addr = EmitPointerWithAlignment(BaseExpr, &AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003337 QualType PtrTy = BaseExpr->getType()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003338 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy);
3339 BaseLV = MakeAddrLValue(Addr, PtrTy, AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003340 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003341 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003342
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003343 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003344 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003345 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003346 setObjCGCLValueClass(getContext(), E, LV);
3347 return LV;
3348 }
Craig Topper99e79272013-07-26 05:59:26 +00003349
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003350 if (auto *VD = dyn_cast<VarDecl>(ND))
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00003351 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003352
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003353 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003354 return EmitFunctionDeclLValue(*this, E, FD);
3355
David Blaikie83d382b2011-09-23 05:06:16 +00003356 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003357}
Devang Patel30efa2e2007-10-23 20:28:39 +00003358
John McCalldec348f72013-05-03 07:33:41 +00003359/// Given that we are currently emitting a lambda, emit an l-value for
3360/// one of its members.
3361LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3362 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3363 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3364 QualType LambdaTagType =
3365 getContext().getTagDeclType(Field->getParent());
3366 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3367 return EmitLValueForField(LambdaLV, Field);
3368}
3369
John McCall7f416cc2015-09-08 08:05:57 +00003370/// Drill down to the storage of a field without walking into
3371/// reference types.
3372///
3373/// The resulting address doesn't necessarily have the right type.
3374static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3375 const FieldDecl *field) {
3376 const RecordDecl *rec = field->getParent();
3377
3378 unsigned idx =
3379 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3380
3381 CharUnits offset;
3382 // Adjust the alignment down to the given offset.
3383 // As a special case, if the LLVM field index is 0, we know that this
3384 // is zero.
3385 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3386 .getFieldOffset(field->getFieldIndex()) == 0) &&
3387 "LLVM field at index zero had non-zero offset?");
3388 if (idx != 0) {
3389 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3390 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3391 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3392 }
3393
3394 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3395}
3396
Eli Friedman7f1ff602012-04-16 03:54:45 +00003397LValue CodeGenFunction::EmitLValueForField(LValue base,
3398 const FieldDecl *field) {
John McCall7f416cc2015-09-08 08:05:57 +00003399 AlignmentSource fieldAlignSource =
3400 getFieldAlignmentSource(base.getAlignmentSource());
3401
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003402 if (field->isBitField()) {
3403 const CGRecordLayout &RL =
3404 CGM.getTypes().getCGRecordLayout(field->getParent());
3405 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003406 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003407 unsigned Idx = RL.getLLVMFieldNo(field);
3408 if (Idx != 0)
3409 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003410 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3411 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003412 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003413 llvm::Type *FieldIntTy =
3414 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3415 if (Addr.getElementType() != FieldIntTy)
3416 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003417
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003418 QualType fieldType =
3419 field->getType().withCVRQualifiers(base.getVRQualifiers());
John McCall7f416cc2015-09-08 08:05:57 +00003420 return LValue::MakeBitfield(Addr, Info, fieldType, fieldAlignSource);
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003421 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003422
John McCall53fcbd22011-02-26 08:07:02 +00003423 const RecordDecl *rec = field->getParent();
3424 QualType type = field->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003425
John McCall53fcbd22011-02-26 08:07:02 +00003426 bool mayAlias = rec->hasAttr<MayAliasAttr>();
3427
John McCall7f416cc2015-09-08 08:05:57 +00003428 Address addr = base.getAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003429 unsigned cvr = base.getVRQualifiers();
Manman Renc451e572013-04-04 21:53:22 +00003430 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
John McCall53fcbd22011-02-26 08:07:02 +00003431 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003432 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00003433 assert(!type->isReferenceType() && "union has reference member");
Manman Renc451e572013-04-04 21:53:22 +00003434 // TODO: handle path-aware TBAA for union.
3435 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003436 } else {
3437 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003438 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003439
3440 // If this is a reference field, load the reference right now.
3441 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3442 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3443 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3444
Manman Renc451e572013-04-04 21:53:22 +00003445 // Loading the reference will disable path-aware TBAA.
3446 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003447 if (CGM.shouldUseTBAA()) {
3448 llvm::MDNode *tbaa;
3449 if (mayAlias)
3450 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3451 else
3452 tbaa = CGM.getTBAAInfo(type);
Manman Ren4f755de2013-10-08 00:08:49 +00003453 if (tbaa)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00003454 CGM.DecorateInstructionWithTBAA(load, tbaa);
John McCall53fcbd22011-02-26 08:07:02 +00003455 }
3456
John McCall53fcbd22011-02-26 08:07:02 +00003457 mayAlias = false;
3458 type = refType->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003459
3460 CharUnits alignment =
3461 getNaturalTypeAlignment(type, &fieldAlignSource, /*pointee*/ true);
3462 addr = Address(load, alignment);
3463
3464 // Qualifiers on the struct don't apply to the referencee, and
3465 // we'll pick up CVR from the actual type later, so reset these
3466 // additional qualifiers now.
3467 cvr = 0;
John McCall53fcbd22011-02-26 08:07:02 +00003468 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003469 }
Craig Topper99e79272013-07-26 05:59:26 +00003470
Chris Lattner13ee4f42011-07-10 05:34:54 +00003471 // Make sure that the address is pointing to the right type. This is critical
3472 // for both unions and structs. A union needs a bitcast, a struct element
3473 // will need a bitcast if the LLVM type laid out doesn't match the desired
3474 // type.
John McCall7f416cc2015-09-08 08:05:57 +00003475 addr = Builder.CreateElementBitCast(addr,
3476 CGM.getTypes().ConvertTypeForMem(type),
3477 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003478
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003479 if (field->hasAttr<AnnotateAttr>())
3480 addr = EmitFieldAnnotations(field, addr);
3481
John McCall7f416cc2015-09-08 08:05:57 +00003482 LValue LV = MakeAddrLValue(addr, type, fieldAlignSource);
John McCall53fcbd22011-02-26 08:07:02 +00003483 LV.getQuals().addCVRQualifiers(cvr);
Manman Renc451e572013-04-04 21:53:22 +00003484 if (TBAAPath) {
3485 const ASTRecordLayout &Layout =
3486 getContext().getASTRecordLayout(field->getParent());
3487 // Set the base type to be the base type of the base LValue and
3488 // update offset to be relative to the base type.
Manman Ren0e521662013-04-27 00:39:37 +00003489 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3490 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
Manman Renc451e572013-04-04 21:53:22 +00003491 Layout.getFieldOffset(field->getFieldIndex()) /
3492 getContext().getCharWidth());
3493 }
Daniel Dunbarf166a522010-08-21 03:44:13 +00003494
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003495 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003496 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3497 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003498
3499 // Fields of may_alias structs act like 'char' for TBAA purposes.
3500 // FIXME: this should get propagated down through anonymous structs
3501 // and unions.
3502 if (mayAlias && LV.getTBAAInfo())
3503 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3504
Daniel Dunbarf166a522010-08-21 03:44:13 +00003505 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003506}
3507
Craig Topper99e79272013-07-26 05:59:26 +00003508LValue
3509CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003510 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003511 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003512
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003513 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003514 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003515
John McCall7f416cc2015-09-08 08:05:57 +00003516 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003517
John McCall7f416cc2015-09-08 08:05:57 +00003518 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003519 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003520 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003521
John McCall7f416cc2015-09-08 08:05:57 +00003522 // TODO: access-path TBAA?
3523 auto FieldAlignSource = getFieldAlignmentSource(Base.getAlignmentSource());
3524 return MakeAddrLValue(V, FieldType, FieldAlignSource);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003525}
3526
Chris Lattnerf53c0962010-09-06 00:11:41 +00003527LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00003528 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003529 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3530 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
Richard Smith2d988f02011-11-22 22:48:32 +00003531 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003532 if (E->getType()->isVariablyModifiedType())
3533 // make sure to emit the VLA size.
3534 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003535
John McCall7f416cc2015-09-08 08:05:57 +00003536 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003537 const Expr *InitExpr = E->getInitializer();
John McCall7f416cc2015-09-08 08:05:57 +00003538 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003539
Chad Rosier615ed1a2012-03-29 17:37:10 +00003540 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3541 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003542
3543 return Result;
3544}
3545
Richard Smithbb653bd2012-05-14 21:57:21 +00003546LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3547 if (!E->isGLValue())
3548 // Initializing an aggregate temporary in C++11: T{...}.
3549 return EmitAggExprToLValue(E);
3550
3551 // An lvalue initializer list must be initializing a reference.
Richard Smith122f88d2016-12-06 23:52:28 +00003552 assert(E->isTransparent() && "non-transparent glvalue init list");
Richard Smithbb653bd2012-05-14 21:57:21 +00003553 return EmitLValue(E->getInit(0));
3554}
3555
Richard Smithf3076ff2014-06-20 18:43:47 +00003556/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3557/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3558/// LValue is returned and the current block has been terminated.
3559static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3560 const Expr *Operand) {
3561 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3562 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3563 return None;
3564 }
3565
3566 return CGF.EmitLValue(Operand);
3567}
3568
John McCallc07a0c72011-02-17 10:25:35 +00003569LValue CodeGenFunction::
3570EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3571 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003572 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003573 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003574 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003575 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003576 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003577
Eli Friedman59954892012-01-25 05:04:17 +00003578 OpaqueValueMapping binding(*this, expr);
3579
John McCallc07a0c72011-02-17 10:25:35 +00003580 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003581 bool CondExprBool;
3582 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003583 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003584 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003585
Justin Bogneref512b92014-01-06 22:27:43 +00003586 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003587 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003588 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003589 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003590 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003591 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003592 }
3593
John McCallc07a0c72011-02-17 10:25:35 +00003594 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3595 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3596 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003597
3598 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003599 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003600
John McCall0a6bf2e2011-01-26 19:21:13 +00003601 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003602 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003603 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003604 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003605 Optional<LValue> lhs =
3606 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003607 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003608
Richard Smithf3076ff2014-06-20 18:43:47 +00003609 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003610 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003611
John McCallc07a0c72011-02-17 10:25:35 +00003612 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003613 if (lhs)
3614 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003615
John McCall0a6bf2e2011-01-26 19:21:13 +00003616 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003617 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003618 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003619 Optional<LValue> rhs =
3620 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003621 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003622 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003623 return EmitUnsupportedLValue(expr, "conditional operator");
3624 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003625
John McCallc07a0c72011-02-17 10:25:35 +00003626 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003627
Richard Smithf3076ff2014-06-20 18:43:47 +00003628 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003629 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003630 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003631 phi->addIncoming(lhs->getPointer(), lhsBlock);
3632 phi->addIncoming(rhs->getPointer(), rhsBlock);
3633 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3634 AlignmentSource alignSource =
3635 std::max(lhs->getAlignmentSource(), rhs->getAlignmentSource());
3636 return MakeAddrLValue(result, expr->getType(), alignSource);
Richard Smithf3076ff2014-06-20 18:43:47 +00003637 } else {
3638 assert((lhs || rhs) &&
3639 "both operands of glvalue conditional are throw-expressions?");
3640 return lhs ? *lhs : *rhs;
3641 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003642}
3643
Richard Smithbb653bd2012-05-14 21:57:21 +00003644/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3645/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003646/// otherwise if a cast is needed by the code generator in an lvalue context,
3647/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003648/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003649/// are permitted with aggregate result, including noop aggregate casts, and
3650/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003651LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003652 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003653 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003654 case CK_BitCast:
3655 case CK_ArrayToPointerDecay:
3656 case CK_FunctionToPointerDecay:
3657 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003658 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003659 case CK_IntegralToPointer:
3660 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003661 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003662 case CK_VectorSplat:
3663 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00003664 case CK_BooleanToSignedIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003665 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003666 case CK_IntegralToFloating:
3667 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003668 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003669 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003670 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003671 case CK_FloatingComplexToReal:
3672 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003673 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003674 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003675 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003676 case CK_IntegralComplexToReal:
3677 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003678 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003679 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003680 case CK_DerivedToBaseMemberPointer:
3681 case CK_BaseToDerivedMemberPointer:
3682 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003683 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003684 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003685 case CK_ARCProduceObject:
3686 case CK_ARCConsumeObject:
3687 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003688 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003689 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003690 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00003691 case CK_IntToOCLSampler:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003692 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3693
3694 case CK_Dependent:
3695 llvm_unreachable("dependent cast kind in IR gen!");
3696
3697 case CK_BuiltinFnToFnPtr:
3698 llvm_unreachable("builtin functions are handled elsewhere");
3699
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003700 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003701 case CK_NonAtomicToAtomic:
3702 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003703 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00003704
Anders Carlsson8a01a752011-04-11 02:03:26 +00003705 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00003706 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003707 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003708 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00003709 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00003710 }
3711
John McCalle3027922010-08-25 11:45:40 +00003712 case CK_ConstructorConversion:
3713 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00003714 case CK_CPointerToObjCPointerCast:
3715 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003716 case CK_NoOp:
3717 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003718 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00003719
John McCalle3027922010-08-25 11:45:40 +00003720 case CK_UncheckedDerivedToBase:
3721 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00003722 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00003723 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003724 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003725
Anders Carlssond95f9602009-09-12 16:16:49 +00003726 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003727 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00003728
Anders Carlssond95f9602009-09-12 16:16:49 +00003729 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00003730 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00003731 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3732 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00003733
John McCall7f416cc2015-09-08 08:05:57 +00003734 return MakeAddrLValue(Base, E->getType(), LV.getAlignmentSource());
Anders Carlssond95f9602009-09-12 16:16:49 +00003735 }
John McCalle3027922010-08-25 11:45:40 +00003736 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00003737 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00003738 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00003739 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003740 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003741
Anders Carlsson8c793172009-11-23 17:57:54 +00003742 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00003743
Anders Carlsson8c793172009-11-23 17:57:54 +00003744 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00003745 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00003746 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00003747 E->path_begin(), E->path_end(),
3748 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00003749
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003750 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3751 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00003752 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003753 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00003754 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003755
Peter Collingbourned2926c92015-03-14 02:42:25 +00003756 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003757 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3758 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003759 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003760
John McCall7f416cc2015-09-08 08:05:57 +00003761 return MakeAddrLValue(Derived, E->getType(), LV.getAlignmentSource());
Eli Friedman8c98dff2009-11-16 05:48:01 +00003762 }
John McCalle3027922010-08-25 11:45:40 +00003763 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00003764 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003765 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00003766
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00003767 CGM.EmitExplicitCastExprType(CE, this);
Anders Carlsson50cb3212009-11-14 21:21:42 +00003768 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003769 Address V = Builder.CreateBitCast(LV.getAddress(),
3770 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00003771
3772 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003773 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3774 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003775 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003776
John McCall7f416cc2015-09-08 08:05:57 +00003777 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Anders Carlsson50cb3212009-11-14 21:21:42 +00003778 }
John McCalle3027922010-08-25 11:45:40 +00003779 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003780 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003781 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3782 ConvertType(E->getType()));
3783 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003784 }
Egor Churaev89831422016-12-23 14:55:49 +00003785 case CK_ZeroToOCLQueue:
3786 llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003787 case CK_ZeroToOCLEvent:
3788 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00003789 }
Craig Topper99e79272013-07-26 05:59:26 +00003790
Douglas Gregorcdb466e2010-07-15 18:58:16 +00003791 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003792}
3793
John McCall1bf58462011-02-16 08:02:54 +00003794LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00003795 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00003796 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00003797}
3798
Eli Friedman7f1ff602012-04-16 03:54:45 +00003799RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003800 const FieldDecl *FD,
3801 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003802 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003803 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00003804 switch (getEvaluationKind(FT)) {
3805 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003806 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00003807 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00003808 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00003809 case TEK_Scalar:
Reid Kleckner9d031092016-05-02 22:42:34 +00003810 // This routine is used to load fields one-by-one to perform a copy, so
3811 // don't load reference fields.
3812 if (FD->getType()->isReferenceType())
3813 return RValue::get(FieldLV.getPointer());
Nick Lewycky2d84e842013-10-02 02:29:49 +00003814 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00003815 }
3816 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003817}
Douglas Gregorfe314812011-06-21 17:03:29 +00003818
Chris Lattnere47e4402007-06-01 18:02:12 +00003819//===--------------------------------------------------------------------===//
3820// Expression Emission
3821//===--------------------------------------------------------------------===//
3822
Craig Topper99e79272013-07-26 05:59:26 +00003823RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00003824 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003825 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003826 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00003827 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003828
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003829 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003830 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003831
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003832 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00003833 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3834
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003835 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
John McCallb92ab1a2016-10-26 23:46:34 +00003836 if (const CXXMethodDecl *MD =
3837 dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003838 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003839
John McCallb92ab1a2016-10-26 23:46:34 +00003840 CGCallee callee = EmitCallee(E->getCallee());
Craig Topper99e79272013-07-26 05:59:26 +00003841
John McCallb92ab1a2016-10-26 23:46:34 +00003842 if (callee.isBuiltin()) {
3843 return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
3844 E, ReturnValue);
Douglas Gregorad8a3362009-09-04 17:36:40 +00003845 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003846
John McCallb92ab1a2016-10-26 23:46:34 +00003847 if (callee.isPseudoDestructor()) {
3848 return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
3849 }
3850
3851 return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
3852}
3853
3854/// Emit a CallExpr without considering whether it might be a subclass.
3855RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
3856 ReturnValueSlot ReturnValue) {
3857 CGCallee Callee = EmitCallee(E->getCallee());
3858 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
3859}
3860
3861static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
3862 if (auto builtinID = FD->getBuiltinID()) {
3863 return CGCallee::forBuiltin(builtinID, FD);
3864 }
3865
3866 llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
3867 return CGCallee::forDirect(calleePtr, FD);
3868}
3869
3870CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
3871 E = E->IgnoreParens();
3872
3873 // Look through function-to-pointer decay.
3874 if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
3875 if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
3876 ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
3877 return EmitCallee(ICE->getSubExpr());
3878 }
3879
3880 // Resolve direct calls.
3881 } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
3882 if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
3883 return EmitDirectCallee(*this, FD);
3884 }
3885 } else if (auto ME = dyn_cast<MemberExpr>(E)) {
3886 if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
3887 EmitIgnoredExpr(ME->getBase());
3888 return EmitDirectCallee(*this, FD);
3889 }
3890
3891 // Look through template substitutions.
3892 } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
3893 return EmitCallee(NTTP->getReplacement());
3894
3895 // Treat pseudo-destructor calls differently.
3896 } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
3897 return CGCallee::forPseudoDestructor(PDE);
3898 }
3899
3900 // Otherwise, we have an indirect reference.
3901 llvm::Value *calleePtr;
3902 QualType functionType;
3903 if (auto ptrType = E->getType()->getAs<PointerType>()) {
3904 calleePtr = EmitScalarExpr(E);
3905 functionType = ptrType->getPointeeType();
3906 } else {
3907 functionType = E->getType();
3908 calleePtr = EmitLValue(E).getPointer();
3909 }
3910 assert(functionType->isFunctionType());
3911 CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
3912 E->getReferencedDeclOfCallee());
3913 CGCallee callee(calleeInfo, calleePtr);
3914 return callee;
Chris Lattner9e47ead2007-08-31 04:44:06 +00003915}
3916
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003917LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00003918 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00003919 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00003920 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00003921 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00003922 return EmitLValue(E->getRHS());
3923 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003924
John McCalle3027922010-08-25 11:45:40 +00003925 if (E->getOpcode() == BO_PtrMemD ||
3926 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003927 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003928
John McCalla2342eb2010-12-05 02:00:02 +00003929 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00003930
3931 // Note that in all of these cases, __block variables need the RHS
3932 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00003933
3934 switch (getEvaluationKind(E->getType())) {
3935 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00003936 switch (E->getLHS()->getType().getObjCLifetime()) {
3937 case Qualifiers::OCL_Strong:
3938 return EmitARCStoreStrong(E, /*ignored*/ false).first;
3939
3940 case Qualifiers::OCL_Autoreleasing:
3941 return EmitARCStoreAutoreleasing(E).first;
3942
3943 // No reason to do any of these differently.
3944 case Qualifiers::OCL_None:
3945 case Qualifiers::OCL_ExplicitNone:
3946 case Qualifiers::OCL_Weak:
3947 break;
3948 }
3949
John McCalld0a30012010-12-06 06:10:02 +00003950 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00003951 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
John McCall55e1fbc2011-06-25 02:11:03 +00003952 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00003953 return LV;
3954 }
John McCall4f29b492010-11-16 23:07:28 +00003955
John McCall47fb9502013-03-07 21:37:08 +00003956 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00003957 return EmitComplexAssignmentLValue(E);
3958
John McCall47fb9502013-03-07 21:37:08 +00003959 case TEK_Aggregate:
3960 return EmitAggExprToLValue(E);
3961 }
3962 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003963}
3964
Christopher Lambd91c3d42007-12-29 05:02:41 +00003965LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00003966 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00003967
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003968 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00003969 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3970 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00003971
David Majnemerced8bdf2015-02-25 17:36:15 +00003972 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003973 "Can't have a scalar return unless the return type is a "
3974 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00003975
John McCall7f416cc2015-09-08 08:05:57 +00003976 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00003977}
3978
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003979LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
3980 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00003981 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003982}
3983
Anders Carlsson3be22e22009-05-30 23:23:33 +00003984LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003985 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
3986 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00003987 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00003988 EmitCXXConstructExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003989 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3990 AlignmentSource::Decl);
Anders Carlsson3be22e22009-05-30 23:23:33 +00003991}
3992
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003993LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00003994CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003995 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00003996}
3997
John McCall7f416cc2015-09-08 08:05:57 +00003998Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
3999 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4000 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00004001}
4002
4003LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004004 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
4005 AlignmentSource::Decl);
Nico Webercf4ff5862012-10-11 10:13:44 +00004006}
4007
Mike Stumpc9b231c2009-11-15 08:09:41 +00004008LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004009CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00004010 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00004011 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00004012 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004013 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
4014 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4015 AlignmentSource::Decl);
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00004016}
4017
Eli Friedman5bc17122012-02-08 05:34:55 +00004018LValue
4019CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00004020 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00004021 EmitLambdaExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00004022 return MakeAddrLValue(Slot.getAddress(), E->getType(),
4023 AlignmentSource::Decl);
Eli Friedman5bc17122012-02-08 05:34:55 +00004024}
4025
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004026LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004027 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00004028
Anders Carlsson280e61f12010-06-21 20:59:55 +00004029 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00004030 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4031 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00004032
Alp Toker314cc812014-01-25 16:55:45 +00004033 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00004034 "Can't have a scalar return unless the return type is a "
4035 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00004036
John McCall7f416cc2015-09-08 08:05:57 +00004037 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00004038}
4039
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004040LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004041 Address V =
4042 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
4043 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00004044}
4045
Daniel Dunbar722f4242009-04-22 05:08:15 +00004046llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004047 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00004048 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004049}
4050
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004051LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4052 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004053 const ObjCIvarDecl *Ivar,
4054 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00004055 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00004056 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004057}
4058
4059LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004060 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00004061 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004062 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00004063 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004064 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004065 if (E->isArrow()) {
4066 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00004067 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00004068 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004069 } else {
4070 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00004071 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00004072 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00004073 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00004074 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00004075
Craig Topper99e79272013-07-26 05:59:26 +00004076 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00004077 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4078 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00004079 setObjCGCLValueClass(getContext(), E, LV);
4080 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00004081}
4082
Chris Lattnera4185c52009-04-25 19:35:26 +00004083LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00004084 // Can only get l-value for message expression returning aggregate type
4085 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00004086 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4087 AlignmentSource::Decl);
Chris Lattnera4185c52009-04-25 19:35:26 +00004088}
4089
John McCallb92ab1a2016-10-26 23:46:34 +00004090RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004091 const CallExpr *E, ReturnValueSlot ReturnValue,
John McCallb92ab1a2016-10-26 23:46:34 +00004092 llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00004093 // Get the actual function type. The callee type will always be a pointer to
4094 // function type or a block pointer type.
4095 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00004096 "Call must have function pointer type!");
4097
John McCallb92ab1a2016-10-26 23:46:34 +00004098 const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
Samuel Antao798f11c2015-11-23 22:04:44 +00004099
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004100 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
Eric Christopher39db7262015-11-14 01:56:04 +00004101 // We can only guarantee that a function is called from the correct
4102 // context/function based on the appropriate target attributes,
4103 // so only check in the case where we have both always_inline and target
4104 // since otherwise we could be making a conditional call after a check for
4105 // the proper cpu features (and it won't cause code generation issues due to
4106 // function based code generation).
Eric Christopher2b2d56f2015-11-12 00:44:12 +00004107 if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4108 TargetDecl->hasAttr<TargetAttr>())
4109 checkTargetFeatures(E, FD);
4110
John McCall6fd4c232009-10-23 08:22:42 +00004111 CalleeType = getContext().getCanonicalType(CalleeType);
4112
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004113 const auto *FnType =
4114 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00004115
John McCallb92ab1a2016-10-26 23:46:34 +00004116 CGCallee Callee = OrigCallee;
4117
Alexey Samsonovedf99a92014-11-07 22:29:38 +00004118 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004119 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4120 if (llvm::Constant *PrefixSig =
4121 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00004122 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004123 llvm::Constant *FTRTTIConst =
4124 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4125 llvm::Type *PrefixStructTyElems[] = {
4126 PrefixSig->getType(),
4127 FTRTTIConst->getType()
4128 };
4129 llvm::StructType *PrefixStructTy = llvm::StructType::get(
4130 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4131
John McCallb92ab1a2016-10-26 23:46:34 +00004132 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4133
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004134 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
John McCallb92ab1a2016-10-26 23:46:34 +00004135 CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004136 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004137 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00004138 llvm::Value *CalleeSig =
4139 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004140 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4141
4142 llvm::BasicBlock *Cont = createBasicBlock("cont");
4143 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4144 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4145
4146 EmitBlock(TypeCheck);
4147 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00004148 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
John McCall7f416cc2015-09-08 08:05:57 +00004149 llvm::Value *CalleeRTTI =
4150 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004151 llvm::Value *CalleeRTTIMatch =
4152 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4153 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00004154 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004155 EmitCheckTypeDescriptor(CalleeType)
4156 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00004157 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004158 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00004159
4160 Builder.CreateBr(Cont);
4161 EmitBlock(Cont);
4162 }
4163 }
4164
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004165 // If we are checking indirect calls and this call is indirect, check that the
4166 // function pointer is a member of the bit set for the function type.
4167 if (SanOpts.has(SanitizerKind::CFIICall) &&
4168 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4169 SanitizerScope SanScope(this);
Peter Collingbournedc134532016-01-16 00:31:22 +00004170 EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004171
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004172 llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004173 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004174
John McCallb92ab1a2016-10-26 23:46:34 +00004175 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4176 llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004177 llvm::Value *TypeTest = Builder.CreateCall(
4178 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004179
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004180 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004181 llvm::Constant *StaticData[] = {
4182 llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4183 EmitCheckSourceLocation(E->getLocStart()),
4184 EmitCheckTypeDescriptor(QualType(FnType, 0)),
4185 };
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004186 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4187 EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
Evgeniy Stepanov3fd61df2016-01-25 23:34:52 +00004188 CastedCallee, StaticData);
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004189 } else {
Peter Collingbourne8dd14da2016-06-24 21:21:46 +00004190 EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00004191 SanitizerHandler::CFICheckFail, StaticData,
Evgeniy Stepanovf31ea302016-02-03 22:18:55 +00004192 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
Evgeniy Stepanovfd6f92d2015-12-15 23:00:20 +00004193 }
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00004194 }
4195
Daniel Dunbarc722b852008-08-30 03:02:31 +00004196 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00004197 if (Chain)
4198 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4199 CGM.getContext().VoidPtrTy);
Richard Smith762672a2016-09-28 19:09:10 +00004200
4201 // C++17 requires that we evaluate arguments to a call using assignment syntax
Richard Smitha560ccf2016-09-29 21:30:12 +00004202 // right-to-left, and that we evaluate arguments to certain other operators
4203 // left-to-right. Note that we allow this to override the order dictated by
4204 // the calling convention on the MS ABI, which means that parameter
4205 // destruction order is not necessarily reverse construction order.
4206 // FIXME: Revisit this based on C++ committee response to unimplementability.
4207 EvaluationOrder Order = EvaluationOrder::Default;
4208 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4209 if (OCE->isAssignmentOp())
4210 Order = EvaluationOrder::ForceRightToLeft;
4211 else {
4212 switch (OCE->getOperator()) {
4213 case OO_LessLess:
4214 case OO_GreaterGreater:
4215 case OO_AmpAmp:
4216 case OO_PipePipe:
4217 case OO_Comma:
4218 case OO_ArrowStar:
4219 Order = EvaluationOrder::ForceLeftToRight;
4220 break;
4221 default:
4222 break;
4223 }
4224 }
4225 }
Richard Smith762672a2016-09-28 19:09:10 +00004226
David Blaikief05779e2015-07-21 18:37:18 +00004227 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
Richard Smitha560ccf2016-09-29 21:30:12 +00004228 E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
Daniel Dunbarc722b852008-08-30 03:02:31 +00004229
Peter Collingbournef7706832014-12-12 23:41:25 +00004230 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4231 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00004232
4233 // C99 6.5.2.2p6:
4234 // If the expression that denotes the called function has a type
4235 // that does not include a prototype, [the default argument
4236 // promotions are performed]. If the number of arguments does not
4237 // equal the number of parameters, the behavior is undefined. If
4238 // the function is defined with a type that includes a prototype,
4239 // and either the prototype ends with an ellipsis (, ...) or the
4240 // types of the arguments after promotion are not compatible with
4241 // the types of the parameters, the behavior is undefined. If the
4242 // function is defined with a type that does not include a
4243 // prototype, and the types of the arguments after promotion are
4244 // not compatible with those of the parameters after promotion,
4245 // the behavior is undefined [except in some trivial cases].
4246 // That is, in the general case, we should assume that a call
4247 // through an unprototyped function type works like a *non-variadic*
4248 // call. The way we make this work is to cast to the exact type
4249 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00004250 //
4251 // Chain calls use this same code path to add the invisible chain parameter
4252 // to the function type.
4253 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00004254 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00004255 CalleeTy = CalleeTy->getPointerTo();
John McCallb92ab1a2016-10-26 23:46:34 +00004256
4257 llvm::Value *CalleePtr = Callee.getFunctionPointer();
4258 CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4259 Callee.setFunctionPointer(CalleePtr);
John McCallcbc038a2011-09-21 08:08:30 +00004260 }
4261
John McCallb92ab1a2016-10-26 23:46:34 +00004262 return EmitCall(FnInfo, Callee, ReturnValue, Args);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00004263}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004264
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004265LValue CodeGenFunction::
4266EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00004267 Address BaseAddr = Address::invalid();
4268 if (E->getOpcode() == BO_PtrMemI) {
4269 BaseAddr = EmitPointerWithAlignment(E->getLHS());
4270 } else {
4271 BaseAddr = EmitLValue(E->getLHS()).getAddress();
4272 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00004273
John McCallc134eb52010-08-31 21:07:20 +00004274 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4275
4276 const MemberPointerType *MPT
4277 = E->getRHS()->getType()->getAs<MemberPointerType>();
4278
John McCall7f416cc2015-09-08 08:05:57 +00004279 AlignmentSource AlignSource;
4280 Address MemberAddr =
4281 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT,
4282 &AlignSource);
John McCallc134eb52010-08-31 21:07:20 +00004283
John McCall7f416cc2015-09-08 08:05:57 +00004284 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), AlignSource);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00004285}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004286
John McCall47fb9502013-03-07 21:37:08 +00004287/// Given the address of a temporary variable, produce an r-value of
4288/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00004289RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00004290 QualType type,
4291 SourceLocation loc) {
John McCall7f416cc2015-09-08 08:05:57 +00004292 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
John McCall47fb9502013-03-07 21:37:08 +00004293 switch (getEvaluationKind(type)) {
4294 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004295 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004296 case TEK_Aggregate:
4297 return lvalue.asAggregateRValue();
4298 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00004299 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00004300 }
4301 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004302}
4303
Duncan Sandse81111c2012-04-10 08:23:07 +00004304void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004305 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00004306 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004307 return;
4308
Duncan Sands65229ed2012-04-16 16:29:47 +00004309 llvm::MDBuilder MDHelper(getLLVMContext());
4310 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004311
Duncan Sands6fc46192012-04-14 12:37:26 +00004312 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00004313}
John McCallfe96e0b2011-11-06 09:01:30 +00004314
4315namespace {
4316 struct LValueOrRValue {
4317 LValue LV;
4318 RValue RV;
4319 };
4320}
4321
4322static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4323 const PseudoObjectExpr *E,
4324 bool forLValue,
4325 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004326 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00004327
4328 // Find the result expression, if any.
4329 const Expr *resultExpr = E->getResultExpr();
4330 LValueOrRValue result;
4331
4332 for (PseudoObjectExpr::const_semantics_iterator
4333 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4334 const Expr *semantic = *i;
4335
4336 // If this semantic expression is an opaque value, bind it
4337 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00004338 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00004339
4340 // If this is the result expression, we may need to evaluate
4341 // directly into the slot.
4342 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4343 OVMA opaqueData;
4344 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00004345 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00004346 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
4347
John McCall7f416cc2015-09-08 08:05:57 +00004348 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4349 AlignmentSource::Decl);
John McCallfe96e0b2011-11-06 09:01:30 +00004350 opaqueData = OVMA::bind(CGF, ov, LV);
4351 result.RV = slot.asRValue();
4352
4353 // Otherwise, emit as normal.
4354 } else {
4355 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4356
4357 // If this is the result, also evaluate the result now.
4358 if (ov == resultExpr) {
4359 if (forLValue)
4360 result.LV = CGF.EmitLValue(ov);
4361 else
4362 result.RV = CGF.EmitAnyExpr(ov, slot);
4363 }
4364 }
4365
4366 opaques.push_back(opaqueData);
4367
4368 // Otherwise, if the expression is the result, evaluate it
4369 // and remember the result.
4370 } else if (semantic == resultExpr) {
4371 if (forLValue)
4372 result.LV = CGF.EmitLValue(semantic);
4373 else
4374 result.RV = CGF.EmitAnyExpr(semantic, slot);
4375
4376 // Otherwise, evaluate the expression in an ignored context.
4377 } else {
4378 CGF.EmitIgnoredExpr(semantic);
4379 }
4380 }
4381
4382 // Unbind all the opaques now.
4383 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4384 opaques[i].unbind(CGF);
4385
4386 return result;
4387}
4388
4389RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4390 AggValueSlot slot) {
4391 return emitPseudoObjectExpr(*this, E, false, slot).RV;
4392}
4393
4394LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4395 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4396}