blob: f61f63470c7ab0486b8f4b31869001451ec59f8f [file] [log] [blame]
Chris Lattnere47e4402007-06-01 18:02:12 +00001//===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnere47e4402007-06-01 18:02:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
John McCall5d865c322010-08-31 07:33:07 +000015#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CGCall.h"
Devang Pateld3a6b0f2011-03-04 18:54:42 +000017#include "CGDebugInfo.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000018#include "CGObjCRuntime.h"
Alexey Bataev97720002014-11-11 04:05:39 +000019#include "CGOpenMPRuntime.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "CGRecordLayout.h"
21#include "CodeGenModule.h"
John McCallcbc038a2011-09-21 08:08:30 +000022#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000023#include "clang/AST/ASTContext.h"
Renato Golin230c5eb2014-05-19 18:15:42 +000024#include "clang/AST/Attr.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000025#include "clang/AST/DeclObjC.h"
Chandler Carruth85098242010-06-15 23:19:56 +000026#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "llvm/ADT/Hashing.h"
Alexey Bataevec474782014-10-09 08:45:04 +000028#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000029#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/LLVMContext.h"
32#include "llvm/IR/MDBuilder.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000033#include "llvm/Support/ConvertUTF.h"
Peter Collingbourne3eea6772015-05-11 21:39:14 +000034#include "llvm/Support/MathExtras.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000035
Chris Lattnere47e4402007-06-01 18:02:12 +000036using namespace clang;
37using namespace CodeGen;
38
Chris Lattnerd7f58862007-06-02 05:24:33 +000039//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000040// Miscellaneous Helper Methods
41//===--------------------------------------------------------------------===//
42
John McCallad7c5c12011-02-08 08:22:06 +000043llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
44 unsigned addressSpace =
45 cast<llvm::PointerType>(value->getType())->getAddressSpace();
46
Chris Lattner2192fe52011-07-18 04:24:23 +000047 llvm::PointerType *destType = Int8PtrTy;
John McCallad7c5c12011-02-08 08:22:06 +000048 if (addressSpace)
49 destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
50
51 if (value->getType() == destType) return value;
52 return Builder.CreateBitCast(value, destType);
53}
54
Chris Lattnere9a64532007-06-22 21:44:33 +000055/// CreateTempAlloca - This creates a alloca and inserts it into the entry
56/// block.
John McCall7f416cc2015-09-08 08:05:57 +000057Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
58 const Twine &Name) {
59 auto Alloca = CreateTempAlloca(Ty, Name);
60 Alloca->setAlignment(Align.getQuantity());
61 return Address(Alloca, Align);
62}
63
64/// CreateTempAlloca - This creates a alloca and inserts it into the entry
65/// block.
Chris Lattner2192fe52011-07-18 04:24:23 +000066llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
Chris Lattner0e62c1c2011-07-23 10:55:15 +000067 const Twine &Name) {
Chris Lattner47640222009-03-22 00:24:14 +000068 if (!Builder.isNamePreserving())
Craig Topper8a13c412014-05-21 05:09:00 +000069 return new llvm::AllocaInst(Ty, nullptr, "", AllocaInsertPt);
70 return new llvm::AllocaInst(Ty, nullptr, Name, AllocaInsertPt);
Chris Lattnere9a64532007-06-22 21:44:33 +000071}
Chris Lattner8394d792007-06-05 20:53:16 +000072
John McCall7f416cc2015-09-08 08:05:57 +000073/// CreateDefaultAlignTempAlloca - This creates an alloca with the
74/// default alignment of the corresponding LLVM type, which is *not*
75/// guaranteed to be related in any way to the expected alignment of
76/// an AST type that might have been lowered to Ty.
77Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
78 const Twine &Name) {
79 CharUnits Align =
80 CharUnits::fromQuantity(CGM.getDataLayout().getABITypeAlignment(Ty));
81 return CreateTempAlloca(Ty, Align, Name);
82}
83
84void CodeGenFunction::InitTempAlloca(Address Var, llvm::Value *Init) {
85 assert(isa<llvm::AllocaInst>(Var.getPointer()));
86 auto *Store = new llvm::StoreInst(Init, Var.getPointer());
87 Store->setAlignment(Var.getAlignment().getQuantity());
John McCall2e6567a2010-04-22 01:10:34 +000088 llvm::BasicBlock *Block = AllocaInsertPt->getParent();
89 Block->getInstList().insertAfter(&*AllocaInsertPt, Store);
90}
91
John McCall7f416cc2015-09-08 08:05:57 +000092Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
Daniel Dunbard0049182010-02-16 19:44:13 +000093 CharUnits Align = getContext().getTypeAlignInChars(Ty);
John McCall7f416cc2015-09-08 08:05:57 +000094 return CreateTempAlloca(ConvertType(Ty), Align, Name);
Daniel Dunbard0049182010-02-16 19:44:13 +000095}
96
John McCall7f416cc2015-09-08 08:05:57 +000097Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name) {
Daniel Dunbara7566f12010-02-09 02:48:28 +000098 // FIXME: Should we prefer the preferred type alignment here?
John McCall7f416cc2015-09-08 08:05:57 +000099 return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name);
100}
101
102Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
103 const Twine &Name) {
104 return CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name);
Daniel Dunbara7566f12010-02-09 02:48:28 +0000105}
106
Chris Lattner8394d792007-06-05 20:53:16 +0000107/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
108/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000109llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Bob Wilsonbf854f02014-02-17 19:21:09 +0000110 PGO.setCurrentStmt(E);
John McCall7a9aac22010-08-23 01:21:21 +0000111 if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
John McCalla1dee5302010-08-22 10:59:02 +0000112 llvm::Value *MemPtr = EmitScalarExpr(E);
John McCallad7c5c12011-02-08 08:22:06 +0000113 return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
Eli Friedman68396b12009-12-11 09:26:29 +0000114 }
John McCall7a9aac22010-08-23 01:21:21 +0000115
116 QualType BoolTy = getContext().BoolTy;
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000117 SourceLocation Loc = E->getExprLoc();
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000118 if (!E->getType()->isAnyComplexType())
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000119 return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
Chris Lattner8394d792007-06-05 20:53:16 +0000120
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000121 return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
122 Loc);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000123}
124
John McCalla2342eb2010-12-05 02:00:02 +0000125/// EmitIgnoredExpr - Emit code to compute the specified expression,
126/// ignoring the result.
127void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
128 if (E->isRValue())
129 return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
130
131 // Just emit it as an l-value and drop the result.
132 EmitLValue(E);
133}
134
John McCall7a626f62010-09-15 10:14:12 +0000135/// EmitAnyExpr - Emit code to compute the specified expression which
136/// can have any type. The result is returned as an RValue struct.
137/// If this is an aggregate expression, AggSlot indicates where the
Mike Stump4a3999f2009-09-09 13:00:44 +0000138/// result should be returned.
John McCall4e8ca4f2012-07-02 23:58:38 +0000139RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
140 AggValueSlot aggSlot,
141 bool ignoreResult) {
John McCall47fb9502013-03-07 21:37:08 +0000142 switch (getEvaluationKind(E->getType())) {
143 case TEK_Scalar:
John McCall4e8ca4f2012-07-02 23:58:38 +0000144 return RValue::get(EmitScalarExpr(E, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000145 case TEK_Complex:
John McCall4e8ca4f2012-07-02 23:58:38 +0000146 return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
John McCall47fb9502013-03-07 21:37:08 +0000147 case TEK_Aggregate:
148 if (!ignoreResult && aggSlot.isIgnored())
149 aggSlot = CreateAggTemp(E->getType(), "agg-temp");
150 EmitAggExpr(E, aggSlot);
151 return aggSlot.asRValue();
152 }
153 llvm_unreachable("bad evaluation kind");
Chris Lattner4647a212007-08-31 22:49:20 +0000154}
155
Mike Stump4a3999f2009-09-09 13:00:44 +0000156/// EmitAnyExprToTemp - Similary to EmitAnyExpr(), however, the result will
157/// always be accessible even if no aggregate location is provided.
John McCall7a626f62010-09-15 10:14:12 +0000158RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
159 AggValueSlot AggSlot = AggValueSlot::ignored();
Mike Stump4a3999f2009-09-09 13:00:44 +0000160
John McCall47fb9502013-03-07 21:37:08 +0000161 if (hasAggregateEvaluationKind(E->getType()))
John McCall7a626f62010-09-15 10:14:12 +0000162 AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
163 return EmitAnyExpr(E, AggSlot);
Daniel Dunbar41cf9de2008-09-09 01:06:48 +0000164}
165
John McCall21886962010-04-21 10:05:39 +0000166/// EmitAnyExprToMem - Evaluate an expression into a given memory
167/// location.
168void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
John McCall7f416cc2015-09-08 08:05:57 +0000169 Address Location,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000170 Qualifiers Quals,
171 bool IsInit) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000172 // FIXME: This function should take an LValue as an argument.
John McCall47fb9502013-03-07 21:37:08 +0000173 switch (getEvaluationKind(E->getType())) {
174 case TEK_Complex:
John McCall7f416cc2015-09-08 08:05:57 +0000175 EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
John McCall47fb9502013-03-07 21:37:08 +0000176 /*isInit*/ false);
177 return;
178
179 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000180 EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000181 AggValueSlot::IsDestructed_t(IsInit),
John McCalla8a39bc2011-08-26 05:38:08 +0000182 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000183 AggValueSlot::IsAliased_t(!IsInit)));
John McCall47fb9502013-03-07 21:37:08 +0000184 return;
185 }
186
187 case TEK_Scalar: {
John McCall21886962010-04-21 10:05:39 +0000188 RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000189 LValue LV = MakeAddrLValue(Location, E->getType());
John McCall55e1fbc2011-06-25 02:11:03 +0000190 EmitStoreThroughLValue(RV, LV);
John McCall47fb9502013-03-07 21:37:08 +0000191 return;
John McCall21886962010-04-21 10:05:39 +0000192 }
John McCall47fb9502013-03-07 21:37:08 +0000193 }
194 llvm_unreachable("bad evaluation kind");
John McCall21886962010-04-21 10:05:39 +0000195}
196
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000197static void
198pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
John McCall7f416cc2015-09-08 08:05:57 +0000199 const Expr *E, Address ReferenceTemporary) {
Rafael Espindolab9d75ca2012-10-27 00:43:14 +0000200 // Objective-C++ ARC:
201 // If we are binding a reference to a temporary that has ownership, we
202 // need to perform retain/release operations on the temporary.
Richard Smith736a9472013-06-12 20:42:33 +0000203 //
204 // FIXME: This should be looking at E, not M.
205 if (CGF.getLangOpts().ObjCAutoRefCount &&
206 M->getType()->isObjCLifetimeType()) {
207 QualType ObjCARCReferenceLifetimeType = M->getType();
208 switch (Qualifiers::ObjCLifetime Lifetime =
209 ObjCARCReferenceLifetimeType.getObjCLifetime()) {
210 case Qualifiers::OCL_None:
211 case Qualifiers::OCL_ExplicitNone:
212 // Carry on to normal cleanup handling.
213 break;
Sebastian Redl29526f02011-11-27 16:50:07 +0000214
Richard Smith736a9472013-06-12 20:42:33 +0000215 case Qualifiers::OCL_Autoreleasing:
216 // Nothing to do; cleaned up by an autorelease pool.
217 return;
218
219 case Qualifiers::OCL_Strong:
220 case Qualifiers::OCL_Weak:
221 switch (StorageDuration Duration = M->getStorageDuration()) {
222 case SD_Static:
223 // Note: we intentionally do not register a cleanup to release
224 // the object on program termination.
225 return;
226
227 case SD_Thread:
228 // FIXME: We should probably register a cleanup in this case.
229 return;
230
231 case SD_Automatic:
232 case SD_FullExpression:
Richard Smith736a9472013-06-12 20:42:33 +0000233 CodeGenFunction::Destroyer *Destroy;
234 CleanupKind CleanupKind;
235 if (Lifetime == Qualifiers::OCL_Strong) {
236 const ValueDecl *VD = M->getExtendingDecl();
237 bool Precise =
238 VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
239 CleanupKind = CGF.getARCCleanupKind();
240 Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
241 : &CodeGenFunction::destroyARCStrongImprecise;
242 } else {
243 // __weak objects always get EH cleanups; otherwise, exceptions
244 // could cause really nasty crashes instead of mere leaks.
245 CleanupKind = NormalAndEHCleanup;
246 Destroy = &CodeGenFunction::destroyARCWeak;
247 }
248 if (Duration == SD_FullExpression)
249 CGF.pushDestroy(CleanupKind, ReferenceTemporary,
250 ObjCARCReferenceLifetimeType, *Destroy,
251 CleanupKind & EHCleanup);
252 else
253 CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
254 ObjCARCReferenceLifetimeType,
255 *Destroy, CleanupKind & EHCleanup);
256 return;
257
258 case SD_Dynamic:
259 llvm_unreachable("temporary cannot have dynamic storage duration");
260 }
261 llvm_unreachable("unknown storage duration");
262 }
263 }
264
Craig Topper8a13c412014-05-21 05:09:00 +0000265 CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
Richard Smith736a9472013-06-12 20:42:33 +0000266 if (const RecordType *RT =
267 E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
268 // Get the destructor for the reference temporary.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000269 auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Richard Smith736a9472013-06-12 20:42:33 +0000270 if (!ClassDecl->hasTrivialDestructor())
271 ReferenceTemporaryDtor = ClassDecl->getDestructor();
272 }
273
274 if (!ReferenceTemporaryDtor)
275 return;
276
277 // Call the destructor for the temporary.
278 switch (M->getStorageDuration()) {
279 case SD_Static:
280 case SD_Thread: {
281 llvm::Constant *CleanupFn;
282 llvm::Constant *CleanupArg;
283 if (E->getType()->isArrayType()) {
284 CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
John McCall7f416cc2015-09-08 08:05:57 +0000285 ReferenceTemporary, E->getType(),
David Blaikieebe87e12013-08-27 23:57:18 +0000286 CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
287 dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
Richard Smith736a9472013-06-12 20:42:33 +0000288 CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
289 } else {
Rafael Espindola1ac0ec82014-09-11 15:42:06 +0000290 CleanupFn = CGF.CGM.getAddrOfCXXStructor(ReferenceTemporaryDtor,
291 StructorType::Complete);
John McCall7f416cc2015-09-08 08:05:57 +0000292 CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
Richard Smith736a9472013-06-12 20:42:33 +0000293 }
294 CGF.CGM.getCXXABI().registerGlobalDtor(
295 CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
296 break;
297 }
298
299 case SD_FullExpression:
300 CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
301 CodeGenFunction::destroyCXXObject,
302 CGF.getLangOpts().Exceptions);
303 break;
304
305 case SD_Automatic:
306 CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
307 ReferenceTemporary, E->getType(),
308 CodeGenFunction::destroyCXXObject,
309 CGF.getLangOpts().Exceptions);
310 break;
311
312 case SD_Dynamic:
313 llvm_unreachable("temporary cannot have dynamic storage duration");
314 }
315}
316
John McCall7f416cc2015-09-08 08:05:57 +0000317static Address
Richard Smith736a9472013-06-12 20:42:33 +0000318createReferenceTemporary(CodeGenFunction &CGF,
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000319 const MaterializeTemporaryExpr *M, const Expr *Inner) {
Richard Smith736a9472013-06-12 20:42:33 +0000320 switch (M->getStorageDuration()) {
321 case SD_FullExpression:
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000322 case SD_Automatic: {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000323 // If we have a constant temporary array or record try to promote it into a
324 // constant global under the same rules a normal constant would've been
325 // promoted. This is easier on the optimizer and generally emits fewer
326 // instructions.
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000327 QualType Ty = Inner->getType();
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000328 if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000329 (Ty->isArrayType() || Ty->isRecordType()) &&
330 CGF.CGM.isTypeConstant(Ty, true))
331 if (llvm::Constant *Init = CGF.CGM.EmitConstantExpr(Inner, Ty, &CGF)) {
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000332 auto *GV = new llvm::GlobalVariable(
333 CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
334 llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp");
John McCall7f416cc2015-09-08 08:05:57 +0000335 CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
336 GV->setAlignment(alignment.getQuantity());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000337 // FIXME: Should we put the new global into a COMDAT?
John McCall7f416cc2015-09-08 08:05:57 +0000338 return Address(GV, alignment);
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000339 }
Benjamin Kramerf3e67de2015-04-09 22:50:07 +0000340 return CGF.CreateMemTemp(Ty, "ref.tmp");
341 }
Richard Smith736a9472013-06-12 20:42:33 +0000342 case SD_Thread:
343 case SD_Static:
Hans Wennborgf9d865b2015-03-17 16:38:58 +0000344 return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
Richard Smith736a9472013-06-12 20:42:33 +0000345
346 case SD_Dynamic:
347 llvm_unreachable("temporary can't have dynamic storage duration");
348 }
349 llvm_unreachable("unknown storage duration");
350}
351
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000352LValue CodeGenFunction::
353EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000354 const Expr *E = M->GetTemporaryExpr();
Richard Smith7c5d4dc2013-06-11 02:41:00 +0000355
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000356 // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
357 // as that will cause the lifetime adjustment to be lost for ARC
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000358 if (getLangOpts().ObjCAutoRefCount &&
Richard Smith736a9472013-06-12 20:42:33 +0000359 M->getType()->isObjCLifetimeType() &&
360 M->getType().getObjCLifetime() != Qualifiers::OCL_None &&
361 M->getType().getObjCLifetime() != 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());
Richard Smitha509f2f2013-06-14 03:07:01 +0000368 // We should not have emitted the initializer for this temporary as a
369 // constant.
370 assert(!Var->hasInitializer());
371 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
372 }
John McCall7f416cc2015-09-08 08:05:57 +0000373 LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
374 AlignmentSource::Decl);
Richard Smitha509f2f2013-06-14 03:07:01 +0000375
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000376 switch (getEvaluationKind(E->getType())) {
377 default: llvm_unreachable("expected scalar or aggregate expression");
378 case TEK_Scalar:
379 EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
380 break;
381 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000382 EmitAggExpr(E, AggValueSlot::forAddr(Object,
Saleem Abdulrasoolb31b94a82014-10-24 20:23:43 +0000383 E->getType().getQualifiers(),
384 AggValueSlot::IsDestructed,
385 AggValueSlot::DoesNotNeedGCBarriers,
386 AggValueSlot::IsNotAliased));
387 break;
388 }
389 }
Richard Smith736a9472013-06-12 20:42:33 +0000390
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000391 pushTemporaryCleanup(*this, M, E, Object);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000392 return RefTempDst;
Jordan Roseb1312a52013-04-11 00:58:58 +0000393 }
394
Richard Smithf3fabd22013-06-03 00:17:11 +0000395 SmallVector<const Expr *, 2> CommaLHSs;
Jordan Roseb1312a52013-04-11 00:58:58 +0000396 SmallVector<SubobjectAdjustment, 2> Adjustments;
Richard Smithf3fabd22013-06-03 00:17:11 +0000397 E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
398
Saleem Abdulrasool8925dc02014-10-24 19:54:32 +0000399 for (const auto &Ignored : CommaLHSs)
400 EmitIgnoredExpr(Ignored);
Richard Smithf3fabd22013-06-03 00:17:11 +0000401
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000402 if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
Richard Smith736a9472013-06-12 20:42:33 +0000403 if (opaque->getType()->isRecordType()) {
404 assert(Adjustments.empty());
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000405 return EmitOpaqueValueLValue(opaque);
Jordan Roseb1312a52013-04-11 00:58:58 +0000406 }
407 }
408
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000409 // Create and initialize the reference temporary.
John McCall7f416cc2015-09-08 08:05:57 +0000410 Address Object = createReferenceTemporary(*this, M, E);
411 if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
412 Object = Address(llvm::ConstantExpr::getBitCast(
413 Var, ConvertTypeForMem(E->getType())->getPointerTo()),
414 Object.getAlignment());
Benjamin Kramerf8b86962015-03-07 13:37:13 +0000415 // If the temporary is a global and has a constant initializer or is a
416 // constant temporary that we promoted to a global, we may have already
417 // initialized it.
Richard Smitha509f2f2013-06-14 03:07:01 +0000418 if (!Var->hasInitializer()) {
419 Var->setInitializer(CGM.EmitNullConstant(E->getType()));
420 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
421 }
422 } else {
423 EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
424 }
Nick Lewycky5d1159e2014-10-10 04:05:00 +0000425 pushTemporaryCleanup(*this, M, E, Object);
Jordan Roseb1312a52013-04-11 00:58:58 +0000426
Richard Smith736a9472013-06-12 20:42:33 +0000427 // Perform derived-to-base casts and/or field accesses, to get from the
428 // temporary object we created (and, potentially, for which we extended
429 // the lifetime) to the subobject we're binding the reference to.
430 for (unsigned I = Adjustments.size(); I != 0; --I) {
431 SubobjectAdjustment &Adjustment = Adjustments[I-1];
432 switch (Adjustment.Kind) {
433 case SubobjectAdjustment::DerivedToBaseAdjustment:
434 Object =
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000435 GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
436 Adjustment.DerivedToBase.BasePath->path_begin(),
437 Adjustment.DerivedToBase.BasePath->path_end(),
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000438 /*NullCheckValue=*/ false, E->getExprLoc());
Richard Smith736a9472013-06-12 20:42:33 +0000439 break;
Richard Smithf3fabd22013-06-03 00:17:11 +0000440
Richard Smith736a9472013-06-12 20:42:33 +0000441 case SubobjectAdjustment::FieldAdjustment: {
John McCall7f416cc2015-09-08 08:05:57 +0000442 LValue LV = MakeAddrLValue(Object, E->getType(),
443 AlignmentSource::Decl);
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000444 LV = EmitLValueForField(LV, Adjustment.Field);
Richard Smith736a9472013-06-12 20:42:33 +0000445 assert(LV.isSimple() &&
446 "materialized temporary field is not a simple lvalue");
447 Object = LV.getAddress();
448 break;
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000449 }
450
Richard Smith736a9472013-06-12 20:42:33 +0000451 case SubobjectAdjustment::MemberPointerAdjustment: {
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000452 llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
John McCall7f416cc2015-09-08 08:05:57 +0000453 Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
454 Adjustment.Ptr.MPT);
Richard Smith736a9472013-06-12 20:42:33 +0000455 break;
456 }
457 }
Anders Carlsson7d4c0832009-05-20 00:36:58 +0000458 }
Eli Friedmanc21cb442009-05-20 02:31:19 +0000459
John McCall7f416cc2015-09-08 08:05:57 +0000460 return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000461}
462
463RValue
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000464CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
465 // Emit the expression as an lvalue.
466 LValue LV = EmitLValue(E);
467 assert(LV.isSimple());
John McCall7f416cc2015-09-08 08:05:57 +0000468 llvm::Value *Value = LV.getPointer();
Richard Smith736a9472013-06-12 20:42:33 +0000469
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000470 if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000471 // C++11 [dcl.ref]p5 (as amended by core issue 453):
472 // If a glvalue to which a reference is directly bound designates neither
473 // an existing object or function of an appropriate type nor a region of
474 // storage of suitable size and alignment to contain an object of the
475 // reference's type, the behavior is undefined.
476 QualType Ty = E->getType();
Richard Smithe30752c2012-10-09 19:52:38 +0000477 EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
Richard Smith69d0d262012-08-24 00:54:33 +0000478 }
John McCall8680f872010-07-21 06:29:51 +0000479
Anders Carlsson2969c8c62010-06-27 16:56:04 +0000480 return RValue::get(Value);
Anders Carlsson6f5a0152009-05-20 00:24:07 +0000481}
482
483
Mike Stump4a3999f2009-09-09 13:00:44 +0000484/// getAccessedFieldNo - Given an encoded value and a result number, return the
485/// input field number being accessed.
486unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
Dan Gohman75d69da2008-05-22 00:50:06 +0000487 const llvm::Constant *Elts) {
Chris Lattner595ba3a2012-01-30 06:20:36 +0000488 return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
489 ->getZExtValue();
Dan Gohman75d69da2008-05-22 00:50:06 +0000490}
491
Richard Smith4d3110a2012-10-25 02:14:12 +0000492/// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
493static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
494 llvm::Value *High) {
495 llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
496 llvm::Value *K47 = Builder.getInt64(47);
497 llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
498 llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
499 llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
500 llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
501 return Builder.CreateMul(B1, KMul);
502}
503
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000504bool CodeGenFunction::sanitizePerformTypeCheck() const {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000505 return SanOpts.has(SanitizerKind::Null) |
506 SanOpts.has(SanitizerKind::Alignment) |
507 SanOpts.has(SanitizerKind::ObjectSize) |
508 SanOpts.has(SanitizerKind::Vptr);
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000509}
510
Richard Smithe30752c2012-10-09 19:52:38 +0000511void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +0000512 llvm::Value *Ptr, QualType Ty,
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000513 CharUnits Alignment, bool SkipNullCheck) {
Alexey Samsonovac4afe42014-07-07 23:59:57 +0000514 if (!sanitizePerformTypeCheck())
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000515 return;
516
Richard Smith2d8b2942012-11-01 07:22:08 +0000517 // Don't check pointers outside the default address space. The null check
518 // isn't correct, the object-size check isn't supported by LLVM, and we can't
519 // communicate the addresses to the runtime handler for the vptr check.
John McCall7f416cc2015-09-08 08:05:57 +0000520 if (Ptr->getType()->getPointerAddressSpace())
Richard Smith2d8b2942012-11-01 07:22:08 +0000521 return;
522
Alexey Samsonov24cad992014-07-17 18:46:27 +0000523 SanitizerScope SanScope(this);
524
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000525 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
Craig Topper8a13c412014-05-21 05:09:00 +0000526 llvm::BasicBlock *Done = nullptr;
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000527
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000528 bool AllowNullPointers = TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
529 TCK == TCK_UpcastToVirtualBase;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000530 if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
531 !SkipNullCheck) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000532 // The glvalue must not be an empty glvalue.
John McCall7f416cc2015-09-08 08:05:57 +0000533 llvm::Value *IsNonNull = Builder.CreateIsNotNull(Ptr);
Richard Smith2c5868c2013-02-13 21:18:23 +0000534
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000535 if (AllowNullPointers) {
536 // When performing pointer casts, it's OK if the value is null.
Richard Smith2c5868c2013-02-13 21:18:23 +0000537 // Skip the remaining checks in that case.
538 Done = createBasicBlock("null");
539 llvm::BasicBlock *Rest = createBasicBlock("not.null");
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000540 Builder.CreateCondBr(IsNonNull, Rest, Done);
Richard Smith2c5868c2013-02-13 21:18:23 +0000541 EmitBlock(Rest);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +0000542 } else {
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000543 Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
Richard Smith2c5868c2013-02-13 21:18:23 +0000544 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000545 }
Chris Lattnerbc3be652010-04-10 18:34:14 +0000546
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000547 if (SanOpts.has(SanitizerKind::ObjectSize) && !Ty->isIncompleteType()) {
Richard Smith69d0d262012-08-24 00:54:33 +0000548 uint64_t Size = getContext().getTypeSizeInChars(Ty).getQuantity();
Richard Smith69d0d262012-08-24 00:54:33 +0000549
Richard Smith69d0d262012-08-24 00:54:33 +0000550 // The glvalue must refer to a large enough storage region.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000551 // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
Richard Smith69d0d262012-08-24 00:54:33 +0000552 // to check this.
Matt Arsenault2f152632013-10-07 19:00:18 +0000553 // FIXME: Get object address space
554 llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
555 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
Richard Smith69d0d262012-08-24 00:54:33 +0000556 llvm::Value *Min = Builder.getFalse();
John McCall7f416cc2015-09-08 08:05:57 +0000557 llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
Richard Smith69d0d262012-08-24 00:54:33 +0000558 llvm::Value *LargeEnough =
David Blaikie43f9bb72015-05-18 22:14:03 +0000559 Builder.CreateICmpUGE(Builder.CreateCall(F, {CastAddr, Min}),
Richard Smith69d0d262012-08-24 00:54:33 +0000560 llvm::ConstantInt::get(IntPtrTy, Size));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000561 Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
Richard Smithe30752c2012-10-09 19:52:38 +0000562 }
Richard Smith69d0d262012-08-24 00:54:33 +0000563
Richard Smithb1b0ab42012-11-05 22:21:05 +0000564 uint64_t AlignVal = 0;
565
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000566 if (SanOpts.has(SanitizerKind::Alignment)) {
Richard Smithb1b0ab42012-11-05 22:21:05 +0000567 AlignVal = Alignment.getQuantity();
568 if (!Ty->isIncompleteType() && !AlignVal)
569 AlignVal = getContext().getTypeAlignInChars(Ty).getQuantity();
570
Richard Smith69d0d262012-08-24 00:54:33 +0000571 // The glvalue must be suitably aligned.
Richard Smithb1b0ab42012-11-05 22:21:05 +0000572 if (AlignVal) {
573 llvm::Value *Align =
John McCall7f416cc2015-09-08 08:05:57 +0000574 Builder.CreateAnd(Builder.CreatePtrToInt(Ptr, IntPtrTy),
Richard Smithb1b0ab42012-11-05 22:21:05 +0000575 llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
576 llvm::Value *Aligned =
577 Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000578 Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
Richard Smithb1b0ab42012-11-05 22:21:05 +0000579 }
Richard Smith69d0d262012-08-24 00:54:33 +0000580 }
581
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000582 if (Checks.size() > 0) {
Richard Smithe30752c2012-10-09 19:52:38 +0000583 llvm::Constant *StaticData[] = {
584 EmitCheckSourceLocation(Loc),
585 EmitCheckTypeDescriptor(Ty),
586 llvm::ConstantInt::get(SizeTy, AlignVal),
587 llvm::ConstantInt::get(Int8Ty, TCK)
588 };
John McCall7f416cc2015-09-08 08:05:57 +0000589 EmitCheck(Checks, "type_mismatch", StaticData, Ptr);
Richard Smithe30752c2012-10-09 19:52:38 +0000590 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000591
Richard Smithb1b0ab42012-11-05 22:21:05 +0000592 // If possible, check that the vptr indicates that there is a subobject of
593 // type Ty at offset zero within this object.
Richard Smithbe024a82012-12-18 00:22:45 +0000594 //
595 // C++11 [basic.life]p5,6:
596 // [For storage which does not refer to an object within its lifetime]
597 // The program has undefined behavior if:
598 // -- the [pointer or glvalue] is used to access a non-static data member
Richard Smith8b731ea2012-12-18 03:04:38 +0000599 // or call a non-static member function
Richard Smith4d3110a2012-10-25 02:14:12 +0000600 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000601 if (SanOpts.has(SanitizerKind::Vptr) &&
Richard Smith2c5868c2013-02-13 21:18:23 +0000602 (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000603 TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
604 TCK == TCK_UpcastToVirtualBase) &&
Richard Smith4d3110a2012-10-25 02:14:12 +0000605 RD && RD->hasDefinition() && RD->isDynamicClass()) {
Richard Smith4d3110a2012-10-25 02:14:12 +0000606 // Compute a hash of the mangled name of the type.
607 //
608 // FIXME: This is not guaranteed to be deterministic! Move to a
609 // fingerprinting mechanism once LLVM provides one. For the time
610 // being the implementation happens to be deterministic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000611 SmallString<64> MangledName;
Richard Smith4d3110a2012-10-25 02:14:12 +0000612 llvm::raw_svector_ostream Out(MangledName);
613 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
614 Out);
Richard Smith4d3110a2012-10-25 02:14:12 +0000615
Alexey Samsonov84856012014-07-10 22:34:19 +0000616 // Blacklist based on the mangled type.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000617 if (!CGM.getContext().getSanitizerBlacklist().isBlacklistedType(
618 Out.str())) {
Alexey Samsonov84856012014-07-10 22:34:19 +0000619 llvm::hash_code TypeHash = hash_value(Out.str());
Richard Smith4d3110a2012-10-25 02:14:12 +0000620
Alexey Samsonov84856012014-07-10 22:34:19 +0000621 // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
622 llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
623 llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
John McCall7f416cc2015-09-08 08:05:57 +0000624 Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000625 llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
626 llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
Richard Smith4d3110a2012-10-25 02:14:12 +0000627
Alexey Samsonov84856012014-07-10 22:34:19 +0000628 llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
629 Hash = Builder.CreateTrunc(Hash, IntPtrTy);
Richard Smith4d3110a2012-10-25 02:14:12 +0000630
Alexey Samsonov84856012014-07-10 22:34:19 +0000631 // Look the hash up in our cache.
632 const int CacheSize = 128;
633 llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
634 llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
635 "__ubsan_vptr_type_cache");
636 llvm::Value *Slot = Builder.CreateAnd(Hash,
637 llvm::ConstantInt::get(IntPtrTy,
638 CacheSize-1));
639 llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
640 llvm::Value *CacheVal =
John McCall7f416cc2015-09-08 08:05:57 +0000641 Builder.CreateAlignedLoad(Builder.CreateInBoundsGEP(Cache, Indices),
642 getPointerAlign());
Alexey Samsonov84856012014-07-10 22:34:19 +0000643
644 // If the hash isn't in the cache, call a runtime handler to perform the
645 // hard work of checking whether the vptr is for an object of the right
646 // type. This will either fill in the cache and return, or produce a
647 // diagnostic.
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000648 llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
Alexey Samsonov84856012014-07-10 22:34:19 +0000649 llvm::Constant *StaticData[] = {
650 EmitCheckSourceLocation(Loc),
651 EmitCheckTypeDescriptor(Ty),
652 CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
653 llvm::ConstantInt::get(Int8Ty, TCK)
654 };
John McCall7f416cc2015-09-08 08:05:57 +0000655 llvm::Value *DynamicData[] = { Ptr, Hash };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000656 EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
657 "dynamic_type_cache_miss", StaticData, DynamicData);
Alexey Samsonov84856012014-07-10 22:34:19 +0000658 }
Richard Smith4d3110a2012-10-25 02:14:12 +0000659 }
Richard Smith2c5868c2013-02-13 21:18:23 +0000660
661 if (Done) {
662 Builder.CreateBr(Done);
663 EmitBlock(Done);
664 }
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000665}
Chris Lattner4647a212007-08-31 22:49:20 +0000666
Richard Smith539e4a72013-02-23 02:53:19 +0000667/// Determine whether this expression refers to a flexible array member in a
668/// struct. We disable array bounds checks for such members.
669static bool isFlexibleArrayMemberExpr(const Expr *E) {
670 // For compatibility with existing code, we treat arrays of length 0 or
671 // 1 as flexible array members.
672 const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000673 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000674 if (CAT->getSize().ugt(1))
675 return false;
676 } else if (!isa<IncompleteArrayType>(AT))
677 return false;
678
679 E = E->IgnoreParens();
680
681 // A flexible array member must be the last member in the class.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000682 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000683 // FIXME: If the base type of the member expr is not FD->getParent(),
684 // this should not be treated as a flexible array member access.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000685 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
Richard Smith539e4a72013-02-23 02:53:19 +0000686 RecordDecl::field_iterator FI(
687 DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
688 return ++FI == FD->getParent()->field_end();
689 }
690 }
691
692 return false;
693}
694
695/// If Base is known to point to the start of an array, return the length of
696/// that array. Return 0 if the length cannot be determined.
Benjamin Kramer36f89cc2013-03-09 15:15:22 +0000697static llvm::Value *getArrayIndexingBound(
698 CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
Richard Smith539e4a72013-02-23 02:53:19 +0000699 // For the vector indexing extension, the bound is the number of elements.
700 if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
701 IndexedType = Base->getType();
702 return CGF.Builder.getInt32(VT->getNumElements());
703 }
704
705 Base = Base->IgnoreParens();
706
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000707 if (const auto *CE = dyn_cast<CastExpr>(Base)) {
Richard Smith539e4a72013-02-23 02:53:19 +0000708 if (CE->getCastKind() == CK_ArrayToPointerDecay &&
709 !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
710 IndexedType = CE->getSubExpr()->getType();
711 const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000712 if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000713 return CGF.Builder.getInt(CAT->getSize());
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000714 else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
Richard Smith539e4a72013-02-23 02:53:19 +0000715 return CGF.getVLASize(VAT).first;
716 }
717 }
718
Craig Topper8a13c412014-05-21 05:09:00 +0000719 return nullptr;
Richard Smith539e4a72013-02-23 02:53:19 +0000720}
721
722void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
723 llvm::Value *Index, QualType IndexType,
724 bool Accessed) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000725 assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
Richard Smith6b53e222013-10-22 22:51:04 +0000726 "should not be called unless adding bounds checks");
Alexey Samsonov24cad992014-07-17 18:46:27 +0000727 SanitizerScope SanScope(this);
Richard Smith2847b222013-02-24 01:56:24 +0000728
Richard Smith539e4a72013-02-23 02:53:19 +0000729 QualType IndexedType;
730 llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
731 if (!Bound)
732 return;
733
734 bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
735 llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
736 llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
737
738 llvm::Constant *StaticData[] = {
739 EmitCheckSourceLocation(E->getExprLoc()),
740 EmitCheckTypeDescriptor(IndexedType),
741 EmitCheckTypeDescriptor(IndexType)
742 };
743 llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
744 : Builder.CreateICmpULE(IndexVal, BoundVal);
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000745 EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds), "out_of_bounds",
746 StaticData, Index);
Richard Smith539e4a72013-02-23 02:53:19 +0000747}
748
Chris Lattner116ce8f2010-01-09 21:40:03 +0000749
Chris Lattner116ce8f2010-01-09 21:40:03 +0000750CodeGenFunction::ComplexPairTy CodeGenFunction::
751EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
752 bool isInc, bool isPre) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000753 ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +0000754
Chris Lattner116ce8f2010-01-09 21:40:03 +0000755 llvm::Value *NextVal;
756 if (isa<llvm::IntegerType>(InVal.first->getType())) {
757 uint64_t AmountVal = isInc ? 1 : -1;
758 NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
Craig Topper99e79272013-07-26 05:59:26 +0000759
Chris Lattner116ce8f2010-01-09 21:40:03 +0000760 // Add the inc/dec to the real part.
761 NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
762 } else {
763 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
764 llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
765 if (!isInc)
766 FVal.changeSign();
767 NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
Craig Topper99e79272013-07-26 05:59:26 +0000768
Chris Lattner116ce8f2010-01-09 21:40:03 +0000769 // Add the inc/dec to the real part.
770 NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
771 }
Craig Topper99e79272013-07-26 05:59:26 +0000772
Chris Lattner116ce8f2010-01-09 21:40:03 +0000773 ComplexPairTy IncVal(NextVal, InVal.second);
Craig Topper99e79272013-07-26 05:59:26 +0000774
Chris Lattner116ce8f2010-01-09 21:40:03 +0000775 // Store the updated result through the lvalue.
John McCall47fb9502013-03-07 21:37:08 +0000776 EmitStoreOfComplex(IncVal, LV, /*init*/ false);
Craig Topper99e79272013-07-26 05:59:26 +0000777
Chris Lattner116ce8f2010-01-09 21:40:03 +0000778 // If this is a postinc, return the value read from memory, otherwise use the
779 // updated value.
780 return isPre ? IncVal : InVal;
781}
782
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000783void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
784 CodeGenFunction *CGF) {
785 // Bind VLAs in the cast type.
786 if (CGF && E->getType()->isVariablyModifiedType())
787 CGF->EmitVariablyModifiedType(E->getType());
788
789 if (CGDebugInfo *DI = getModuleDebugInfo())
790 DI->EmitExplicitCastType(E->getType());
791}
792
Chris Lattnera45c5af2007-06-02 19:47:04 +0000793//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000794// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000795//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000796
John McCall7f416cc2015-09-08 08:05:57 +0000797/// EmitPointerWithAlignment - Given an expression of pointer type, try to
798/// derive a more accurate bound on the alignment of the pointer.
799Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
800 AlignmentSource *Source) {
801 // We allow this with ObjC object pointers because of fragile ABIs.
802 assert(E->getType()->isPointerType() ||
803 E->getType()->isObjCObjectPointerType());
804 E = E->IgnoreParens();
805
806 // Casts:
807 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000808 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
809 CGM.EmitExplicitCastExprType(ECE, this);
John McCall7f416cc2015-09-08 08:05:57 +0000810
811 switch (CE->getCastKind()) {
812 // Non-converting casts (but not C's implicit conversion from void*).
813 case CK_BitCast:
814 case CK_NoOp:
815 if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
816 if (PtrTy->getPointeeType()->isVoidType())
817 break;
818
819 AlignmentSource InnerSource;
820 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), &InnerSource);
821 if (Source) *Source = InnerSource;
822
823 // If this is an explicit bitcast, and the source l-value is
824 // opaque, honor the alignment of the casted-to type.
825 if (isa<ExplicitCastExpr>(CE) &&
John McCall7f416cc2015-09-08 08:05:57 +0000826 InnerSource != AlignmentSource::Decl) {
827 Addr = Address(Addr.getPointer(),
828 getNaturalPointeeTypeAlignment(E->getType(), Source));
829 }
830
Peter Collingbourneee381ff2015-09-09 00:01:31 +0000831 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
832 if (auto PT = E->getType()->getAs<PointerType>())
833 EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
834 /*MayBeNull=*/true,
835 CodeGenFunction::CFITCK_UnrelatedCast,
836 CE->getLocStart());
837 }
838
John McCall7f416cc2015-09-08 08:05:57 +0000839 return Builder.CreateBitCast(Addr, ConvertType(E->getType()));
840 }
841 break;
842
843 // Array-to-pointer decay.
844 case CK_ArrayToPointerDecay:
845 return EmitArrayToPointerDecay(CE->getSubExpr(), Source);
846
847 // Derived-to-base conversions.
848 case CK_UncheckedDerivedToBase:
849 case CK_DerivedToBase: {
850 Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), Source);
851 auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
852 return GetAddressOfBaseClass(Addr, Derived,
853 CE->path_begin(), CE->path_end(),
854 ShouldNullCheckClassCastValue(CE),
855 CE->getExprLoc());
856 }
857
858 // TODO: Is there any reason to treat base-to-derived conversions
859 // specially?
860 default:
861 break;
862 }
863 }
864
865 // Unary &.
866 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
867 if (UO->getOpcode() == UO_AddrOf) {
868 LValue LV = EmitLValue(UO->getSubExpr());
869 if (Source) *Source = LV.getAlignmentSource();
870 return LV.getAddress();
871 }
872 }
873
874 // TODO: conditional operators, comma.
875
876 // Otherwise, use the alignment of the type.
877 CharUnits Align = getNaturalPointeeTypeAlignment(E->getType(), Source);
878 return Address(EmitScalarExpr(E), Align);
879}
880
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000881RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000882 if (Ty->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +0000883 return RValue::get(nullptr);
John McCall47fb9502013-03-07 21:37:08 +0000884
885 switch (getEvaluationKind(Ty)) {
886 case TEK_Complex: {
887 llvm::Type *EltTy =
888 ConvertType(Ty->castAs<ComplexType>()->getElementType());
Owen Anderson7ec07a52009-07-30 23:11:26 +0000889 llvm::Value *U = llvm::UndefValue::get(EltTy);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000890 return RValue::getComplex(std::make_pair(U, U));
Chris Lattnerab5e0af2009-10-28 17:39:19 +0000891 }
Craig Topper99e79272013-07-26 05:59:26 +0000892
Chris Lattner65526f02010-08-23 05:26:13 +0000893 // If this is a use of an undefined aggregate type, the aggregate must have an
894 // identifiable address. Just because the contents of the value are undefined
895 // doesn't mean that the address can't be taken and compared.
John McCall47fb9502013-03-07 21:37:08 +0000896 case TEK_Aggregate: {
John McCall7f416cc2015-09-08 08:05:57 +0000897 Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
Chris Lattner65526f02010-08-23 05:26:13 +0000898 return RValue::getAggregate(DestPtr);
Daniel Dunbar8429dbc2009-01-09 20:09:28 +0000899 }
John McCall47fb9502013-03-07 21:37:08 +0000900
901 case TEK_Scalar:
902 return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
903 }
904 llvm_unreachable("bad evaluation kind");
Daniel Dunbarbb197e42009-01-09 16:50:52 +0000905}
906
Daniel Dunbarc79407f2009-02-05 07:09:07 +0000907RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
908 const char *Name) {
909 ErrorUnsupported(E, Name);
910 return GetUndefRValue(E->getType());
911}
912
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000913LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
914 const char *Name) {
915 ErrorUnsupported(E, Name);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000916 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
John McCall7f416cc2015-09-08 08:05:57 +0000917 return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
918 E->getType());
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000919}
920
Richard Smith4d1458e2012-09-08 02:08:36 +0000921LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
Richard Smith539e4a72013-02-23 02:53:19 +0000922 LValue LV;
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000923 if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
Richard Smith539e4a72013-02-23 02:53:19 +0000924 LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
925 else
926 LV = EmitLValue(E);
Daniel Dunbardc406b82010-04-05 21:36:35 +0000927 if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple())
John McCall7f416cc2015-09-08 08:05:57 +0000928 EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(),
Richard Smithe30752c2012-10-09 19:52:38 +0000929 E->getType(), LV.getAlignment());
Mike Stump3f6f9fe2009-12-16 02:57:00 +0000930 return LV;
931}
932
Chris Lattner8394d792007-06-05 20:53:16 +0000933/// EmitLValue - Emit code to compute a designator that specifies the location
934/// of the expression.
935///
Mike Stump4a3999f2009-09-09 13:00:44 +0000936/// This can return one of two things: a simple address or a bitfield reference.
937/// In either case, the LLVM Value* in the LValue structure is guaranteed to be
938/// an LLVM pointer type.
Chris Lattner8394d792007-06-05 20:53:16 +0000939///
Mike Stump4a3999f2009-09-09 13:00:44 +0000940/// If this returns a bitfield reference, nothing about the pointee type of the
941/// LLVM value is known: For example, it may not be a pointer to an integer.
Chris Lattner8394d792007-06-05 20:53:16 +0000942///
Mike Stump4a3999f2009-09-09 13:00:44 +0000943/// If this returns a normal address, and if the lvalue's C type is fixed size,
944/// this method guarantees that the returned pointer type will point to an LLVM
945/// type of the same size of the lvalue's type. If the lvalue has a variable
946/// length type, this is not possible.
Chris Lattner8394d792007-06-05 20:53:16 +0000947///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000948LValue CodeGenFunction::EmitLValue(const Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +0000949 ApplyDebugLocation DL(*this, E);
Chris Lattnerd7f58862007-06-02 05:24:33 +0000950 switch (E->getStmtClass()) {
Daniel Dunbarf2e69882008-08-25 20:45:57 +0000951 default: return EmitUnsupportedLValue(E, "l-value expression");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000952
John McCallc109a252011-11-07 03:59:57 +0000953 case Expr::ObjCPropertyRefExprClass:
954 llvm_unreachable("cannot emit a property reference directly");
955
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +0000956 case Expr::ObjCSelectorExprClass:
Nico Webercf4ff5862012-10-11 10:13:44 +0000957 return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000958 case Expr::ObjCIsaExprClass:
959 return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000960 case Expr::BinaryOperatorClass:
Daniel Dunbar8cde00a2008-09-04 03:20:13 +0000961 return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +0000962 case Expr::CompoundAssignOperatorClass: {
963 QualType Ty = E->getType();
964 if (const AtomicType *AT = Ty->getAs<AtomicType>())
965 Ty = AT->getValueType();
966 if (!Ty->isAnyComplexType())
John McCalla2342eb2010-12-05 02:00:02 +0000967 return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
968 return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
David Majnemerce27e422015-02-14 01:48:17 +0000969 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000970 case Expr::CallExprClass:
Anders Carlssonc82555f2009-09-01 21:18:52 +0000971 case Expr::CXXMemberCallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000972 case Expr::CXXOperatorCallExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +0000973 case Expr::UserDefinedLiteralClass:
Douglas Gregor993603d2008-11-14 16:09:21 +0000974 return EmitCallExprLValue(cast<CallExpr>(E));
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +0000975 case Expr::VAArgExprClass:
976 return EmitVAArgExprLValue(cast<VAArgExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +0000977 case Expr::DeclRefExprClass:
Douglas Gregorc7acfdf2009-01-06 05:10:23 +0000978 return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Eric Christopherd98e4242011-09-08 17:15:04 +0000979 case Expr::ParenExprClass:
980 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Peter Collingbourne91147592011-04-15 00:35:48 +0000981 case Expr::GenericSelectionExprClass:
982 return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
Chris Lattner6307f192008-08-10 01:53:14 +0000983 case Expr::PredefinedExprClass:
984 return EmitPredefinedLValue(cast<PredefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +0000985 case Expr::StringLiteralClass:
986 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +0000987 case Expr::ObjCEncodeExprClass:
988 return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
John McCallfe96e0b2011-11-06 09:01:30 +0000989 case Expr::PseudoObjectExprClass:
990 return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +0000991 case Expr::InitListExprClass:
Richard Smithbb653bd2012-05-14 21:57:21 +0000992 return EmitInitListLValue(cast<InitListExpr>(E));
Anders Carlsson3be22e22009-05-30 23:23:33 +0000993 case Expr::CXXTemporaryObjectExprClass:
994 case Expr::CXXConstructExprClass:
Anders Carlssonfd2af0c2009-05-30 23:30:54 +0000995 return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
996 case Expr::CXXBindTemporaryExprClass:
997 return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
Nico Webercf4ff5862012-10-11 10:13:44 +0000998 case Expr::CXXUuidofExprClass:
999 return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
Eli Friedman5bc17122012-02-08 05:34:55 +00001000 case Expr::LambdaExprClass:
1001 return EmitLambdaLValue(cast<LambdaExpr>(E));
John McCall08ef4662011-11-10 08:15:53 +00001002
1003 case Expr::ExprWithCleanupsClass: {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001004 const auto *cleanups = cast<ExprWithCleanups>(E);
John McCall08ef4662011-11-10 08:15:53 +00001005 enterFullExpression(cleanups);
1006 RunCleanupsScope Scope(*this);
1007 return EmitLValue(cleanups->getSubExpr());
1008 }
1009
Anders Carlsson52ce3bb2009-11-14 01:51:50 +00001010 case Expr::CXXDefaultArgExprClass:
1011 return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
Richard Smith852c9db2013-04-20 22:23:05 +00001012 case Expr::CXXDefaultInitExprClass: {
1013 CXXDefaultInitExprScope Scope(*this);
1014 return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1015 }
Mike Stumpc9b231c2009-11-15 08:09:41 +00001016 case Expr::CXXTypeidExprClass:
1017 return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00001018
Daniel Dunbarc8317a42008-08-23 10:51:21 +00001019 case Expr::ObjCMessageExprClass:
1020 return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001021 case Expr::ObjCIvarRefExprClass:
Chris Lattner4bd55962008-03-30 23:03:07 +00001022 return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
Chris Lattnera4185c52009-04-25 19:35:26 +00001023 case Expr::StmtExprClass:
1024 return EmitStmtExprLValue(cast<StmtExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001025 case Expr::UnaryOperatorClass:
Chris Lattner8394d792007-06-05 20:53:16 +00001026 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00001027 case Expr::ArraySubscriptExprClass:
1028 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00001029 case Expr::OMPArraySectionExprClass:
1030 return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
Nate Begemance4d7fc2008-04-18 23:10:10 +00001031 case Expr::ExtVectorElementExprClass:
1032 return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001033 case Expr::MemberExprClass:
Douglas Gregorc1905232009-08-26 22:36:53 +00001034 return EmitMemberExpr(cast<MemberExpr>(E));
Eli Friedman9fd8b682008-05-13 23:18:27 +00001035 case Expr::CompoundLiteralExprClass:
1036 return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00001037 case Expr::ConditionalOperatorClass:
Anders Carlsson1450adb2009-09-15 16:35:24 +00001038 return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
John McCallc07a0c72011-02-17 10:25:35 +00001039 case Expr::BinaryConditionalOperatorClass:
1040 return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
Chris Lattner053441f2008-12-12 05:35:08 +00001041 case Expr::ChooseExprClass:
Eli Friedman75807f22013-07-20 00:40:58 +00001042 return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
John McCall1bf58462011-02-16 08:02:54 +00001043 case Expr::OpaqueValueExprClass:
1044 return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
John McCall7c454bb2011-07-15 05:09:51 +00001045 case Expr::SubstNonTypeTemplateParmExprClass:
1046 return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
Chris Lattner63d06ab2009-03-18 04:02:57 +00001047 case Expr::ImplicitCastExprClass:
1048 case Expr::CStyleCastExprClass:
1049 case Expr::CXXFunctionalCastExprClass:
1050 case Expr::CXXStaticCastExprClass:
1051 case Expr::CXXDynamicCastExprClass:
1052 case Expr::CXXReinterpretCastExprClass:
1053 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00001054 case Expr::ObjCBridgedCastExprClass:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00001055 return EmitCastLValue(cast<CastExpr>(E));
Sebastian Redl29526f02011-11-27 16:50:07 +00001056
Douglas Gregorfe314812011-06-21 17:03:29 +00001057 case Expr::MaterializeTemporaryExprClass:
1058 return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +00001059 }
1060}
1061
John McCall71335052012-03-10 03:05:10 +00001062/// Given an object of the given canonical type, can we safely copy a
1063/// value out of it based on its initializer?
1064static bool isConstantEmittableObjectType(QualType type) {
1065 assert(type.isCanonical());
1066 assert(!type->isReferenceType());
1067
1068 // Must be const-qualified but non-volatile.
1069 Qualifiers qs = type.getLocalQualifiers();
1070 if (!qs.hasConst() || qs.hasVolatile()) return false;
1071
1072 // Otherwise, all object types satisfy this except C++ classes with
1073 // mutable subobjects or non-trivial copy/destroy behavior.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001074 if (const auto *RT = dyn_cast<RecordType>(type))
1075 if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
John McCall71335052012-03-10 03:05:10 +00001076 if (RD->hasMutableFields() || !RD->isTrivial())
1077 return false;
1078
1079 return true;
1080}
1081
1082/// Can we constant-emit a load of a reference to a variable of the
1083/// given type? This is different from predicates like
1084/// Decl::isUsableInConstantExpressions because we do want it to apply
1085/// in situations that don't necessarily satisfy the language's rules
1086/// for this (e.g. C++'s ODR-use rules). For example, we want to able
1087/// to do this with const float variables even if those variables
1088/// aren't marked 'constexpr'.
1089enum ConstantEmissionKind {
1090 CEK_None,
1091 CEK_AsReferenceOnly,
1092 CEK_AsValueOrReference,
1093 CEK_AsValueOnly
1094};
1095static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1096 type = type.getCanonicalType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001097 if (const auto *ref = dyn_cast<ReferenceType>(type)) {
John McCall71335052012-03-10 03:05:10 +00001098 if (isConstantEmittableObjectType(ref->getPointeeType()))
1099 return CEK_AsValueOrReference;
1100 return CEK_AsReferenceOnly;
1101 }
1102 if (isConstantEmittableObjectType(type))
1103 return CEK_AsValueOnly;
1104 return CEK_None;
1105}
1106
1107/// Try to emit a reference to the given value without producing it as
1108/// an l-value. This is actually more than an optimization: we can't
1109/// produce an l-value for variables that we never actually captured
1110/// in a block or lambda, which means const int variables or constexpr
1111/// literals or similar.
1112CodeGenFunction::ConstantEmission
John McCall113bee02012-03-10 09:33:50 +00001113CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1114 ValueDecl *value = refExpr->getDecl();
1115
John McCall71335052012-03-10 03:05:10 +00001116 // The value needs to be an enum constant or a constant variable.
1117 ConstantEmissionKind CEK;
1118 if (isa<ParmVarDecl>(value)) {
1119 CEK = CEK_None;
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001120 } else if (auto *var = dyn_cast<VarDecl>(value)) {
John McCall71335052012-03-10 03:05:10 +00001121 CEK = checkVarTypeForConstantEmission(var->getType());
1122 } else if (isa<EnumConstantDecl>(value)) {
1123 CEK = CEK_AsValueOnly;
1124 } else {
1125 CEK = CEK_None;
1126 }
1127 if (CEK == CEK_None) return ConstantEmission();
1128
John McCall71335052012-03-10 03:05:10 +00001129 Expr::EvalResult result;
1130 bool resultIsReference;
1131 QualType resultType;
1132
1133 // It's best to evaluate all the way as an r-value if that's permitted.
1134 if (CEK != CEK_AsReferenceOnly &&
John McCall113bee02012-03-10 09:33:50 +00001135 refExpr->EvaluateAsRValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001136 resultIsReference = false;
1137 resultType = refExpr->getType();
1138
1139 // Otherwise, try to evaluate as an l-value.
1140 } else if (CEK != CEK_AsValueOnly &&
John McCall113bee02012-03-10 09:33:50 +00001141 refExpr->EvaluateAsLValue(result, getContext())) {
John McCall71335052012-03-10 03:05:10 +00001142 resultIsReference = true;
1143 resultType = value->getType();
1144
1145 // Failure.
1146 } else {
1147 return ConstantEmission();
1148 }
1149
1150 // In any case, if the initializer has side-effects, abandon ship.
1151 if (result.HasSideEffects)
1152 return ConstantEmission();
1153
1154 // Emit as a constant.
1155 llvm::Constant *C = CGM.EmitConstantValue(result.Val, resultType, this);
1156
Yunzhong Gao0ebf1bb2013-08-30 08:53:09 +00001157 // Make sure we emit a debug reference to the global variable.
1158 // This should probably fire even for
1159 if (isa<VarDecl>(value)) {
1160 if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1161 EmitDeclRefExprDbgValue(refExpr, C);
1162 } else {
1163 assert(isa<EnumConstantDecl>(value));
1164 EmitDeclRefExprDbgValue(refExpr, C);
1165 }
John McCall71335052012-03-10 03:05:10 +00001166
1167 // If we emitted a reference constant, we need to dereference that.
1168 if (resultIsReference)
1169 return ConstantEmission::forReference(C);
1170
1171 return ConstantEmission::forValue(C);
1172}
1173
Nick Lewycky2d84e842013-10-02 02:29:49 +00001174llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1175 SourceLocation Loc) {
John McCall1553b192011-06-16 04:16:24 +00001176 return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001177 lvalue.getType(), Loc, lvalue.getAlignmentSource(),
1178 lvalue.getTBAAInfo(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001179 lvalue.getTBAABaseType(), lvalue.getTBAAOffset(),
1180 lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001181}
1182
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001183static bool hasBooleanRepresentation(QualType Ty) {
1184 if (Ty->isBooleanType())
1185 return true;
1186
1187 if (const EnumType *ET = Ty->getAs<EnumType>())
1188 return ET->getDecl()->getIntegerType()->isBooleanType();
1189
Douglas Gregor298f43d2012-04-12 20:42:30 +00001190 if (const AtomicType *AT = Ty->getAs<AtomicType>())
1191 return hasBooleanRepresentation(AT->getValueType());
1192
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001193 return false;
1194}
1195
Richard Smith1629da92012-12-13 07:11:50 +00001196static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1197 llvm::APInt &Min, llvm::APInt &End,
1198 bool StrictEnums) {
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001199 const EnumType *ET = Ty->getAs<EnumType>();
Richard Smith1629da92012-12-13 07:11:50 +00001200 bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1201 ET && !ET->getDecl()->isFixed();
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001202 bool IsBool = hasBooleanRepresentation(Ty);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001203 if (!IsBool && !IsRegularCPlusPlusEnum)
Richard Smith1629da92012-12-13 07:11:50 +00001204 return false;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001205
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001206 if (IsBool) {
Richard Smith1629da92012-12-13 07:11:50 +00001207 Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1208 End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001209 } else {
1210 const EnumDecl *ED = ET->getDecl();
Richard Smith1629da92012-12-13 07:11:50 +00001211 llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001212 unsigned Bitwidth = LTy->getScalarSizeInBits();
1213 unsigned NumNegativeBits = ED->getNumNegativeBits();
1214 unsigned NumPositiveBits = ED->getNumPositiveBits();
1215
1216 if (NumNegativeBits) {
1217 unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1218 assert(NumBits <= Bitwidth);
1219 End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1220 Min = -End;
1221 } else {
1222 assert(NumPositiveBits <= Bitwidth);
1223 End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1224 Min = llvm::APInt(Bitwidth, 0);
1225 }
1226 }
Richard Smith1629da92012-12-13 07:11:50 +00001227 return true;
1228}
1229
1230llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1231 llvm::APInt Min, End;
1232 if (!getRangeForType(*this, Ty, Min, End,
1233 CGM.getCodeGenOpts().StrictEnums))
Craig Topper8a13c412014-05-21 05:09:00 +00001234 return nullptr;
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001235
Duncan Sandsc720e782012-04-15 18:04:54 +00001236 llvm::MDBuilder MDHelper(getLLVMContext());
Duncan Sands65229ed2012-04-16 16:29:47 +00001237 return MDHelper.createRange(Min, End);
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001238}
1239
John McCall7f416cc2015-09-08 08:05:57 +00001240llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1241 QualType Ty,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001242 SourceLocation Loc,
John McCall7f416cc2015-09-08 08:05:57 +00001243 AlignmentSource AlignSource,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001244 llvm::MDNode *TBAAInfo,
1245 QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001246 uint64_t TBAAOffset,
1247 bool isNontemporal) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001248 // For better performance, handle vector loads differently.
1249 if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00001250 const llvm::Type *EltTy = Addr.getElementType();
Craig Topper99e79272013-07-26 05:59:26 +00001251
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001252 const auto *VTy = cast<llvm::VectorType>(EltTy);
Craig Topper99e79272013-07-26 05:59:26 +00001253
John McCall7f416cc2015-09-08 08:05:57 +00001254 // Handle vectors of size 3 like size 4 for better performance.
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001255 if (VTy->getNumElements() == 3) {
Craig Topper99e79272013-07-26 05:59:26 +00001256
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001257 // Bitcast to vec4 type.
1258 llvm::VectorType *vec4Ty = llvm::VectorType::get(VTy->getElementType(),
1259 4);
John McCall7f416cc2015-09-08 08:05:57 +00001260 Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001261 // Now load value.
John McCall7f416cc2015-09-08 08:05:57 +00001262 llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
Richard Smithf0480fc2012-12-13 05:41:48 +00001263
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001264 // Shuffle vector to get vec3.
John McCall7f416cc2015-09-08 08:05:57 +00001265 V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
Benjamin Kramer99383102015-07-28 16:25:32 +00001266 {0, 1, 2}, "extractVec");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001267 return EmitFromMemory(V, Ty);
1268 }
1269 }
John McCalla8ec7eb2013-03-07 21:37:17 +00001270
1271 // Atomic operations have to be done on integral types.
David Majnemera5b195a2015-02-14 01:35:12 +00001272 if (Ty->isAtomicType() || typeIsSuitableForInlineAtomic(Ty, Volatile)) {
John McCall7f416cc2015-09-08 08:05:57 +00001273 LValue lvalue =
1274 LValue::MakeAddr(Addr, Ty, getContext(), AlignSource, TBAAInfo);
David Majnemereeaec262015-02-14 02:18:14 +00001275 return EmitAtomicLoad(lvalue, Loc).getScalarVal();
John McCalla8ec7eb2013-03-07 21:37:17 +00001276 }
Craig Topper99e79272013-07-26 05:59:26 +00001277
John McCall7f416cc2015-09-08 08:05:57 +00001278 llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001279 if (isNontemporal) {
1280 llvm::MDNode *Node = llvm::MDNode::get(
1281 Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1282 Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1283 }
Manman Renc451e572013-04-04 21:53:22 +00001284 if (TBAAInfo) {
1285 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1286 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001287 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001288 CGM.DecorateInstructionWithTBAA(Load, TBAAPath,
1289 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001290 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001291
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00001292 bool NeedsBoolCheck =
1293 SanOpts.has(SanitizerKind::Bool) && hasBooleanRepresentation(Ty);
1294 bool NeedsEnumCheck =
1295 SanOpts.has(SanitizerKind::Enum) && Ty->getAs<EnumType>();
1296 if (NeedsBoolCheck || NeedsEnumCheck) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00001297 SanitizerScope SanScope(this);
Richard Smith1629da92012-12-13 07:11:50 +00001298 llvm::APInt Min, End;
1299 if (getRangeForType(*this, Ty, Min, End, true)) {
1300 --End;
1301 llvm::Value *Check;
1302 if (!Min)
1303 Check = Builder.CreateICmpULE(
1304 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1305 else {
1306 llvm::Value *Upper = Builder.CreateICmpSLE(
1307 Load, llvm::ConstantInt::get(getLLVMContext(), End));
1308 llvm::Value *Lower = Builder.CreateICmpSGE(
1309 Load, llvm::ConstantInt::get(getLLVMContext(), Min));
1310 Check = Builder.CreateAnd(Upper, Lower);
1311 }
Nick Lewycky2d84e842013-10-02 02:29:49 +00001312 llvm::Constant *StaticArgs[] = {
1313 EmitCheckSourceLocation(Loc),
1314 EmitCheckTypeDescriptor(Ty)
1315 };
Peter Collingbourne3eea6772015-05-11 21:39:14 +00001316 SanitizerMask Kind = NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
Alexey Samsonove396bfc2014-11-11 22:03:54 +00001317 EmitCheck(std::make_pair(Check, Kind), "load_invalid_value", StaticArgs,
1318 EmitCheckValue(Load));
Richard Smith1629da92012-12-13 07:11:50 +00001319 }
1320 } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001321 if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1322 Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
Douglas Gregor0bf31402010-10-08 23:50:27 +00001323
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001324 return EmitFromMemory(Load, Ty);
NAKAMURA Takumi2681efc2012-03-24 14:43:42 +00001325}
1326
John McCall3a7f6922010-10-27 20:58:56 +00001327llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1328 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001329 if (hasBooleanRepresentation(Ty)) {
John McCall3a7f6922010-10-27 20:58:56 +00001330 // This should really always be an i1, but sometimes it's already
1331 // an i8, and it's awkward to track those cases down.
1332 if (Value->getType()->isIntegerTy(1))
Eli Friedmanb369f442012-11-13 02:05:15 +00001333 return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1334 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1335 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001336 }
1337
1338 return Value;
1339}
1340
1341llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1342 // Bool has a different representation in memory than in registers.
Rafael Espindola5c0034a2012-03-24 16:50:34 +00001343 if (hasBooleanRepresentation(Ty)) {
Eli Friedmanb369f442012-11-13 02:05:15 +00001344 assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1345 "wrong value rep of bool");
John McCall3a7f6922010-10-27 20:58:56 +00001346 return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1347 }
1348
1349 return Value;
1350}
1351
John McCall7f416cc2015-09-08 08:05:57 +00001352void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1353 bool Volatile, QualType Ty,
1354 AlignmentSource AlignSource,
1355 llvm::MDNode *TBAAInfo,
Manman Renc451e572013-04-04 21:53:22 +00001356 bool isInit, QualType TBAABaseType,
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001357 uint64_t TBAAOffset,
1358 bool isNontemporal) {
Craig Topper99e79272013-07-26 05:59:26 +00001359
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001360 // Handle vectors differently to get better performance.
1361 if (Ty->isVectorType()) {
1362 llvm::Type *SrcTy = Value->getType();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001363 auto *VecTy = cast<llvm::VectorType>(SrcTy);
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001364 // Handle vec3 special.
1365 if (VecTy->getNumElements() == 3) {
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001366 // Our source is a vec3, do a shuffle vector to make it a vec4.
Benjamin Kramer99383102015-07-28 16:25:32 +00001367 llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1368 Builder.getInt32(2),
1369 llvm::UndefValue::get(Builder.getInt32Ty())};
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001370 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1371 Value = Builder.CreateShuffleVector(Value,
1372 llvm::UndefValue::get(VecTy),
1373 MaskV, "extractVec");
1374 SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1375 }
John McCall7f416cc2015-09-08 08:05:57 +00001376 if (Addr.getElementType() != SrcTy) {
1377 Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
Tanya Lattnera9dd49f2012-08-16 00:10:13 +00001378 }
1379 }
Craig Topper99e79272013-07-26 05:59:26 +00001380
John McCall3a7f6922010-10-27 20:58:56 +00001381 Value = EmitToMemory(Value, Ty);
John McCall47fb9502013-03-07 21:37:08 +00001382
David Majnemera5b195a2015-02-14 01:35:12 +00001383 if (Ty->isAtomicType() ||
1384 (!isInit && typeIsSuitableForInlineAtomic(Ty, Volatile))) {
John McCalla8ec7eb2013-03-07 21:37:17 +00001385 EmitAtomicStore(RValue::get(Value),
John McCall7f416cc2015-09-08 08:05:57 +00001386 LValue::MakeAddr(Addr, Ty, getContext(),
1387 AlignSource, TBAAInfo),
John McCalla8ec7eb2013-03-07 21:37:17 +00001388 isInit);
1389 return;
1390 }
1391
Daniel Dunbar03816342010-08-21 02:24:36 +00001392 llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001393 if (isNontemporal) {
1394 llvm::MDNode *Node =
1395 llvm::MDNode::get(Store->getContext(),
1396 llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1397 Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1398 }
Manman Renc451e572013-04-04 21:53:22 +00001399 if (TBAAInfo) {
1400 llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
1401 TBAAOffset);
Manman Ren4f755de2013-10-08 00:08:49 +00001402 if (TBAAPath)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00001403 CGM.DecorateInstructionWithTBAA(Store, TBAAPath,
1404 false /*ConvertTypeToTag*/);
Manman Renc451e572013-04-04 21:53:22 +00001405 }
Daniel Dunbar1d425462009-02-10 00:57:50 +00001406}
1407
David Chisnallfa35df62012-01-16 17:27:18 +00001408void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
John McCall47fb9502013-03-07 21:37:08 +00001409 bool isInit) {
John McCall1553b192011-06-16 04:16:24 +00001410 EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
John McCall7f416cc2015-09-08 08:05:57 +00001411 lvalue.getType(), lvalue.getAlignmentSource(),
Manman Renc451e572013-04-04 21:53:22 +00001412 lvalue.getTBAAInfo(), isInit, lvalue.getTBAABaseType(),
Michael Zolotukhin84df1232015-09-08 23:52:33 +00001413 lvalue.getTBAAOffset(), lvalue.isNontemporal());
John McCall1553b192011-06-16 04:16:24 +00001414}
1415
Mike Stump4a3999f2009-09-09 13:00:44 +00001416/// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1417/// method emits the address of the lvalue, then loads the result as an rvalue,
1418/// returning the rvalue.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001419RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001420 if (LV.isObjCWeak()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001421 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001422 Address AddrWeakObj = LV.getAddress();
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001423 return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1424 AddrWeakObj));
Fariborz Jahanianf5125d12008-11-18 21:45:40 +00001425 }
Fariborz Jahanianfbd19742012-11-27 23:02:53 +00001426 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1427 llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1428 Object = EmitObjCConsumeObject(LV.getType(), Object);
1429 return RValue::get(Object);
1430 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001431
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001432 if (LV.isSimple()) {
John McCalld68b2d02011-06-27 21:24:11 +00001433 assert(!LV.getType()->isFunctionType());
Mike Stump4a3999f2009-09-09 13:00:44 +00001434
John McCalla1dee5302010-08-22 10:59:02 +00001435 // Everything needs a load.
Nick Lewycky2d84e842013-10-02 02:29:49 +00001436 return RValue::get(EmitLoadOfScalar(LV, Loc));
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001437 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001438
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001439 if (LV.isVectorElt()) {
John McCall7f416cc2015-09-08 08:05:57 +00001440 llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
Eli Friedman610bb872012-03-22 22:36:39 +00001441 LV.isVolatileQualified());
Eli Friedman610bb872012-03-22 22:36:39 +00001442 return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
Chris Lattner08c4b9f2007-07-10 21:17:59 +00001443 "vecext"));
1444 }
Chris Lattner73ab9b32007-08-03 00:16:29 +00001445
1446 // If this is a reference to a subset of the elements of a vector, either
1447 // shuffle the input or extract/insert them as appropriate.
Nate Begemance4d7fc2008-04-18 23:10:10 +00001448 if (LV.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001449 return EmitLoadOfExtVectorElementLValue(LV);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001450
Renato Golin230c5eb2014-05-19 18:15:42 +00001451 // Global Register variables always invoke intrinsics
1452 if (LV.isGlobalReg())
1453 return EmitLoadOfGlobalRegLValue(LV);
1454
John McCallc109a252011-11-07 03:59:57 +00001455 assert(LV.isBitField() && "Unknown LValue type!");
1456 return EmitLoadOfBitfieldLValue(LV);
Chris Lattner8394d792007-06-05 20:53:16 +00001457}
1458
John McCall55e1fbc2011-06-25 02:11:03 +00001459RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001460 const CGBitFieldInfo &Info = LV.getBitFieldInfo();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001461
Daniel Dunbar3447a022010-04-13 23:34:15 +00001462 // Get the output type.
Chris Lattner2192fe52011-07-18 04:24:23 +00001463 llvm::Type *ResLTy = ConvertType(LV.getType());
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001464
John McCall7f416cc2015-09-08 08:05:57 +00001465 Address Ptr = LV.getBitFieldAddress();
1466 llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
Mike Stump4a3999f2009-09-09 13:00:44 +00001467
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001468 if (Info.IsSigned) {
David Greenec5ff6242013-01-15 23:13:47 +00001469 assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001470 unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1471 if (HighBits)
1472 Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1473 if (Info.Offset + HighBits)
1474 Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1475 } else {
1476 if (Info.Offset)
1477 Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
Eli Bendersky03b913d2012-12-18 22:22:16 +00001478 if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001479 Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1480 Info.Size),
1481 "bf.clear");
Daniel Dunbaread7c912008-08-06 05:08:45 +00001482 }
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001483 Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001484
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001485 return RValue::get(Val);
Lauro Ramos Venancio2ddcb25a32008-01-22 20:17:04 +00001486}
1487
Nate Begemanb699c9b2009-01-18 06:42:49 +00001488// If this is a reference to a subset of the elements of a vector, create an
1489// appropriate shufflevector.
John McCall55e1fbc2011-06-25 02:11:03 +00001490RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
John McCall7f416cc2015-09-08 08:05:57 +00001491 llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1492 LV.isVolatileQualified());
Mike Stump4a3999f2009-09-09 13:00:44 +00001493
Nate Begemanf322eab2008-05-09 06:41:27 +00001494 const llvm::Constant *Elts = LV.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001495
1496 // If the result of the expression is a non-vector type, we must be extracting
1497 // a single element. Just codegen as an extractelement.
John McCall55e1fbc2011-06-25 02:11:03 +00001498 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001499 if (!ExprVT) {
Dan Gohman75d69da2008-05-22 00:50:06 +00001500 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001501 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001502 return RValue::get(Builder.CreateExtractElement(Vec, Elt));
Chris Lattner40ff7012007-08-03 16:18:34 +00001503 }
Nate Begemanb699c9b2009-01-18 06:42:49 +00001504
1505 // Always use shuffle vector to try to retain the original program structure
Chris Lattner8eab8ff2007-08-10 17:10:08 +00001506 unsigned NumResultElts = ExprVT->getNumElements();
Mike Stump4a3999f2009-09-09 13:00:44 +00001507
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001508 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001509 for (unsigned i = 0; i != NumResultElts; ++i)
1510 Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
Mike Stump4a3999f2009-09-09 13:00:44 +00001511
Chris Lattner91c08ad2011-02-15 00:14:06 +00001512 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1513 Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001514 MaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001515 return RValue::get(Vec);
Chris Lattner40ff7012007-08-03 16:18:34 +00001516}
1517
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001518/// @brief Generates lvalue for partial ext_vector access.
John McCall7f416cc2015-09-08 08:05:57 +00001519Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1520 Address VectorAddress = LV.getExtVectorAddress();
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001521 const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1522 QualType EQT = ExprVT->getElementType();
1523 llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001524
John McCall7f416cc2015-09-08 08:05:57 +00001525 Address CastToPointerElement =
1526 Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1527 "conv.ptr.element");
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001528
1529 const llvm::Constant *Elts = LV.getExtVectorElts();
1530 unsigned ix = getAccessedFieldNo(0, Elts);
1531
John McCall7f416cc2015-09-08 08:05:57 +00001532 Address VectorBasePtrPlusIx =
1533 Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1534 getContext().getTypeSizeInChars(EQT),
1535 "vector.elt");
1536
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00001537 return VectorBasePtrPlusIx;
1538}
1539
Renato Golin230c5eb2014-05-19 18:15:42 +00001540/// @brief Load of global gamed gegisters are always calls to intrinsics.
1541RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001542 assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1543 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001544 llvm::MDNode *RegName = cast<llvm::MDNode>(
1545 cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
Renato Golin2e31e4e2014-06-05 16:45:22 +00001546
1547 // We accept integer and pointer types only
1548 llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1549 llvm::Type *Ty = OrigTy;
1550 if (OrigTy->isPointerTy())
1551 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1552 llvm::Type *Types[] = { Ty };
1553
Renato Golin230c5eb2014-05-19 18:15:42 +00001554 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001555 llvm::Value *Call = Builder.CreateCall(
1556 F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
Renato Golin2e31e4e2014-06-05 16:45:22 +00001557 if (OrigTy->isPointerTy())
1558 Call = Builder.CreateIntToPtr(Call, OrigTy);
Renato Golin230c5eb2014-05-19 18:15:42 +00001559 return RValue::get(Call);
1560}
Chris Lattner40ff7012007-08-03 16:18:34 +00001561
Chris Lattner9369a562007-06-29 16:31:29 +00001562
Chris Lattner8394d792007-06-05 20:53:16 +00001563/// EmitStoreThroughLValue - Store the specified rvalue into the specified
1564/// lvalue, where both are guaranteed to the have the same type, and that type
1565/// is 'Ty'.
Nick Lewycky5fa40c32013-10-01 21:51:38 +00001566void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
David Blaikie66e41972015-01-14 07:38:27 +00001567 bool isInit) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001568 if (!Dst.isSimple()) {
1569 if (Dst.isVectorElt()) {
1570 // Read/modify/write the vector, inserting the new element.
John McCall7f416cc2015-09-08 08:05:57 +00001571 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1572 Dst.isVolatileQualified());
Chris Lattner4647a212007-08-31 22:49:20 +00001573 Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
Chris Lattner41d480e2007-08-03 16:28:33 +00001574 Dst.getVectorIdx(), "vecins");
John McCall7f416cc2015-09-08 08:05:57 +00001575 Builder.CreateStore(Vec, Dst.getVectorAddress(),
1576 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001577 return;
1578 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001579
Nate Begemance4d7fc2008-04-18 23:10:10 +00001580 // If this is an update of extended vector elements, insert them as
1581 // appropriate.
1582 if (Dst.isExtVectorElt())
John McCall55e1fbc2011-06-25 02:11:03 +00001583 return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001584
Renato Golin230c5eb2014-05-19 18:15:42 +00001585 if (Dst.isGlobalReg())
1586 return EmitStoreThroughGlobalRegLValue(Src, Dst);
1587
John McCallc109a252011-11-07 03:59:57 +00001588 assert(Dst.isBitField() && "Unknown LValue type");
1589 return EmitStoreThroughBitfieldLValue(Src, Dst);
Chris Lattner41d480e2007-08-03 16:28:33 +00001590 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001591
John McCall31168b02011-06-15 23:02:42 +00001592 // There's special magic for assigning into an ARC-qualified l-value.
1593 if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1594 switch (Lifetime) {
1595 case Qualifiers::OCL_None:
1596 llvm_unreachable("present but none");
1597
1598 case Qualifiers::OCL_ExplicitNone:
1599 // nothing special
1600 break;
1601
1602 case Qualifiers::OCL_Strong:
John McCall55e1fbc2011-06-25 02:11:03 +00001603 EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
John McCall31168b02011-06-15 23:02:42 +00001604 return;
1605
1606 case Qualifiers::OCL_Weak:
1607 EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1608 return;
1609
1610 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00001611 Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1612 Src.getScalarVal()));
John McCall31168b02011-06-15 23:02:42 +00001613 // fall into the normal path
1614 break;
1615 }
1616 }
1617
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001618 if (Dst.isObjCWeak() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001619 // load of a __weak object.
John McCall7f416cc2015-09-08 08:05:57 +00001620 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001621 llvm::Value *src = Src.getScalarVal();
Mike Stumpca5ae662009-04-14 00:57:29 +00001622 CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001623 return;
1624 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001625
Fariborz Jahanian10bec102009-02-21 00:30:43 +00001626 if (Dst.isObjCStrong() && !Dst.isNonGC()) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001627 // load of a __strong object.
John McCall7f416cc2015-09-08 08:05:57 +00001628 Address LvalueDst = Dst.getAddress();
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001629 llvm::Value *src = Src.getScalarVal();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001630 if (Dst.isObjCIvar()) {
1631 assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
John McCall7f416cc2015-09-08 08:05:57 +00001632 llvm::Type *ResultType = IntPtrTy;
1633 Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1634 llvm::Value *RHS = dst.getPointer();
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001635 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
Craig Topper99e79272013-07-26 05:59:26 +00001636 llvm::Value *LHS =
John McCall7f416cc2015-09-08 08:05:57 +00001637 Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1638 "sub.ptr.lhs.cast");
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001639 llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
Fariborz Jahanian1f9ed582009-09-25 00:00:20 +00001640 CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001641 BytesBetween);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001642 } else if (Dst.isGlobalObjCRef()) {
1643 CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1644 Dst.isThreadLocalRef());
1645 }
Fariborz Jahanian32ff7ae2009-05-04 23:27:20 +00001646 else
1647 CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
Fariborz Jahanian50a12702008-11-19 17:34:06 +00001648 return;
1649 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001650
Chris Lattner6278e6a2007-08-11 00:04:45 +00001651 assert(Src.isScalar() && "Can't emit an agg store with this method");
David Chisnallfa35df62012-01-16 17:27:18 +00001652 EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
Chris Lattner8394d792007-06-05 20:53:16 +00001653}
1654
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001655void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001656 llvm::Value **Result) {
Daniel Dunbar196ea442010-04-06 01:07:44 +00001657 const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
Chris Lattner2192fe52011-07-18 04:24:23 +00001658 llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
John McCall7f416cc2015-09-08 08:05:57 +00001659 Address Ptr = Dst.getBitFieldAddress();
Daniel Dunbaread7c912008-08-06 05:08:45 +00001660
Daniel Dunbar67aba792010-04-15 03:47:33 +00001661 // Get the source value, truncated to the width of the bit-field.
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001662 llvm::Value *SrcVal = Src.getScalarVal();
Anders Carlsson8345a702010-04-17 21:52:22 +00001663
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001664 // Cast the source to the storage type and shift it into place.
John McCall7f416cc2015-09-08 08:05:57 +00001665 SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001666 /*IsSigned=*/false);
1667 llvm::Value *MaskedVal = SrcVal;
Anders Carlsson8345a702010-04-17 21:52:22 +00001668
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001669 // See if there are other bits in the bitfield's storage we'll need to load
1670 // and mask together with source before storing.
1671 if (Info.StorageSize != Info.Size) {
1672 assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
John McCall7f416cc2015-09-08 08:05:57 +00001673 llvm::Value *Val =
1674 Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001675
1676 // Mask the source value as needed.
1677 if (!hasBooleanRepresentation(Dst.getType()))
1678 SrcVal = Builder.CreateAnd(SrcVal,
1679 llvm::APInt::getLowBitsSet(Info.StorageSize,
1680 Info.Size),
1681 "bf.value");
1682 MaskedVal = SrcVal;
1683 if (Info.Offset)
1684 SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1685
1686 // Mask out the original value.
1687 Val = Builder.CreateAnd(Val,
1688 ~llvm::APInt::getBitsSet(Info.StorageSize,
1689 Info.Offset,
1690 Info.Offset + Info.Size),
1691 "bf.clear");
1692
1693 // Or together the unchanged values and the source value.
1694 SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1695 } else {
1696 assert(Info.Offset == 0);
1697 }
1698
1699 // Write the new value back out.
John McCall7f416cc2015-09-08 08:05:57 +00001700 Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001701
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001702 // Return the new value of the bit-field, if requested.
1703 if (Result) {
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001704 llvm::Value *ResultVal = MaskedVal;
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001705
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001706 // Sign extend the value if needed.
1707 if (Info.IsSigned) {
1708 assert(Info.Size <= Info.StorageSize);
1709 unsigned HighBits = Info.StorageSize - Info.Size;
1710 if (HighBits) {
1711 ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1712 ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1713 }
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001714 }
1715
Chandler Carruthff0e3a12012-12-06 11:14:44 +00001716 ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1717 "bf.result.cast");
Eli Friedman39b685e2012-12-19 00:26:58 +00001718 *Result = EmitFromMemory(ResultVal, Dst.getType());
Daniel Dunbaread7c912008-08-06 05:08:45 +00001719 }
Lauro Ramos Venancio09af71c2008-01-22 22:36:45 +00001720}
1721
Nate Begemance4d7fc2008-04-18 23:10:10 +00001722void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
John McCall55e1fbc2011-06-25 02:11:03 +00001723 LValue Dst) {
Chris Lattner41d480e2007-08-03 16:28:33 +00001724 // This access turns into a read/modify/write of the vector. Load the input
1725 // value now.
John McCall7f416cc2015-09-08 08:05:57 +00001726 llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1727 Dst.isVolatileQualified());
Nate Begemanf322eab2008-05-09 06:41:27 +00001728 const llvm::Constant *Elts = Dst.getExtVectorElts();
Mike Stump4a3999f2009-09-09 13:00:44 +00001729
Chris Lattner4647a212007-08-31 22:49:20 +00001730 llvm::Value *SrcVal = Src.getScalarVal();
Mike Stump4a3999f2009-09-09 13:00:44 +00001731
John McCall55e1fbc2011-06-25 02:11:03 +00001732 if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
Chris Lattner3a44aa72007-08-03 16:37:04 +00001733 unsigned NumSrcElts = VTy->getNumElements();
Nate Begemanb699c9b2009-01-18 06:42:49 +00001734 unsigned NumDstElts =
1735 cast<llvm::VectorType>(Vec->getType())->getNumElements();
1736 if (NumDstElts == NumSrcElts) {
Mike Stump4a3999f2009-09-09 13:00:44 +00001737 // Use shuffle vector is the src and destination are the same number of
1738 // elements and restore the vector mask since it is on the side it will be
1739 // stored.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001740 SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001741 for (unsigned i = 0; i != NumSrcElts; ++i)
1742 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
Mike Stump4a3999f2009-09-09 13:00:44 +00001743
Chris Lattner91c08ad2011-02-15 00:14:06 +00001744 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001745 Vec = Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001746 llvm::UndefValue::get(Vec->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001747 MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001748 } else if (NumDstElts > NumSrcElts) {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001749 // Extended the source vector to the same length and then shuffle it
1750 // into the destination.
1751 // FIXME: since we're shuffling with undef, can we just use the indices
1752 // into that? This could be simpler.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001753 SmallVector<llvm::Constant*, 4> ExtMask;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001754 for (unsigned i = 0; i != NumSrcElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001755 ExtMask.push_back(Builder.getInt32(i));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001756 ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001757 llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
Mike Stump4a3999f2009-09-09 13:00:44 +00001758 llvm::Value *ExtSrcVal =
Daniel Dunbar3d926cb2009-02-17 18:31:04 +00001759 Builder.CreateShuffleVector(SrcVal,
Owen Anderson7ec07a52009-07-30 23:11:26 +00001760 llvm::UndefValue::get(SrcVal->getType()),
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001761 ExtMaskV);
Nate Begemanb699c9b2009-01-18 06:42:49 +00001762 // build identity
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001763 SmallVector<llvm::Constant*, 4> Mask;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001764 for (unsigned i = 0; i != NumDstElts; ++i)
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001765 Mask.push_back(Builder.getInt32(i));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001766
Joey Goulycf4143b2013-11-21 17:09:05 +00001767 // When the vector size is odd and .odd or .hi is used, the last element
1768 // of the Elts constant array will be one past the size of the vector.
1769 // Ignore the last element here, if it is greater than the mask size.
1770 if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1771 NumSrcElts--;
1772
Nate Begemanb699c9b2009-01-18 06:42:49 +00001773 // modify when what gets shuffled in
Chris Lattner2d6b7b92012-01-25 05:34:41 +00001774 for (unsigned i = 0; i != NumSrcElts; ++i)
1775 Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001776 llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001777 Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
Mike Stump658fe022009-07-30 22:28:39 +00001778 } else {
Nate Begemanb699c9b2009-01-18 06:42:49 +00001779 // We should never shorten the vector
David Blaikie83d382b2011-09-23 05:06:16 +00001780 llvm_unreachable("unexpected shorten vector length");
Chris Lattner3a44aa72007-08-03 16:37:04 +00001781 }
1782 } else {
1783 // If the Src is a scalar (not a vector) it must be updating one element.
Dan Gohman75d69da2008-05-22 00:50:06 +00001784 unsigned InIdx = getAccessedFieldNo(0, Elts);
Michael J. Spencerdd597752014-05-31 00:22:12 +00001785 llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001786 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
Chris Lattner41d480e2007-08-03 16:28:33 +00001787 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001788
John McCall7f416cc2015-09-08 08:05:57 +00001789 Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
1790 Dst.isVolatileQualified());
Chris Lattner41d480e2007-08-03 16:28:33 +00001791}
1792
Renato Golin230c5eb2014-05-19 18:15:42 +00001793/// @brief Store of global named registers are always calls to intrinsics.
1794void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
Renato Golin2e31e4e2014-06-05 16:45:22 +00001795 assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
1796 "Bad type for register variable");
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001797 llvm::MDNode *RegName = cast<llvm::MDNode>(
1798 cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
Renato Golin230c5eb2014-05-19 18:15:42 +00001799 assert(RegName && "Register LValue is not metadata");
Renato Golin2e31e4e2014-06-05 16:45:22 +00001800
1801 // We accept integer and pointer types only
1802 llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
1803 llvm::Type *Ty = OrigTy;
1804 if (OrigTy->isPointerTy())
1805 Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1806 llvm::Type *Types[] = { Ty };
1807
Renato Golin230c5eb2014-05-19 18:15:42 +00001808 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
1809 llvm::Value *Value = Src.getScalarVal();
Renato Golin2e31e4e2014-06-05 16:45:22 +00001810 if (OrigTy->isPointerTy())
1811 Value = Builder.CreatePtrToInt(Value, Ty);
David Blaikie43f9bb72015-05-18 22:14:03 +00001812 Builder.CreateCall(
1813 F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
Renato Golin230c5eb2014-05-19 18:15:42 +00001814}
1815
Eric Christopherc9e2a682014-05-20 17:10:39 +00001816// setObjCGCLValueClass - sets class of the lvalue for the purpose of
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001817// generating write-barries API. It is currently a global, ivar,
1818// or neither.
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001819static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001820 LValue &LV,
1821 bool IsMemberAccess=false) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001822 if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001823 return;
Craig Topper99e79272013-07-26 05:59:26 +00001824
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001825 if (isa<ObjCIvarRefExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001826 QualType ExpTy = E->getType();
1827 if (IsMemberAccess && ExpTy->isPointerType()) {
1828 // If ivar is a structure pointer, assigning to field of
Craig Topper99e79272013-07-26 05:59:26 +00001829 // this struct follows gcc's behavior and makes it a non-ivar
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001830 // writer-barrier conservatively.
1831 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1832 if (ExpTy->isRecordType()) {
1833 LV.setObjCIvar(false);
1834 return;
1835 }
1836 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001837 LV.setObjCIvar(true);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001838 auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
Fariborz Jahanian7a95d722009-09-24 22:25:38 +00001839 LV.setBaseIvarExp(Exp->getBase());
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001840 LV.setObjCArray(E->getType()->isArrayType());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00001841 return;
1842 }
Craig Topper99e79272013-07-26 05:59:26 +00001843
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001844 if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
1845 if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
John McCall1c9c3fd2010-10-15 04:57:14 +00001846 if (VD->hasGlobalStorage()) {
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001847 LV.setGlobalObjCRef(true);
Richard Smithfd3834f2013-04-13 02:43:54 +00001848 LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
Fariborz Jahanian217af242010-07-20 20:30:03 +00001849 }
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001850 }
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001851 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001852 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001853 }
Craig Topper99e79272013-07-26 05:59:26 +00001854
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001855 if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001856 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001857 return;
1858 }
Craig Topper99e79272013-07-26 05:59:26 +00001859
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001860 if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001861 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001862 if (LV.isObjCIvar()) {
1863 // If cast is to a structure pointer, follow gcc's behavior and make it
1864 // a non-ivar write-barrier.
1865 QualType ExpTy = E->getType();
1866 if (ExpTy->isPointerType())
1867 ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
1868 if (ExpTy->isRecordType())
Craig Topper99e79272013-07-26 05:59:26 +00001869 LV.setObjCIvar(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001870 }
1871 return;
Fariborz Jahaniane01e4342009-09-30 17:10:29 +00001872 }
Peter Collingbourne91147592011-04-15 00:35:48 +00001873
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001874 if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
Peter Collingbourne91147592011-04-15 00:35:48 +00001875 setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
1876 return;
1877 }
1878
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001879 if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001880 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001881 return;
1882 }
Craig Topper99e79272013-07-26 05:59:26 +00001883
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001884 if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001885 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001886 return;
1887 }
John McCall31168b02011-06-15 23:02:42 +00001888
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001889 if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001890 setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
John McCall31168b02011-06-15 23:02:42 +00001891 return;
1892 }
1893
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001894 if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001895 setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
Craig Topper99e79272013-07-26 05:59:26 +00001896 if (LV.isObjCIvar() && !LV.isObjCArray())
1897 // Using array syntax to assigning to what an ivar points to is not
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001898 // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
Craig Topper99e79272013-07-26 05:59:26 +00001899 LV.setObjCIvar(false);
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001900 else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
Craig Topper99e79272013-07-26 05:59:26 +00001901 // Using array syntax to assigning to what global points to is not
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00001902 // same as assigning to the global itself. {id *G;} G[i] = 0;
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001903 LV.setGlobalObjCRef(false);
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001904 return;
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001905 }
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001906
Rafael Espindola2ae250c2014-05-09 00:08:36 +00001907 if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
Fariborz Jahanian0c784272011-09-30 18:23:36 +00001908 setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
Fariborz Jahanian2e32ddc2009-09-18 00:04:00 +00001909 // We don't know if member is an 'ivar', but this flag is looked at
1910 // only in the context of LV.isObjCIvar().
Daniel Dunbar4bb04ce2010-08-21 03:51:29 +00001911 LV.setObjCArray(E->getType()->isArrayType());
Chris Lattnerab5e0af2009-10-28 17:39:19 +00001912 return;
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00001913 }
1914}
1915
Chris Lattner3f32d692011-07-12 06:52:18 +00001916static llvm::Value *
Chandler Carruth4678f672011-07-12 08:58:26 +00001917EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
Chris Lattner3f32d692011-07-12 06:52:18 +00001918 llvm::Value *V, llvm::Type *IRType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001919 StringRef Name = StringRef()) {
Chris Lattner3f32d692011-07-12 06:52:18 +00001920 unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
Chandler Carruth4678f672011-07-12 08:58:26 +00001921 return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
Chris Lattner3f32d692011-07-12 06:52:18 +00001922}
1923
Alexey Bataev97720002014-11-11 04:05:39 +00001924static LValue EmitThreadPrivateVarDeclLValue(
John McCall7f416cc2015-09-08 08:05:57 +00001925 CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
1926 llvm::Type *RealVarTy, SourceLocation Loc) {
1927 Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
1928 Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
1929 return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
1930}
1931
1932Address CodeGenFunction::EmitLoadOfReference(Address Addr,
1933 const ReferenceType *RefTy,
1934 AlignmentSource *Source) {
1935 llvm::Value *Ptr = Builder.CreateLoad(Addr);
1936 return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
1937 Source, /*forPointee*/ true));
1938
1939}
1940
1941LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
1942 const ReferenceType *RefTy) {
1943 AlignmentSource Source;
1944 Address Addr = EmitLoadOfReference(RefAddr, RefTy, &Source);
1945 return MakeAddrLValue(Addr, RefTy->getPointeeType(), Source);
Alexey Bataev97720002014-11-11 04:05:39 +00001946}
1947
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001948static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
1949 const Expr *E, const VarDecl *VD) {
Richard Smith0f383742014-03-26 22:48:22 +00001950 QualType T = E->getType();
1951
1952 // If it's thread_local, emit a call to its wrapper function instead.
David Majnemerb3341ea2014-10-05 05:05:40 +00001953 if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
1954 CGF.CGM.getCXXABI().usesThreadWrapperFunction())
Richard Smith0f383742014-03-26 22:48:22 +00001955 return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
1956
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001957 llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001958 llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
1959 V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
Eli Friedmana0544d62011-12-03 04:14:32 +00001960 CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
John McCall7f416cc2015-09-08 08:05:57 +00001961 Address Addr(V, Alignment);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001962 LValue LV;
Alexey Bataev97720002014-11-11 04:05:39 +00001963 // Emit reference to the private copy of the variable if it is an OpenMP
1964 // threadprivate variable.
1965 if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
John McCall7f416cc2015-09-08 08:05:57 +00001966 return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
Alexey Bataev97720002014-11-11 04:05:39 +00001967 E->getExprLoc());
John McCall7f416cc2015-09-08 08:05:57 +00001968 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
1969 LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001970 } else {
John McCall7f416cc2015-09-08 08:05:57 +00001971 LV = CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00001972 }
Anders Carlssonea4c30b2009-11-07 23:06:58 +00001973 setObjCGCLValueClass(CGF.getContext(), E, LV);
1974 return LV;
1975}
1976
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001977static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
Chris Lattner13ee4f42011-07-10 05:34:54 +00001978 const Expr *E, const FunctionDecl *FD) {
Chris Lattnerf53c0962010-09-06 00:11:41 +00001979 llvm::Value *V = CGF.CGM.GetAddrOfFunction(FD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001980 if (!FD->hasPrototype()) {
1981 if (const FunctionProtoType *Proto =
1982 FD->getType()->getAs<FunctionProtoType>()) {
1983 // Ugly case: for a K&R-style definition, the type of the definition
1984 // isn't the same as the type of a use. Correct for this with a
1985 // bitcast.
1986 QualType NoProtoType =
Alp Toker314cc812014-01-25 16:55:45 +00001987 CGF.getContext().getFunctionNoProtoType(Proto->getReturnType());
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001988 NoProtoType = CGF.getContext().getPointerType(NoProtoType);
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001989 V = CGF.Builder.CreateBitCast(V, CGF.ConvertType(NoProtoType));
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001990 }
1991 }
Eli Friedmana0544d62011-12-03 04:14:32 +00001992 CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
John McCall7f416cc2015-09-08 08:05:57 +00001993 return CGF.MakeAddrLValue(V, E->getType(), Alignment, AlignmentSource::Decl);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00001994}
1995
Ben Langmuir3b4c30b2013-05-09 19:17:11 +00001996static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
1997 llvm::Value *ThisValue) {
1998 QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
1999 LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2000 return CGF.EmitLValueForField(LV, FD);
2001}
2002
Renato Golin230c5eb2014-05-19 18:15:42 +00002003/// Named Registers are named metadata pointing to the register name
2004/// which will be read from/written to as an argument to the intrinsic
2005/// @llvm.read/write_register.
2006/// So far, only the name is being passed down, but other options such as
2007/// register type, allocation type or even optimization options could be
2008/// passed down via the metadata node.
John McCall7f416cc2015-09-08 08:05:57 +00002009static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
Renato Golinc296d952014-05-19 23:25:25 +00002010 SmallString<64> Name("llvm.named.register.");
Renato Golin230c5eb2014-05-19 18:15:42 +00002011 AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
Renato Golinc296d952014-05-19 23:25:25 +00002012 assert(Asm->getLabel().size() < 64-Name.size() &&
2013 "Register name too big");
2014 Name.append(Asm->getLabel());
Renato Golin156a8532014-05-19 22:36:19 +00002015 llvm::NamedMDNode *M =
Renato Golinc296d952014-05-19 23:25:25 +00002016 CGM.getModule().getOrInsertNamedMetadata(Name);
Renato Golin230c5eb2014-05-19 18:15:42 +00002017 if (M->getNumOperands() == 0) {
2018 llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2019 Asm->getLabel());
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002020 llvm::Metadata *Ops[] = {Str};
Renato Golin230c5eb2014-05-19 18:15:42 +00002021 M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2022 }
John McCall7f416cc2015-09-08 08:05:57 +00002023
2024 CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2025
2026 llvm::Value *Ptr =
2027 llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2028 return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
Renato Golin230c5eb2014-05-19 18:15:42 +00002029}
2030
Chris Lattnerd7f58862007-06-02 05:24:33 +00002031LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002032 const NamedDecl *ND = E->getDecl();
Eli Friedmand20adbd2011-11-16 00:42:57 +00002033 QualType T = E->getType();
Renato Golin230c5eb2014-05-19 18:15:42 +00002034
Renato Goline7b3d5d2014-05-27 16:46:27 +00002035 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2036 // Global Named registers access via intrinsics only
2037 if (VD->getStorageClass() == SC_Register &&
2038 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
John McCall7f416cc2015-09-08 08:05:57 +00002039 return EmitGlobalNamedRegister(VD, CGM);
Mike Stump4a3999f2009-09-09 13:00:44 +00002040
Renato Goline7b3d5d2014-05-27 16:46:27 +00002041 // A DeclRefExpr for a reference initialized by a constant expression can
2042 // appear without being odr-used. Directly emit the constant initializer.
Richard Smith5a1104b2012-10-20 01:38:33 +00002043 const Expr *Init = VD->getAnyInitializer(VD);
2044 if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2045 VD->isUsableInConstantExpressions(getContext()) &&
Alexey Bataev2377fe92015-09-10 08:12:02 +00002046 VD->checkInitIsICE() &&
2047 // Do not emit if it is private OpenMP variable.
2048 !(E->refersToEnclosingVariableOrCapture() && CapturedStmtInfo &&
2049 LocalDeclMap.count(VD))) {
Richard Smith5a1104b2012-10-20 01:38:33 +00002050 llvm::Constant *Val =
2051 CGM.EmitConstantValue(*VD->evaluateValue(), VD->getType(), this);
2052 assert(Val && "failed to emit reference constant expression");
2053 // FIXME: Eventually we will want to emit vector element references.
John McCall7f416cc2015-09-08 08:05:57 +00002054
2055 // Should we be using the alignment of the constant pointer we emitted?
2056 CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2057 /*pointee*/ true);
2058
2059 return MakeAddrLValue(Address(Val, Alignment), T, AlignmentSource::Decl);
Richard Smith5a1104b2012-10-20 01:38:33 +00002060 }
David Majnemer602cfe72015-01-01 09:49:44 +00002061
2062 // Check for captured variables.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00002063 if (E->refersToEnclosingVariableOrCapture()) {
David Majnemer602cfe72015-01-01 09:49:44 +00002064 if (auto *FD = LambdaCaptureFields.lookup(VD))
2065 return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2066 else if (CapturedStmtInfo) {
John McCall7f416cc2015-09-08 08:05:57 +00002067 auto it = LocalDeclMap.find(VD);
2068 if (it != LocalDeclMap.end()) {
2069 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2070 return EmitLoadOfReferenceLValue(it->second, RefTy);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002071 }
John McCall7f416cc2015-09-08 08:05:57 +00002072 return MakeAddrLValue(it->second, T);
Alexey Bataevcaacd532015-09-04 11:26:21 +00002073 }
Alexey Bataevc71a4092015-09-11 10:29:41 +00002074 LValue CapLVal =
2075 EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2076 CapturedStmtInfo->getContextValue());
2077 return MakeAddrLValue(
2078 Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2079 CapLVal.getType(), AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002080 }
John McCall7f416cc2015-09-08 08:05:57 +00002081
David Majnemer602cfe72015-01-01 09:49:44 +00002082 assert(isa<BlockDecl>(CurCodeDecl));
John McCall7f416cc2015-09-08 08:05:57 +00002083 Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2084 return MakeAddrLValue(addr, T, AlignmentSource::Decl);
David Majnemer602cfe72015-01-01 09:49:44 +00002085 }
Richard Smith5a1104b2012-10-20 01:38:33 +00002086 }
2087
Eli Friedman5720e342012-01-21 04:52:58 +00002088 // FIXME: We should be able to assert this for FunctionDecls as well!
2089 // FIXME: We should be able to assert this for all DeclRefExprs, not just
2090 // those with a valid source location.
2091 assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2092 !E->getLocation().isValid()) &&
2093 "Should not use decl without marking it used!");
2094
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002095 if (ND->hasAttr<WeakRefAttr>()) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002096 const auto *VD = cast<ValueDecl>(ND);
John McCall7f416cc2015-09-08 08:05:57 +00002097 ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2098 return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
Rafael Espindola2e42fec2010-03-04 18:17:24 +00002099 }
2100
Renato Goline7b3d5d2014-05-27 16:46:27 +00002101 if (const auto *VD = dyn_cast<VarDecl>(ND)) {
Anders Carlsson2ff6395d2009-11-07 22:53:10 +00002102 // Check if this is a global variable.
Richard Smith0f383742014-03-26 22:48:22 +00002103 if (VD->hasLinkage() || VD->isStaticDataMember())
Anders Carlssonea4c30b2009-11-07 23:06:58 +00002104 return EmitGlobalVarDeclLValue(*this, E, VD);
Anders Carlsson6eee9722009-11-07 22:46:42 +00002105
John McCall7f416cc2015-09-08 08:05:57 +00002106 Address addr = Address::invalid();
John McCall113bee02012-03-10 09:33:50 +00002107
John McCall7f416cc2015-09-08 08:05:57 +00002108 // The variable should generally be present in the local decl map.
2109 auto iter = LocalDeclMap.find(VD);
2110 if (iter != LocalDeclMap.end()) {
2111 addr = iter->second;
Eli Friedman9fbeba02012-02-11 02:57:39 +00002112
John McCall7f416cc2015-09-08 08:05:57 +00002113 // Otherwise, it might be static local we haven't emitted yet for
2114 // some reason; most likely, because it's in an outer function.
2115 } else if (VD->isStaticLocal()) {
2116 addr = Address(CGM.getOrCreateStaticVarDecl(
2117 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2118 getContext().getDeclAlign(VD));
Alexey Bataev97720002014-11-11 04:05:39 +00002119
John McCall7f416cc2015-09-08 08:05:57 +00002120 // No other cases for now.
Eli Friedmand20adbd2011-11-16 00:42:57 +00002121 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002122 llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2123 }
2124
2125
2126 // Check for OpenMP threadprivate variables.
2127 if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2128 return EmitThreadPrivateVarDeclLValue(
2129 *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2130 E->getExprLoc());
2131 }
2132
2133 // Drill into block byref variables.
2134 bool isBlockByref = VD->hasAttr<BlocksAttr>();
2135 if (isBlockByref) {
2136 addr = emitBlockByrefAddress(addr, VD);
2137 }
2138
2139 // Drill into reference types.
2140 LValue LV;
2141 if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2142 LV = EmitLoadOfReferenceLValue(addr, RefTy);
2143 } else {
2144 LV = MakeAddrLValue(addr, T, AlignmentSource::Decl);
Eli Friedmand20adbd2011-11-16 00:42:57 +00002145 }
Chris Lattner3f32d692011-07-12 06:52:18 +00002146
John McCallcdda29c2013-03-13 03:10:54 +00002147 bool isLocalStorage = VD->hasLocalStorage();
2148
2149 bool NonGCable = isLocalStorage &&
2150 !VD->getType()->isReferenceType() &&
John McCall7f416cc2015-09-08 08:05:57 +00002151 !isBlockByref;
Fariborz Jahanian44a41d12010-11-19 18:17:09 +00002152 if (NonGCable) {
Daniel Dunbarf166a522010-08-21 03:44:13 +00002153 LV.getQuals().removeObjCGCAttr();
Daniel Dunbare50dda92010-08-21 03:22:38 +00002154 LV.setNonGC(true);
2155 }
John McCallcdda29c2013-03-13 03:10:54 +00002156
2157 bool isImpreciseLifetime =
2158 (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2159 if (isImpreciseLifetime)
2160 LV.setARCPreciseLifetime(ARCImpreciseLifetime);
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002161 setObjCGCLValueClass(getContext(), E, LV);
Fariborz Jahanian003e8302008-11-20 00:15:42 +00002162 return LV;
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002163 }
John McCallf3a88602011-02-03 08:15:49 +00002164
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002165 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Richard Smithb47c36f2013-11-05 09:12:18 +00002166 return EmitFunctionDeclLValue(*this, E, FD);
John McCallf3a88602011-02-03 08:15:49 +00002167
David Blaikie83d382b2011-09-23 05:06:16 +00002168 llvm_unreachable("Unhandled DeclRefExpr");
Chris Lattnerd7f58862007-06-02 05:24:33 +00002169}
Chris Lattnere47e4402007-06-01 18:02:12 +00002170
Chris Lattner8394d792007-06-05 20:53:16 +00002171LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2172 // __extension__ doesn't affect lvalue-ness.
John McCalle3027922010-08-25 11:45:40 +00002173 if (E->getOpcode() == UO_Extension)
Chris Lattner8394d792007-06-05 20:53:16 +00002174 return EmitLValue(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002175
Chris Lattner0f398c42008-07-26 22:37:01 +00002176 QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
Chris Lattner595db862007-10-30 22:53:42 +00002177 switch (E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002178 default: llvm_unreachable("Unknown unary operator lvalue!");
John McCalle3027922010-08-25 11:45:40 +00002179 case UO_Deref: {
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002180 QualType T = E->getSubExpr()->getType()->getPointeeType();
2181 assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
Mike Stump4a3999f2009-09-09 13:00:44 +00002182
John McCall7f416cc2015-09-08 08:05:57 +00002183 AlignmentSource AlignSource;
2184 Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &AlignSource);
2185 LValue LV = MakeAddrLValue(Addr, T, AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002186 LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
John McCall8ccfcb52009-09-24 19:53:00 +00002187
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002188 // We should not generate __weak write barrier on indirect reference
2189 // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2190 // But, we continue to generate __strong write barrier on indirect write
2191 // into a pointer to object.
Richard Smith9c6890a2012-11-01 22:30:59 +00002192 if (getLangOpts().ObjC1 &&
2193 getLangOpts().getGC() != LangOptions::NonGC &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002194 LV.isObjCWeak())
Daniel Dunbare50dda92010-08-21 03:22:38 +00002195 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Chris Lattnerab5e0af2009-10-28 17:39:19 +00002196 return LV;
2197 }
John McCalle3027922010-08-25 11:45:40 +00002198 case UO_Real:
2199 case UO_Imag: {
Chris Lattner595db862007-10-30 22:53:42 +00002200 LValue LV = EmitLValue(E->getSubExpr());
John McCalla2342eb2010-12-05 02:00:02 +00002201 assert(LV.isSimple() && "real/imag on non-ordinary l-value");
John McCalla2342eb2010-12-05 02:00:02 +00002202
Richard Smith0b6b8e42012-02-18 20:53:32 +00002203 // __real is valid on scalars. This is a faster way of testing that.
2204 // __imag can only produce an rvalue on scalars.
2205 if (E->getOpcode() == UO_Real &&
John McCall7f416cc2015-09-08 08:05:57 +00002206 !LV.getAddress().getElementType()->isStructTy()) {
John McCalla2342eb2010-12-05 02:00:02 +00002207 assert(E->getSubExpr()->getType()->isArithmeticType());
2208 return LV;
2209 }
2210
2211 assert(E->getSubExpr()->getType()->isAnyComplexType());
2212
John McCall7f416cc2015-09-08 08:05:57 +00002213 Address Component =
2214 (E->getOpcode() == UO_Real
2215 ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2216 : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
2217 return MakeAddrLValue(Component, ExprTy, LV.getAlignmentSource());
Chris Lattner595db862007-10-30 22:53:42 +00002218 }
John McCalle3027922010-08-25 11:45:40 +00002219 case UO_PreInc:
2220 case UO_PreDec: {
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002221 LValue LV = EmitLValue(E->getSubExpr());
John McCalle3027922010-08-25 11:45:40 +00002222 bool isInc = E->getOpcode() == UO_PreInc;
Craig Topper99e79272013-07-26 05:59:26 +00002223
Chris Lattnerbb8976e2010-01-09 21:44:40 +00002224 if (E->getType()->isAnyComplexType())
2225 EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2226 else
2227 EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2228 return LV;
2229 }
Eli Friedmana72bf0f2009-11-09 04:20:47 +00002230 }
Chris Lattner8394d792007-06-05 20:53:16 +00002231}
2232
Chris Lattner4347e3692007-06-06 04:54:52 +00002233LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002234 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
John McCall7f416cc2015-09-08 08:05:57 +00002235 E->getType(), AlignmentSource::Decl);
Chris Lattner4347e3692007-06-06 04:54:52 +00002236}
2237
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002238LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
Daniel Dunbar2e442a02010-08-21 03:15:20 +00002239 return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
John McCall7f416cc2015-09-08 08:05:57 +00002240 E->getType(), AlignmentSource::Decl);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00002241}
2242
Mike Stump4a3999f2009-09-09 13:00:44 +00002243LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
Alexey Bataevec474782014-10-09 08:45:04 +00002244 auto SL = E->getFunctionName();
2245 assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2246 StringRef FnName = CurFn->getName();
2247 if (FnName.startswith("\01"))
2248 FnName = FnName.substr(1);
2249 StringRef NameItems[] = {
2250 PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2251 std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002252 if (CurCodeDecl && isa<BlockDecl>(CurCodeDecl)) {
John McCall7f416cc2015-09-08 08:05:57 +00002253 auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2254 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian68e79382014-11-14 23:55:27 +00002255 }
Alexey Bataevec474782014-10-09 08:45:04 +00002256 auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
John McCall7f416cc2015-09-08 08:05:57 +00002257 return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
Anders Carlsson625bfc82007-07-21 05:21:51 +00002258}
2259
Richard Smithe30752c2012-10-09 19:52:38 +00002260/// Emit a type description suitable for use by a runtime sanitizer library. The
2261/// format of a type descriptor is
2262///
2263/// \code
Richard Smith683398a2012-10-09 23:55:19 +00002264/// { i16 TypeKind, i16 TypeInfo }
Richard Smithe30752c2012-10-09 19:52:38 +00002265/// \endcode
2266///
Richard Smith683398a2012-10-09 23:55:19 +00002267/// followed by an array of i8 containing the type name. TypeKind is 0 for an
2268/// integer, 1 for a floating point value, and -1 for anything else.
Richard Smithe30752c2012-10-09 19:52:38 +00002269llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
Will Dietz949ec542013-11-08 01:09:22 +00002270 // Only emit each type's descriptor once.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002271 if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
Will Dietz949ec542013-11-08 01:09:22 +00002272 return C;
2273
Richard Smithe30752c2012-10-09 19:52:38 +00002274 uint16_t TypeKind = -1;
2275 uint16_t TypeInfo = 0;
Mike Stump9a4e0122009-12-15 00:59:40 +00002276
Richard Smithe30752c2012-10-09 19:52:38 +00002277 if (T->isIntegerType()) {
2278 TypeKind = 0;
2279 TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
Aaron Ballmanf505d552012-11-30 21:44:01 +00002280 (T->isSignedIntegerType() ? 1 : 0);
Richard Smithe30752c2012-10-09 19:52:38 +00002281 } else if (T->isFloatingType()) {
2282 TypeKind = 1;
2283 TypeInfo = getContext().getTypeSize(T);
2284 }
2285
2286 // Format the type name as if for a diagnostic, including quotes and
2287 // optionally an 'aka'.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002288 SmallString<32> Buffer;
Richard Smithe30752c2012-10-09 19:52:38 +00002289 CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2290 (intptr_t)T.getAsOpaquePtr(),
Craig Topper3aa4fb32014-06-12 05:32:35 +00002291 StringRef(), StringRef(), None, Buffer,
Craig Topper5fc8fc22014-08-27 06:28:36 +00002292 None);
Richard Smithe30752c2012-10-09 19:52:38 +00002293
2294 llvm::Constant *Components[] = {
Richard Smith683398a2012-10-09 23:55:19 +00002295 Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2296 llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
Richard Smithe30752c2012-10-09 19:52:38 +00002297 };
2298 llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2299
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002300 auto *GV = new llvm::GlobalVariable(
2301 CGM.getModule(), Descriptor->getType(),
2302 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
Richard Smithe30752c2012-10-09 19:52:38 +00002303 GV->setUnnamedAddr(true);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002304 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
Will Dietz949ec542013-11-08 01:09:22 +00002305
2306 // Remember the descriptor for this type.
Warren Hunt5c2b4ea2014-05-23 16:07:43 +00002307 CGM.setTypeDescriptorInMap(T, GV);
Will Dietz949ec542013-11-08 01:09:22 +00002308
Richard Smithe30752c2012-10-09 19:52:38 +00002309 return GV;
2310}
2311
2312llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2313 llvm::Type *TargetTy = IntPtrTy;
2314
Richard Smith48366f72013-03-22 00:47:07 +00002315 // Floating-point types which fit into intptr_t are bitcast to integers
2316 // and then passed directly (after zero-extension, if necessary).
2317 if (V->getType()->isFloatingPointTy()) {
2318 unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2319 if (Bits <= TargetTy->getIntegerBitWidth())
2320 V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2321 Bits));
2322 }
2323
Richard Smithe30752c2012-10-09 19:52:38 +00002324 // Integers which fit in intptr_t are zero-extended and passed directly.
2325 if (V->getType()->isIntegerTy() &&
2326 V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2327 return Builder.CreateZExt(V, TargetTy);
2328
2329 // Pointers are passed directly, everything else is passed by address.
2330 if (!V->getType()->isPointerTy()) {
John McCall7f416cc2015-09-08 08:05:57 +00002331 Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
Richard Smithe30752c2012-10-09 19:52:38 +00002332 Builder.CreateStore(V, Ptr);
John McCall7f416cc2015-09-08 08:05:57 +00002333 V = Ptr.getPointer();
Richard Smithe30752c2012-10-09 19:52:38 +00002334 }
2335 return Builder.CreatePtrToInt(V, TargetTy);
2336}
2337
2338/// \brief Emit a representation of a SourceLocation for passing to a handler
2339/// in a sanitizer runtime library. The format for this data is:
2340/// \code
2341/// struct SourceLocation {
2342/// const char *Filename;
2343/// int32_t Line, Column;
2344/// };
2345/// \endcode
2346/// For an invalid SourceLocation, the Filename pointer is null.
2347llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
Alexey Samsonov6c124142014-07-18 17:50:06 +00002348 llvm::Constant *Filename;
2349 int Line, Column;
Richard Smithe30752c2012-10-09 19:52:38 +00002350
Alexey Samsonov6c124142014-07-18 17:50:06 +00002351 PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2352 if (PLoc.isValid()) {
2353 auto FilenameGV = CGM.GetAddrOfConstantCString(PLoc.getFilename(), ".src");
John McCall7f416cc2015-09-08 08:05:57 +00002354 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2355 cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2356 Filename = FilenameGV.getPointer();
Alexey Samsonov6c124142014-07-18 17:50:06 +00002357 Line = PLoc.getLine();
2358 Column = PLoc.getColumn();
2359 } else {
2360 Filename = llvm::Constant::getNullValue(Int8PtrTy);
2361 Line = Column = 0;
2362 }
2363
2364 llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2365 Builder.getInt32(Column)};
Richard Smithe30752c2012-10-09 19:52:38 +00002366
2367 return llvm::ConstantStruct::getAnon(Data);
2368}
2369
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002370namespace {
2371/// \brief Specify under what conditions this check can be recovered
2372enum class CheckRecoverableKind {
Alexey Samsonov88459522015-01-12 22:39:12 +00002373 /// Always terminate program execution if this check fails.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002374 Unrecoverable,
Alexey Samsonov88459522015-01-12 22:39:12 +00002375 /// Check supports recovering, runtime has both fatal (noreturn) and
2376 /// non-fatal handlers for this check.
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002377 Recoverable,
2378 /// Runtime conditionally aborts, always need to support recovery.
2379 AlwaysRecoverable
2380};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002381}
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002382
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002383static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2384 assert(llvm::countPopulation(Kind) == 1);
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002385 switch (Kind) {
2386 case SanitizerKind::Vptr:
2387 return CheckRecoverableKind::AlwaysRecoverable;
2388 case SanitizerKind::Return:
2389 case SanitizerKind::Unreachable:
2390 return CheckRecoverableKind::Unrecoverable;
2391 default:
2392 return CheckRecoverableKind::Recoverable;
2393 }
2394}
2395
Alexey Samsonov88459522015-01-12 22:39:12 +00002396static void emitCheckHandlerCall(CodeGenFunction &CGF,
2397 llvm::FunctionType *FnType,
2398 ArrayRef<llvm::Value *> FnArgs,
2399 StringRef CheckName,
2400 CheckRecoverableKind RecoverKind, bool IsFatal,
2401 llvm::BasicBlock *ContBB) {
2402 assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2403 bool NeedsAbortSuffix =
2404 IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2405 std::string FnName = ("__ubsan_handle_" + CheckName +
2406 (NeedsAbortSuffix ? "_abort" : "")).str();
2407 bool MayReturn =
2408 !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2409
2410 llvm::AttrBuilder B;
2411 if (!MayReturn) {
2412 B.addAttribute(llvm::Attribute::NoReturn)
2413 .addAttribute(llvm::Attribute::NoUnwind);
2414 }
2415 B.addAttribute(llvm::Attribute::UWTable);
2416
2417 llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2418 FnType, FnName,
2419 llvm::AttributeSet::get(CGF.getLLVMContext(),
2420 llvm::AttributeSet::FunctionIndex, B));
2421 llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2422 if (!MayReturn) {
2423 HandlerCall->setDoesNotReturn();
2424 CGF.Builder.CreateUnreachable();
2425 } else {
2426 CGF.Builder.CreateBr(ContBB);
2427 }
2428}
2429
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002430void CodeGenFunction::EmitCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002431 ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002432 StringRef CheckName, ArrayRef<llvm::Constant *> StaticArgs,
2433 ArrayRef<llvm::Value *> DynamicArgs) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002434 assert(IsSanitizerScope);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002435 assert(Checked.size() > 0);
Alexey Samsonov88459522015-01-12 22:39:12 +00002436
2437 llvm::Value *FatalCond = nullptr;
2438 llvm::Value *RecoverableCond = nullptr;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002439 llvm::Value *TrapCond = nullptr;
Alexey Samsonov88459522015-01-12 22:39:12 +00002440 for (int i = 0, n = Checked.size(); i < n; ++i) {
2441 llvm::Value *Check = Checked[i].first;
Peter Collingbourne9881b782015-06-18 23:59:22 +00002442 // -fsanitize-trap= overrides -fsanitize-recover=.
Alexey Samsonov88459522015-01-12 22:39:12 +00002443 llvm::Value *&Cond =
Peter Collingbourne9881b782015-06-18 23:59:22 +00002444 CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2445 ? TrapCond
2446 : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2447 ? RecoverableCond
2448 : FatalCond;
Alexey Samsonov88459522015-01-12 22:39:12 +00002449 Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2450 }
2451
Peter Collingbourne9881b782015-06-18 23:59:22 +00002452 if (TrapCond)
2453 EmitTrapCheck(TrapCond);
2454 if (!FatalCond && !RecoverableCond)
2455 return;
2456
Alexey Samsonov88459522015-01-12 22:39:12 +00002457 llvm::Value *JointCond;
2458 if (FatalCond && RecoverableCond)
2459 JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2460 else
2461 JointCond = FatalCond ? FatalCond : RecoverableCond;
2462 assert(JointCond);
2463
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002464 CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
2465 assert(SanOpts.has(Checked[0].second));
Alexey Samsonov88459522015-01-12 22:39:12 +00002466#ifndef NDEBUG
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002467 for (int i = 1, n = Checked.size(); i < n; ++i) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002468 assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002469 "All recoverable kinds in a single check must be same!");
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002470 assert(SanOpts.has(Checked[i].second));
2471 }
Alexey Samsonov88459522015-01-12 22:39:12 +00002472#endif
Chad Rosierae229d52013-01-29 23:31:22 +00002473
Richard Smith4d1458e2012-09-08 02:08:36 +00002474 llvm::BasicBlock *Cont = createBasicBlock("cont");
Alexey Samsonov88459522015-01-12 22:39:12 +00002475 llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2476 llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002477 // Give hint that we very much don't expect to execute the handler
2478 // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2479 llvm::MDBuilder MDHelper(getLLVMContext());
2480 llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2481 Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
Alexey Samsonov88459522015-01-12 22:39:12 +00002482 EmitBlock(Handlers);
Will Dietzddd282a2012-12-15 01:39:14 +00002483
Alexey Samsonov88459522015-01-12 22:39:12 +00002484 // Emit handler arguments and create handler function type.
Richard Smithe30752c2012-10-09 19:52:38 +00002485 llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002486 auto *InfoPtr =
Will Dietz450f1a12013-01-09 03:39:41 +00002487 new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
Richard Smithe30752c2012-10-09 19:52:38 +00002488 llvm::GlobalVariable::PrivateLinkage, Info);
2489 InfoPtr->setUnnamedAddr(true);
Alexey Samsonov4b8de112014-08-01 21:35:28 +00002490 CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
Richard Smithe30752c2012-10-09 19:52:38 +00002491
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002492 SmallVector<llvm::Value *, 4> Args;
2493 SmallVector<llvm::Type *, 4> ArgTypes;
Richard Smithe30752c2012-10-09 19:52:38 +00002494 Args.reserve(DynamicArgs.size() + 1);
2495 ArgTypes.reserve(DynamicArgs.size() + 1);
2496
2497 // Handler functions take an i8* pointing to the (handler-specific) static
2498 // information block, followed by a sequence of intptr_t arguments
2499 // representing operand values.
2500 Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2501 ArgTypes.push_back(Int8PtrTy);
2502 for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2503 Args.push_back(EmitCheckValue(DynamicArgs[i]));
2504 ArgTypes.push_back(IntPtrTy);
2505 }
2506
2507 llvm::FunctionType *FnType =
2508 llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
Will Dietz88e02332012-12-02 19:50:33 +00002509
Alexey Samsonov88459522015-01-12 22:39:12 +00002510 if (!FatalCond || !RecoverableCond) {
2511 // Simple case: we need to generate a single handler call, either
2512 // fatal, or non-fatal.
2513 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind,
2514 (FatalCond != nullptr), Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002515 } else {
Alexey Samsonov88459522015-01-12 22:39:12 +00002516 // Emit two handler calls: first one for set of unrecoverable checks,
2517 // another one for recoverable.
2518 llvm::BasicBlock *NonFatalHandlerBB =
2519 createBasicBlock("non_fatal." + CheckName);
2520 llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2521 Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2522 EmitBlock(FatalHandlerBB);
2523 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, true,
2524 NonFatalHandlerBB);
2525 EmitBlock(NonFatalHandlerBB);
2526 emitCheckHandlerCall(*this, FnType, Args, CheckName, RecoverKind, false,
2527 Cont);
Richard Smith4d3110a2012-10-25 02:14:12 +00002528 }
Richard Smithe30752c2012-10-09 19:52:38 +00002529
Richard Smith4d1458e2012-09-08 02:08:36 +00002530 EmitBlock(Cont);
Mike Stumpd9546382009-12-12 01:27:46 +00002531}
2532
Chad Rosierae229d52013-01-29 23:31:22 +00002533void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
Richard Smithde670682012-11-01 22:15:34 +00002534 llvm::BasicBlock *Cont = createBasicBlock("cont");
2535
2536 // If we're optimizing, collapse all calls to trap down to just one per
2537 // function to save on code size.
2538 if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
2539 TrapBB = createBasicBlock("trap");
2540 Builder.CreateCondBr(Checked, Cont, TrapBB);
2541 EmitBlock(TrapBB);
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002542 llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
Richard Smithde670682012-11-01 22:15:34 +00002543 TrapCall->setDoesNotReturn();
2544 TrapCall->setDoesNotThrow();
2545 Builder.CreateUnreachable();
2546 } else {
2547 Builder.CreateCondBr(Checked, Cont, TrapBB);
2548 }
2549
2550 EmitBlock(Cont);
2551}
2552
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002553llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
David Blaikie4ba525b2015-07-14 17:27:39 +00002554 llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
Akira Hatanaka85365cd2015-07-02 22:15:41 +00002555
2556 if (!CGM.getCodeGenOpts().TrapFuncName.empty())
2557 TrapCall->addAttribute(llvm::AttributeSet::FunctionIndex,
2558 "trap-func-name",
2559 CGM.getCodeGenOpts().TrapFuncName);
2560
2561 return TrapCall;
2562}
2563
John McCall7f416cc2015-09-08 08:05:57 +00002564Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
2565 AlignmentSource *AlignSource) {
2566 assert(E->getType()->isArrayType() &&
2567 "Array to pointer decay must have array source type!");
2568
2569 // Expressions of array type can't be bitfields or vector elements.
2570 LValue LV = EmitLValue(E);
2571 Address Addr = LV.getAddress();
2572 if (AlignSource) *AlignSource = LV.getAlignmentSource();
2573
2574 // If the array type was an incomplete type, we need to make sure
2575 // the decay ends up being the right type.
2576 llvm::Type *NewTy = ConvertType(E->getType());
2577 Addr = Builder.CreateElementBitCast(Addr, NewTy);
2578
2579 // Note that VLA pointers are always decayed, so we don't need to do
2580 // anything here.
2581 if (!E->getType()->isVariableArrayType()) {
2582 assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
2583 "Expected pointer to array");
2584 Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
2585 }
2586
2587 QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
2588 return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
2589}
2590
Chris Lattner6c5abe82010-06-26 23:03:20 +00002591/// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
2592/// array to pointer, return the array subexpression.
2593static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
2594 // If this isn't just an array->pointer decay, bail out.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002595 const auto *CE = dyn_cast<CastExpr>(E);
Craig Topper8a13c412014-05-21 05:09:00 +00002596 if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
Craig Topper4b566922014-06-09 02:04:02 +00002597 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002598
Chris Lattner6c5abe82010-06-26 23:03:20 +00002599 // If this is a decay from variable width array, bail out.
2600 const Expr *SubExpr = CE->getSubExpr();
2601 if (SubExpr->getType()->isVariableArrayType())
Craig Topper8a13c412014-05-21 05:09:00 +00002602 return nullptr;
Craig Topper99e79272013-07-26 05:59:26 +00002603
Chris Lattner6c5abe82010-06-26 23:03:20 +00002604 return SubExpr;
2605}
2606
John McCall7f416cc2015-09-08 08:05:57 +00002607static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
2608 llvm::Value *ptr,
2609 ArrayRef<llvm::Value*> indices,
2610 bool inbounds,
2611 const llvm::Twine &name = "arrayidx") {
2612 if (inbounds) {
2613 return CGF.Builder.CreateInBoundsGEP(ptr, indices, name);
2614 } else {
2615 return CGF.Builder.CreateGEP(ptr, indices, name);
2616 }
2617}
2618
2619static CharUnits getArrayElementAlign(CharUnits arrayAlign,
2620 llvm::Value *idx,
2621 CharUnits eltSize) {
2622 // If we have a constant index, we can use the exact offset of the
2623 // element we're accessing.
2624 if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
2625 CharUnits offset = constantIdx->getZExtValue() * eltSize;
2626 return arrayAlign.alignmentAtOffset(offset);
2627
2628 // Otherwise, use the worst-case alignment for any element.
2629 } else {
2630 return arrayAlign.alignmentOfArrayElement(eltSize);
2631 }
2632}
2633
2634static QualType getFixedSizeElementType(const ASTContext &ctx,
2635 const VariableArrayType *vla) {
2636 QualType eltType;
2637 do {
2638 eltType = vla->getElementType();
2639 } while ((vla = ctx.getAsVariableArrayType(eltType)));
2640 return eltType;
2641}
2642
2643static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
2644 ArrayRef<llvm::Value*> indices,
2645 QualType eltType, bool inbounds,
2646 const llvm::Twine &name = "arrayidx") {
2647 // All the indices except that last must be zero.
2648#ifndef NDEBUG
2649 for (auto idx : indices.drop_back())
2650 assert(isa<llvm::ConstantInt>(idx) &&
2651 cast<llvm::ConstantInt>(idx)->isZero());
2652#endif
2653
2654 // Determine the element size of the statically-sized base. This is
2655 // the thing that the indices are expressed in terms of.
2656 if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
2657 eltType = getFixedSizeElementType(CGF.getContext(), vla);
2658 }
2659
2660 // We can use that to compute the best alignment of the element.
2661 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
2662 CharUnits eltAlign =
2663 getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
2664
2665 llvm::Value *eltPtr =
2666 emitArraySubscriptGEP(CGF, addr.getPointer(), indices, inbounds, name);
2667 return Address(eltPtr, eltAlign);
2668}
2669
Richard Smith539e4a72013-02-23 02:53:19 +00002670LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
2671 bool Accessed) {
Ted Kremenekc81614d2007-08-20 16:18:38 +00002672 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner2da04b32007-08-24 05:35:26 +00002673 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Eli Friedman07bbeca2009-06-06 19:09:26 +00002674 QualType IdxTy = E->getIdx()->getType();
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002675 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
Eli Friedman07bbeca2009-06-06 19:09:26 +00002676
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002677 if (SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00002678 EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
2679
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002680 // If the base is a vector type, then we are forming a vector element lvalue
2681 // with this subscript.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002682 if (E->getBase()->getType()->isVectorType() &&
2683 !isa<ExtVectorElementExpr>(E->getBase())) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002684 // Emit the vector as an lvalue to get its address.
Eli Friedman327944b2008-06-13 23:01:12 +00002685 LValue LHS = EmitLValue(E->getBase());
Ted Kremenekc81614d2007-08-20 16:18:38 +00002686 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Eli Friedman327944b2008-06-13 23:01:12 +00002687 return LValue::MakeVectorElt(LHS.getAddress(), Idx,
John McCall7f416cc2015-09-08 08:05:57 +00002688 E->getBase()->getType(),
2689 LHS.getAlignmentSource());
Chris Lattner08c4b9f2007-07-10 21:17:59 +00002690 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002691
John McCall7f416cc2015-09-08 08:05:57 +00002692 // All the other cases basically behave like simple offsetting.
2693
Ted Kremenekc81614d2007-08-20 16:18:38 +00002694 // Extend or truncate the index type to 32 or 64-bits.
John McCalle3dc1702011-02-15 09:22:45 +00002695 if (Idx->getType() != IntPtrTy)
2696 Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
Mike Stumpd9546382009-12-12 01:27:46 +00002697
John McCall7f416cc2015-09-08 08:05:57 +00002698 // Handle the extvector case we ignored above.
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002699 if (isa<ExtVectorElementExpr>(E->getBase())) {
2700 LValue LV = EmitLValue(E->getBase());
John McCall7f416cc2015-09-08 08:05:57 +00002701 Address Addr = EmitExtVectorElementLValue(LV);
2702
2703 QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
2704 Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true);
2705 return MakeAddrLValue(Addr, EltType, LV.getAlignmentSource());
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002706 }
John McCall7f416cc2015-09-08 08:05:57 +00002707
2708 AlignmentSource AlignSource;
2709 Address Addr = Address::invalid();
2710 if (const VariableArrayType *vla =
Fariborz Jahanian91b2fa22014-08-19 17:17:40 +00002711 getContext().getAsVariableArrayType(E->getType())) {
John McCall23c29fe2011-06-24 21:55:10 +00002712 // The base must be a pointer, which is not an aggregate. Emit
2713 // it. It needs to be emitted first in case it's what captures
2714 // the VLA bounds.
John McCall7f416cc2015-09-08 08:05:57 +00002715 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00002716
John McCall23c29fe2011-06-24 21:55:10 +00002717 // The element count here is the total number of non-VLA elements.
2718 llvm::Value *numElements = getVLASize(vla).first;
Mike Stump4a3999f2009-09-09 13:00:44 +00002719
John McCall77527a82011-06-25 01:32:37 +00002720 // Effectively, the multiply by the VLA size is part of the GEP.
2721 // GEP indexes are signed, and scaling an index isn't permitted to
2722 // signed-overflow, so we use the same semantics for our explicit
2723 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002724 if (getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00002725 Idx = Builder.CreateMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00002726 } else {
2727 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall77527a82011-06-25 01:32:37 +00002728 }
John McCall7f416cc2015-09-08 08:05:57 +00002729
2730 Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
2731 !getLangOpts().isSignedOverflowDefined());
2732
Chris Lattner6c5abe82010-06-26 23:03:20 +00002733 } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
2734 // Indexing over an interface, as in "NSString *P; P[4];"
John McCall7f416cc2015-09-08 08:05:57 +00002735 CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
2736 llvm::Value *InterfaceSizeVal =
2737 llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());;
Mike Stump4a3999f2009-09-09 13:00:44 +00002738
John McCall7f416cc2015-09-08 08:05:57 +00002739 llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002740
John McCall7f416cc2015-09-08 08:05:57 +00002741 // Emit the base pointer.
2742 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
2743
2744 // We don't necessarily build correct LLVM struct types for ObjC
2745 // interfaces, so we can't rely on GEP to do this scaling
2746 // correctly, so we need to cast to i8*. FIXME: is this actually
2747 // true? A lot of other things in the fragile ABI would break...
2748 llvm::Type *OrigBaseTy = Addr.getType();
2749 Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
2750
2751 // Do the GEP.
2752 CharUnits EltAlign =
2753 getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
2754 llvm::Value *EltPtr =
2755 emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false);
2756 Addr = Address(EltPtr, EltAlign);
2757
2758 // Cast back.
2759 Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
Chris Lattner6c5abe82010-06-26 23:03:20 +00002760 } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
2761 // If this is A[i] where A is an array, the frontend will have decayed the
2762 // base to be a ArrayToPointerDecay implicit cast. While correct, it is
2763 // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
2764 // "gep x, i" here. Emit one "gep A, 0, i".
2765 assert(Array->getType()->isArrayType() &&
2766 "Array to pointer decay must have array source type!");
Richard Smith539e4a72013-02-23 02:53:19 +00002767 LValue ArrayLV;
2768 // For simple multidimensional array indexing, set the 'accessed' flag for
2769 // better bounds-checking of the base expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00002770 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
Richard Smith539e4a72013-02-23 02:53:19 +00002771 ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
2772 else
2773 ArrayLV = EmitLValue(Array);
Craig Topper99e79272013-07-26 05:59:26 +00002774
Daniel Dunbar82634272011-04-01 00:49:43 +00002775 // Propagate the alignment from the array itself to the result.
John McCall7f416cc2015-09-08 08:05:57 +00002776 Addr = emitArraySubscriptGEP(*this, ArrayLV.getAddress(),
2777 {CGM.getSize(CharUnits::Zero()), Idx},
2778 E->getType(),
2779 !getLangOpts().isSignedOverflowDefined());
2780 AlignSource = ArrayLV.getAlignmentSource();
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002781 } else {
John McCall7f416cc2015-09-08 08:05:57 +00002782 // The base must be a pointer; emit it with an estimate of its alignment.
2783 Addr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
2784 Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
2785 !getLangOpts().isSignedOverflowDefined());
Anders Carlsson3d312f82008-12-21 00:11:23 +00002786 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002787
John McCall7f416cc2015-09-08 08:05:57 +00002788 LValue LV = MakeAddrLValue(Addr, E->getType(), AlignSource);
Mike Stump4a3999f2009-09-09 13:00:44 +00002789
John McCall7f416cc2015-09-08 08:05:57 +00002790 // TODO: Preserve/extend path TBAA metadata?
John McCall8ccfcb52009-09-24 19:53:00 +00002791
Richard Smith9c6890a2012-11-01 22:30:59 +00002792 if (getLangOpts().ObjC1 &&
2793 getLangOpts().getGC() != LangOptions::NonGC) {
Daniel Dunbare50dda92010-08-21 03:22:38 +00002794 LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
Fariborz Jahaniana7fa6be2009-09-16 21:37:16 +00002795 setObjCGCLValueClass(getContext(), E, LV);
2796 }
Fariborz Jahaniana9fecf32009-02-21 23:37:19 +00002797 return LV;
Chris Lattnerd9d2fb12007-06-08 23:31:14 +00002798}
2799
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002800LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
2801 bool IsLowerBound) {
2802 LValue Base;
2803 if (auto *ASE =
2804 dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
2805 Base = EmitOMPArraySectionExpr(ASE, IsLowerBound);
2806 else
2807 Base = EmitLValue(E->getBase());
2808 QualType BaseTy = Base.getType();
2809 llvm::Value *Idx = nullptr;
2810 QualType ResultExprTy;
2811 if (auto *AT = getContext().getAsArrayType(BaseTy))
2812 ResultExprTy = AT->getElementType();
2813 else
2814 ResultExprTy = BaseTy->getPointeeType();
2815 if (IsLowerBound || (!IsLowerBound && E->getColonLoc().isInvalid())) {
2816 // Requesting lower bound or upper bound, but without provided length and
2817 // without ':' symbol for the default length -> length = 1.
2818 // Idx = LowerBound ?: 0;
2819 if (auto *LowerBound = E->getLowerBound()) {
2820 Idx = Builder.CreateIntCast(
2821 EmitScalarExpr(LowerBound), IntPtrTy,
2822 LowerBound->getType()->hasSignedIntegerRepresentation());
2823 } else
2824 Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
2825 } else {
2826 // Try to emit length or lower bound as constant. If this is possible, 1 is
2827 // subtracted from constant length or lower bound. Otherwise, emit LLVM IR
2828 // (LB + Len) - 1.
2829 auto &C = CGM.getContext();
2830 auto *Length = E->getLength();
2831 llvm::APSInt ConstLength;
2832 if (Length) {
2833 // Idx = LowerBound + Length - 1;
2834 if (Length->isIntegerConstantExpr(ConstLength, C)) {
2835 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
2836 Length = nullptr;
2837 }
2838 auto *LowerBound = E->getLowerBound();
2839 llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
2840 if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
2841 ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
2842 LowerBound = nullptr;
2843 }
2844 if (!Length)
2845 --ConstLength;
2846 else if (!LowerBound)
2847 --ConstLowerBound;
2848
2849 if (Length || LowerBound) {
2850 auto *LowerBoundVal =
2851 LowerBound
2852 ? Builder.CreateIntCast(
2853 EmitScalarExpr(LowerBound), IntPtrTy,
2854 LowerBound->getType()->hasSignedIntegerRepresentation())
2855 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
2856 auto *LengthVal =
2857 Length
2858 ? Builder.CreateIntCast(
2859 EmitScalarExpr(Length), IntPtrTy,
2860 Length->getType()->hasSignedIntegerRepresentation())
2861 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
2862 Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
2863 /*HasNUW=*/false,
2864 !getLangOpts().isSignedOverflowDefined());
2865 if (Length && LowerBound) {
2866 Idx = Builder.CreateSub(
2867 Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
2868 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
2869 }
2870 } else
2871 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
2872 } else {
2873 // Idx = ArraySize - 1;
2874 if (auto *VAT = C.getAsVariableArrayType(BaseTy)) {
2875 Length = VAT->getSizeExpr();
2876 if (Length->isIntegerConstantExpr(ConstLength, C))
2877 Length = nullptr;
2878 } else {
2879 auto *CAT = C.getAsConstantArrayType(BaseTy);
2880 ConstLength = CAT->getSize();
2881 }
2882 if (Length) {
2883 auto *LengthVal = Builder.CreateIntCast(
2884 EmitScalarExpr(Length), IntPtrTy,
2885 Length->getType()->hasSignedIntegerRepresentation());
2886 Idx = Builder.CreateSub(
2887 LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
2888 /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
2889 } else {
2890 ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
2891 --ConstLength;
2892 Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
2893 }
2894 }
2895 }
2896 assert(Idx);
2897
John McCall7f416cc2015-09-08 08:05:57 +00002898 llvm::Value *EltPtr;
2899 QualType FixedSizeEltType = ResultExprTy;
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002900 if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
2901 // The element count here is the total number of non-VLA elements.
2902 llvm::Value *numElements = getVLASize(VLA).first;
John McCall7f416cc2015-09-08 08:05:57 +00002903 FixedSizeEltType = getFixedSizeElementType(getContext(), VLA);
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002904
2905 // Effectively, the multiply by the VLA size is part of the GEP.
2906 // GEP indexes are signed, and scaling an index isn't permitted to
2907 // signed-overflow, so we use the same semantics for our explicit
2908 // multiply. We suppress this if overflow is not undefined behavior.
2909 if (getLangOpts().isSignedOverflowDefined()) {
2910 Idx = Builder.CreateMul(Idx, numElements);
John McCall7f416cc2015-09-08 08:05:57 +00002911 EltPtr = Builder.CreateGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002912 } else {
2913 Idx = Builder.CreateNSWMul(Idx, numElements);
John McCall7f416cc2015-09-08 08:05:57 +00002914 EltPtr = Builder.CreateInBoundsGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002915 }
2916 } else if (BaseTy->isConstantArrayType()) {
John McCall7f416cc2015-09-08 08:05:57 +00002917 llvm::Value *ArrayPtr = Base.getPointer();
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002918 llvm::Value *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
2919 llvm::Value *Args[] = {Zero, Idx};
2920
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002921 if (getLangOpts().isSignedOverflowDefined())
John McCall7f416cc2015-09-08 08:05:57 +00002922 EltPtr = Builder.CreateGEP(ArrayPtr, Args, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002923 else
John McCall7f416cc2015-09-08 08:05:57 +00002924 EltPtr = Builder.CreateInBoundsGEP(ArrayPtr, Args, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002925 } else {
2926 // The base must be a pointer, which is not an aggregate. Emit it.
2927 if (getLangOpts().isSignedOverflowDefined())
John McCall7f416cc2015-09-08 08:05:57 +00002928 EltPtr = Builder.CreateGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002929 else
John McCall7f416cc2015-09-08 08:05:57 +00002930 EltPtr = Builder.CreateInBoundsGEP(Base.getPointer(), Idx, "arrayidx");
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002931 }
2932
John McCall7f416cc2015-09-08 08:05:57 +00002933 CharUnits EltAlign =
2934 Base.getAlignment().alignmentOfArrayElement(
2935 getContext().getTypeSizeInChars(FixedSizeEltType));
2936
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002937 // Limit the alignment to that of the result type.
John McCall7f416cc2015-09-08 08:05:57 +00002938 LValue LV = MakeAddrLValue(Address(EltPtr, EltAlign), ResultExprTy,
2939 Base.getAlignmentSource());
Alexey Bataevd6fdc8b2015-08-31 07:32:19 +00002940
2941 LV.getQuals().setAddressSpace(BaseTy.getAddressSpace());
2942
2943 return LV;
2944}
2945
Chris Lattner9e751ca2007-08-02 23:37:31 +00002946LValue CodeGenFunction::
Nate Begemance4d7fc2008-04-18 23:10:10 +00002947EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +00002948 // Emit the base vector as an l-value.
Chris Lattner6c7ce102009-02-16 21:11:58 +00002949 LValue Base;
2950
2951 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
Chris Lattner4e1a3232009-12-23 21:31:11 +00002952 if (E->isArrow()) {
2953 // If it is a pointer to a vector, emit the address and form an lvalue with
2954 // it.
John McCall7f416cc2015-09-08 08:05:57 +00002955 AlignmentSource AlignSource;
2956 Address Ptr = EmitPointerWithAlignment(E->getBase(), &AlignSource);
Chris Lattner4e1a3232009-12-23 21:31:11 +00002957 const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
John McCall7f416cc2015-09-08 08:05:57 +00002958 Base = MakeAddrLValue(Ptr, PT->getPointeeType(), AlignSource);
Daniel Dunbarf166a522010-08-21 03:44:13 +00002959 Base.getQuals().removeObjCGCAttr();
John McCall086a4642010-11-24 05:12:34 +00002960 } else if (E->getBase()->isGLValue()) {
Chris Lattner4e1a3232009-12-23 21:31:11 +00002961 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
2962 // emit the base as an lvalue.
2963 assert(E->getBase()->getType()->isVectorType());
2964 Base = EmitLValue(E->getBase());
2965 } else {
2966 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
John McCall1553b192011-06-16 04:16:24 +00002967 assert(E->getBase()->getType()->isVectorType() &&
Daniel Dunbar5b901952010-01-04 18:02:28 +00002968 "Result must be a vector");
Chris Lattner4e1a3232009-12-23 21:31:11 +00002969 llvm::Value *Vec = EmitScalarExpr(E->getBase());
Craig Topper99e79272013-07-26 05:59:26 +00002970
Chris Lattnerf0a9ba32009-12-23 21:33:41 +00002971 // Store the vector to memory (because LValue wants an address).
John McCall7f416cc2015-09-08 08:05:57 +00002972 Address VecMem = CreateMemTemp(E->getBase()->getType());
Chris Lattner4e1a3232009-12-23 21:31:11 +00002973 Builder.CreateStore(Vec, VecMem);
John McCall7f416cc2015-09-08 08:05:57 +00002974 Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
2975 AlignmentSource::Decl);
Chris Lattner4e1a3232009-12-23 21:31:11 +00002976 }
John McCall1553b192011-06-16 04:16:24 +00002977
2978 QualType type =
2979 E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
Craig Topper99e79272013-07-26 05:59:26 +00002980
Nate Begemand3862152008-05-13 21:03:02 +00002981 // Encode the element access list into a vector of unsigned indices.
Benjamin Kramer99383102015-07-28 16:25:32 +00002982 SmallVector<uint32_t, 4> Indices;
Nate Begemand3862152008-05-13 21:03:02 +00002983 E->getEncodedElementAccess(Indices);
2984
2985 if (Base.isSimple()) {
Benjamin Kramer99383102015-07-28 16:25:32 +00002986 llvm::Constant *CV =
2987 llvm::ConstantDataVector::get(getLLVMContext(), Indices);
Eli Friedman610bb872012-03-22 22:36:39 +00002988 return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
John McCall7f416cc2015-09-08 08:05:57 +00002989 Base.getAlignmentSource());
Nate Begemand3862152008-05-13 21:03:02 +00002990 }
2991 assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
2992
2993 llvm::Constant *BaseElts = Base.getExtVectorElts();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002994 SmallVector<llvm::Constant *, 4> CElts;
Nate Begemand3862152008-05-13 21:03:02 +00002995
Chris Lattner595ba3a2012-01-30 06:20:36 +00002996 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
2997 CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
Chris Lattner91c08ad2011-02-15 00:14:06 +00002998 llvm::Constant *CV = llvm::ConstantVector::get(CElts);
John McCall7f416cc2015-09-08 08:05:57 +00002999 return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3000 Base.getAlignmentSource());
Chris Lattner9e751ca2007-08-02 23:37:31 +00003001}
3002
Devang Patel30efa2e2007-10-23 20:28:39 +00003003LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
Devang Pateld68df202007-10-24 22:26:28 +00003004 Expr *BaseExpr = E->getBase();
Eli Friedman327944b2008-06-13 23:01:12 +00003005
Chris Lattner4e4186b2007-12-02 18:52:07 +00003006 // 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 +00003007 LValue BaseLV;
Richard Smith69d0d262012-08-24 00:54:33 +00003008 if (E->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00003009 AlignmentSource AlignSource;
3010 Address Addr = EmitPointerWithAlignment(BaseExpr, &AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003011 QualType PtrTy = BaseExpr->getType()->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003012 EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy);
3013 BaseLV = MakeAddrLValue(Addr, PtrTy, AlignSource);
Richard Smith69d0d262012-08-24 00:54:33 +00003014 } else
Richard Smith4d1458e2012-09-08 02:08:36 +00003015 BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
Devang Patel30efa2e2007-10-23 20:28:39 +00003016
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003017 NamedDecl *ND = E->getMemberDecl();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003018 if (auto *Field = dyn_cast<FieldDecl>(ND)) {
Eli Friedman7f1ff602012-04-16 03:54:45 +00003019 LValue LV = EmitLValueForField(BaseLV, Field);
Anders Carlssonea4c30b2009-11-07 23:06:58 +00003020 setObjCGCLValueClass(getContext(), E, LV);
3021 return LV;
3022 }
Craig Topper99e79272013-07-26 05:59:26 +00003023
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003024 if (auto *VD = dyn_cast<VarDecl>(ND))
Anders Carlsson5bbdc9f2009-11-07 23:16:50 +00003025 return EmitGlobalVarDeclLValue(*this, E, VD);
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003026
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003027 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
Eli Friedmand15eb34d2009-11-26 06:08:14 +00003028 return EmitFunctionDeclLValue(*this, E, FD);
3029
David Blaikie83d382b2011-09-23 05:06:16 +00003030 llvm_unreachable("Unhandled member declaration!");
Eli Friedmana62f3e12008-02-09 08:50:58 +00003031}
Devang Patel30efa2e2007-10-23 20:28:39 +00003032
John McCalldec348f72013-05-03 07:33:41 +00003033/// Given that we are currently emitting a lambda, emit an l-value for
3034/// one of its members.
3035LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3036 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3037 assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3038 QualType LambdaTagType =
3039 getContext().getTagDeclType(Field->getParent());
3040 LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3041 return EmitLValueForField(LambdaLV, Field);
3042}
3043
John McCall7f416cc2015-09-08 08:05:57 +00003044/// Drill down to the storage of a field without walking into
3045/// reference types.
3046///
3047/// The resulting address doesn't necessarily have the right type.
3048static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3049 const FieldDecl *field) {
3050 const RecordDecl *rec = field->getParent();
3051
3052 unsigned idx =
3053 CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3054
3055 CharUnits offset;
3056 // Adjust the alignment down to the given offset.
3057 // As a special case, if the LLVM field index is 0, we know that this
3058 // is zero.
3059 assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3060 .getFieldOffset(field->getFieldIndex()) == 0) &&
3061 "LLVM field at index zero had non-zero offset?");
3062 if (idx != 0) {
3063 auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3064 auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3065 offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3066 }
3067
3068 return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3069}
3070
Eli Friedman7f1ff602012-04-16 03:54:45 +00003071LValue CodeGenFunction::EmitLValueForField(LValue base,
3072 const FieldDecl *field) {
John McCall7f416cc2015-09-08 08:05:57 +00003073 AlignmentSource fieldAlignSource =
3074 getFieldAlignmentSource(base.getAlignmentSource());
3075
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003076 if (field->isBitField()) {
3077 const CGRecordLayout &RL =
3078 CGM.getTypes().getCGRecordLayout(field->getParent());
3079 const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
John McCall7f416cc2015-09-08 08:05:57 +00003080 Address Addr = base.getAddress();
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003081 unsigned Idx = RL.getLLVMFieldNo(field);
3082 if (Idx != 0)
3083 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003084 Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3085 field->getName());
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003086 // Get the access type.
John McCall7f416cc2015-09-08 08:05:57 +00003087 llvm::Type *FieldIntTy =
3088 llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3089 if (Addr.getElementType() != FieldIntTy)
3090 Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
Chandler Carruthff0e3a12012-12-06 11:14:44 +00003091
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003092 QualType fieldType =
3093 field->getType().withCVRQualifiers(base.getVRQualifiers());
John McCall7f416cc2015-09-08 08:05:57 +00003094 return LValue::MakeBitfield(Addr, Info, fieldType, fieldAlignSource);
Eli Friedmanc24e2fb2012-06-27 21:19:48 +00003095 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003096
John McCall53fcbd22011-02-26 08:07:02 +00003097 const RecordDecl *rec = field->getParent();
3098 QualType type = field->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003099
John McCall53fcbd22011-02-26 08:07:02 +00003100 bool mayAlias = rec->hasAttr<MayAliasAttr>();
3101
John McCall7f416cc2015-09-08 08:05:57 +00003102 Address addr = base.getAddress();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003103 unsigned cvr = base.getVRQualifiers();
Manman Renc451e572013-04-04 21:53:22 +00003104 bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
John McCall53fcbd22011-02-26 08:07:02 +00003105 if (rec->isUnion()) {
Chris Lattner13ee4f42011-07-10 05:34:54 +00003106 // For unions, there is no pointer adjustment.
John McCall53fcbd22011-02-26 08:07:02 +00003107 assert(!type->isReferenceType() && "union has reference member");
Manman Renc451e572013-04-04 21:53:22 +00003108 // TODO: handle path-aware TBAA for union.
3109 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003110 } else {
3111 // For structs, we GEP to the field that the record layout suggests.
John McCall7f416cc2015-09-08 08:05:57 +00003112 addr = emitAddrOfFieldStorage(*this, addr, field);
John McCall53fcbd22011-02-26 08:07:02 +00003113
3114 // If this is a reference field, load the reference right now.
3115 if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3116 llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3117 if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3118
Manman Renc451e572013-04-04 21:53:22 +00003119 // Loading the reference will disable path-aware TBAA.
3120 TBAAPath = false;
John McCall53fcbd22011-02-26 08:07:02 +00003121 if (CGM.shouldUseTBAA()) {
3122 llvm::MDNode *tbaa;
3123 if (mayAlias)
3124 tbaa = CGM.getTBAAInfo(getContext().CharTy);
3125 else
3126 tbaa = CGM.getTBAAInfo(type);
Manman Ren4f755de2013-10-08 00:08:49 +00003127 if (tbaa)
Piotr Padlewski4b1ac722015-09-15 21:46:55 +00003128 CGM.DecorateInstructionWithTBAA(load, tbaa);
John McCall53fcbd22011-02-26 08:07:02 +00003129 }
3130
John McCall53fcbd22011-02-26 08:07:02 +00003131 mayAlias = false;
3132 type = refType->getPointeeType();
John McCall7f416cc2015-09-08 08:05:57 +00003133
3134 CharUnits alignment =
3135 getNaturalTypeAlignment(type, &fieldAlignSource, /*pointee*/ true);
3136 addr = Address(load, alignment);
3137
3138 // Qualifiers on the struct don't apply to the referencee, and
3139 // we'll pick up CVR from the actual type later, so reset these
3140 // additional qualifiers now.
3141 cvr = 0;
John McCall53fcbd22011-02-26 08:07:02 +00003142 }
Devang Pateled93c3c2007-10-26 19:42:18 +00003143 }
Craig Topper99e79272013-07-26 05:59:26 +00003144
Chris Lattner13ee4f42011-07-10 05:34:54 +00003145 // Make sure that the address is pointing to the right type. This is critical
3146 // for both unions and structs. A union needs a bitcast, a struct element
3147 // will need a bitcast if the LLVM type laid out doesn't match the desired
3148 // type.
John McCall7f416cc2015-09-08 08:05:57 +00003149 addr = Builder.CreateElementBitCast(addr,
3150 CGM.getTypes().ConvertTypeForMem(type),
3151 field->getName());
John McCall8ccfcb52009-09-24 19:53:00 +00003152
Julien Lerouge5a6b6982011-09-09 22:41:49 +00003153 if (field->hasAttr<AnnotateAttr>())
3154 addr = EmitFieldAnnotations(field, addr);
3155
John McCall7f416cc2015-09-08 08:05:57 +00003156 LValue LV = MakeAddrLValue(addr, type, fieldAlignSource);
John McCall53fcbd22011-02-26 08:07:02 +00003157 LV.getQuals().addCVRQualifiers(cvr);
Manman Renc451e572013-04-04 21:53:22 +00003158 if (TBAAPath) {
3159 const ASTRecordLayout &Layout =
3160 getContext().getASTRecordLayout(field->getParent());
3161 // Set the base type to be the base type of the base LValue and
3162 // update offset to be relative to the base type.
Manman Ren0e521662013-04-27 00:39:37 +00003163 LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
3164 LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
Manman Renc451e572013-04-04 21:53:22 +00003165 Layout.getFieldOffset(field->getFieldIndex()) /
3166 getContext().getCharWidth());
3167 }
Daniel Dunbarf166a522010-08-21 03:44:13 +00003168
Fariborz Jahanian38c3ae92009-09-21 18:54:29 +00003169 // __weak attribute on a field is ignored.
Daniel Dunbarf166a522010-08-21 03:44:13 +00003170 if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3171 LV.getQuals().removeObjCGCAttr();
John McCall53fcbd22011-02-26 08:07:02 +00003172
3173 // Fields of may_alias structs act like 'char' for TBAA purposes.
3174 // FIXME: this should get propagated down through anonymous structs
3175 // and unions.
3176 if (mayAlias && LV.getTBAAInfo())
3177 LV.setTBAAInfo(CGM.getTBAAInfo(getContext().CharTy));
3178
Daniel Dunbarf166a522010-08-21 03:44:13 +00003179 return LV;
Devang Patel30efa2e2007-10-23 20:28:39 +00003180}
3181
Craig Topper99e79272013-07-26 05:59:26 +00003182LValue
3183CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
Eli Friedman7f1ff602012-04-16 03:54:45 +00003184 const FieldDecl *Field) {
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003185 QualType FieldType = Field->getType();
Craig Topper99e79272013-07-26 05:59:26 +00003186
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003187 if (!FieldType->isReferenceType())
Eli Friedman7f1ff602012-04-16 03:54:45 +00003188 return EmitLValueForField(Base, Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003189
John McCall7f416cc2015-09-08 08:05:57 +00003190 Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003191
John McCall7f416cc2015-09-08 08:05:57 +00003192 // Make sure that the address is pointing to the right type.
Chris Lattner2192fe52011-07-18 04:24:23 +00003193 llvm::Type *llvmType = ConvertTypeForMem(FieldType);
John McCall7f416cc2015-09-08 08:05:57 +00003194 V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
Eli Friedman7f1ff602012-04-16 03:54:45 +00003195
John McCall7f416cc2015-09-08 08:05:57 +00003196 // TODO: access-path TBAA?
3197 auto FieldAlignSource = getFieldAlignmentSource(Base.getAlignmentSource());
3198 return MakeAddrLValue(V, FieldType, FieldAlignSource);
Anders Carlssondb78f0a2010-01-29 05:24:29 +00003199}
3200
Chris Lattnerf53c0962010-09-06 00:11:41 +00003201LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
Richard Smith2d988f02011-11-22 22:48:32 +00003202 if (E->isFileScope()) {
John McCall7f416cc2015-09-08 08:05:57 +00003203 ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3204 return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
Richard Smith2d988f02011-11-22 22:48:32 +00003205 }
Fariborz Jahanian5d53fcd2012-06-07 18:15:55 +00003206 if (E->getType()->isVariablyModifiedType())
3207 // make sure to emit the VLA size.
3208 EmitVariablyModifiedType(E->getType());
Craig Topper99e79272013-07-26 05:59:26 +00003209
John McCall7f416cc2015-09-08 08:05:57 +00003210 Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
Chris Lattnerf53c0962010-09-06 00:11:41 +00003211 const Expr *InitExpr = E->getInitializer();
John McCall7f416cc2015-09-08 08:05:57 +00003212 LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003213
Chad Rosier615ed1a2012-03-29 17:37:10 +00003214 EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3215 /*Init*/ true);
Eli Friedman9fd8b682008-05-13 23:18:27 +00003216
3217 return Result;
3218}
3219
Richard Smithbb653bd2012-05-14 21:57:21 +00003220LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3221 if (!E->isGLValue())
3222 // Initializing an aggregate temporary in C++11: T{...}.
3223 return EmitAggExprToLValue(E);
3224
3225 // An lvalue initializer list must be initializing a reference.
3226 assert(E->getNumInits() == 1 && "reference init with multiple values");
3227 return EmitLValue(E->getInit(0));
3228}
3229
Richard Smithf3076ff2014-06-20 18:43:47 +00003230/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3231/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3232/// LValue is returned and the current block has been terminated.
3233static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3234 const Expr *Operand) {
3235 if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3236 CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3237 return None;
3238 }
3239
3240 return CGF.EmitLValue(Operand);
3241}
3242
John McCallc07a0c72011-02-17 10:25:35 +00003243LValue CodeGenFunction::
3244EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3245 if (!expr->isGLValue()) {
John McCall0a6bf2e2011-01-26 19:21:13 +00003246 // ?: here should be an aggregate.
John McCall47fb9502013-03-07 21:37:08 +00003247 assert(hasAggregateEvaluationKind(expr->getType()) &&
John McCall0a6bf2e2011-01-26 19:21:13 +00003248 "Unexpected conditional operator!");
John McCallc07a0c72011-02-17 10:25:35 +00003249 return EmitAggExprToLValue(expr);
Anders Carlsson1450adb2009-09-15 16:35:24 +00003250 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003251
Eli Friedman59954892012-01-25 05:04:17 +00003252 OpaqueValueMapping binding(*this, expr);
3253
John McCallc07a0c72011-02-17 10:25:35 +00003254 const Expr *condExpr = expr->getCond();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003255 bool CondExprBool;
3256 if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003257 const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
Chris Lattner41c6ab52011-02-27 23:02:32 +00003258 if (!CondExprBool) std::swap(live, dead);
John McCallc07a0c72011-02-17 10:25:35 +00003259
Justin Bogneref512b92014-01-06 22:27:43 +00003260 if (!ContainsLabel(dead)) {
Justin Bognerea278c32014-01-07 00:20:28 +00003261 // If the true case is live, we need to track its region.
Justin Bogneref512b92014-01-06 22:27:43 +00003262 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003263 incrementProfileCounter(expr);
John McCallc07a0c72011-02-17 10:25:35 +00003264 return EmitLValue(live);
Justin Bogneref512b92014-01-06 22:27:43 +00003265 }
John McCall0a6bf2e2011-01-26 19:21:13 +00003266 }
3267
John McCallc07a0c72011-02-17 10:25:35 +00003268 llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3269 llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3270 llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
John McCall0a6bf2e2011-01-26 19:21:13 +00003271
3272 ConditionalEvaluation eval(*this);
Justin Bogner66242d62015-04-23 23:06:47 +00003273 EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
Craig Topper99e79272013-07-26 05:59:26 +00003274
John McCall0a6bf2e2011-01-26 19:21:13 +00003275 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003276 EmitBlock(lhsBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003277 incrementProfileCounter(expr);
John McCall0a6bf2e2011-01-26 19:21:13 +00003278 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003279 Optional<LValue> lhs =
3280 EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003281 eval.end(*this);
Craig Topper99e79272013-07-26 05:59:26 +00003282
Richard Smithf3076ff2014-06-20 18:43:47 +00003283 if (lhs && !lhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003284 return EmitUnsupportedLValue(expr, "conditional operator");
John McCall0a6bf2e2011-01-26 19:21:13 +00003285
John McCallc07a0c72011-02-17 10:25:35 +00003286 lhsBlock = Builder.GetInsertBlock();
Richard Smithf3076ff2014-06-20 18:43:47 +00003287 if (lhs)
3288 Builder.CreateBr(contBlock);
Craig Topper99e79272013-07-26 05:59:26 +00003289
John McCall0a6bf2e2011-01-26 19:21:13 +00003290 // Any temporaries created here are conditional.
John McCallc07a0c72011-02-17 10:25:35 +00003291 EmitBlock(rhsBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003292 eval.begin(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003293 Optional<LValue> rhs =
3294 EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
John McCall0a6bf2e2011-01-26 19:21:13 +00003295 eval.end(*this);
Richard Smithf3076ff2014-06-20 18:43:47 +00003296 if (rhs && !rhs->isSimple())
John McCallc07a0c72011-02-17 10:25:35 +00003297 return EmitUnsupportedLValue(expr, "conditional operator");
3298 rhsBlock = Builder.GetInsertBlock();
John McCall0a6bf2e2011-01-26 19:21:13 +00003299
John McCallc07a0c72011-02-17 10:25:35 +00003300 EmitBlock(contBlock);
John McCall0a6bf2e2011-01-26 19:21:13 +00003301
Richard Smithf3076ff2014-06-20 18:43:47 +00003302 if (lhs && rhs) {
John McCall7f416cc2015-09-08 08:05:57 +00003303 llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
Richard Smithf3076ff2014-06-20 18:43:47 +00003304 2, "cond-lvalue");
John McCall7f416cc2015-09-08 08:05:57 +00003305 phi->addIncoming(lhs->getPointer(), lhsBlock);
3306 phi->addIncoming(rhs->getPointer(), rhsBlock);
3307 Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3308 AlignmentSource alignSource =
3309 std::max(lhs->getAlignmentSource(), rhs->getAlignmentSource());
3310 return MakeAddrLValue(result, expr->getType(), alignSource);
Richard Smithf3076ff2014-06-20 18:43:47 +00003311 } else {
3312 assert((lhs || rhs) &&
3313 "both operands of glvalue conditional are throw-expressions?");
3314 return lhs ? *lhs : *rhs;
3315 }
Daniel Dunbarbf1fe8c2009-03-24 02:38:23 +00003316}
3317
Richard Smithbb653bd2012-05-14 21:57:21 +00003318/// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3319/// type. If the cast is to a reference, we can have the usual lvalue result,
Mike Stump65511702009-11-16 06:50:58 +00003320/// otherwise if a cast is needed by the code generator in an lvalue context,
3321/// then it must mean that we need the address of an aggregate in order to
Richard Smithbb653bd2012-05-14 21:57:21 +00003322/// access one of its members. This can happen for all the reasons that casts
Mike Stump65511702009-11-16 06:50:58 +00003323/// are permitted with aggregate result, including noop aggregate casts, and
3324/// cast from scalar to union.
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003325LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
Anders Carlssond95f9602009-09-12 16:16:49 +00003326 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00003327 case CK_ToVoid:
John McCalle3027922010-08-25 11:45:40 +00003328 case CK_BitCast:
3329 case CK_ArrayToPointerDecay:
3330 case CK_FunctionToPointerDecay:
3331 case CK_NullToMemberPointer:
John McCalle84af4e2010-11-13 01:35:44 +00003332 case CK_NullToPointer:
John McCalle3027922010-08-25 11:45:40 +00003333 case CK_IntegralToPointer:
3334 case CK_PointerToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003335 case CK_PointerToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003336 case CK_VectorSplat:
3337 case CK_IntegralCast:
John McCall8cb679e2010-11-15 09:13:47 +00003338 case CK_IntegralToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003339 case CK_IntegralToFloating:
3340 case CK_FloatingToIntegral:
John McCall8cb679e2010-11-15 09:13:47 +00003341 case CK_FloatingToBoolean:
John McCalle3027922010-08-25 11:45:40 +00003342 case CK_FloatingCast:
John McCallc5e62b42010-11-13 09:02:35 +00003343 case CK_FloatingRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003344 case CK_FloatingComplexToReal:
3345 case CK_FloatingComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003346 case CK_FloatingComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003347 case CK_FloatingComplexToIntegralComplex:
John McCallc5e62b42010-11-13 09:02:35 +00003348 case CK_IntegralRealToComplex:
John McCalld7646252010-11-14 08:17:51 +00003349 case CK_IntegralComplexToReal:
3350 case CK_IntegralComplexToBoolean:
John McCallc5e62b42010-11-13 09:02:35 +00003351 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00003352 case CK_IntegralComplexToFloatingComplex:
John McCalle3027922010-08-25 11:45:40 +00003353 case CK_DerivedToBaseMemberPointer:
3354 case CK_BaseToDerivedMemberPointer:
3355 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00003356 case CK_ReinterpretMemberPointer:
John McCall31168b02011-06-15 23:02:42 +00003357 case CK_AnyPointerToBlockPointerCast:
John McCall2d637d22011-09-10 06:18:15 +00003358 case CK_ARCProduceObject:
3359 case CK_ARCConsumeObject:
3360 case CK_ARCReclaimReturnedObject:
Craig Topper99e79272013-07-26 05:59:26 +00003361 case CK_ARCExtendBlockObject:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003362 case CK_CopyAndAutoreleaseBlockObject:
David Tweede1468322013-12-11 13:39:46 +00003363 case CK_AddressSpaceConversion:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003364 return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3365
3366 case CK_Dependent:
3367 llvm_unreachable("dependent cast kind in IR gen!");
3368
3369 case CK_BuiltinFnToFnPtr:
3370 llvm_unreachable("builtin functions are handled elsewhere");
3371
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003372 // These are never l-values; just use the aggregate emission code.
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003373 case CK_NonAtomicToAtomic:
3374 case CK_AtomicToNonAtomic:
Eli Friedmanbe4504d2013-07-11 01:32:21 +00003375 return EmitAggExprToLValue(E);
Eli Friedman8c98dff2009-11-16 05:48:01 +00003376
Anders Carlsson8a01a752011-04-11 02:03:26 +00003377 case CK_Dynamic: {
Mike Stump65511702009-11-16 06:50:58 +00003378 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003379 Address V = LV.getAddress();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003380 const auto *DCE = cast<CXXDynamicCastExpr>(E);
John McCall7f416cc2015-09-08 08:05:57 +00003381 return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
Mike Stump65511702009-11-16 06:50:58 +00003382 }
3383
John McCalle3027922010-08-25 11:45:40 +00003384 case CK_ConstructorConversion:
3385 case CK_UserDefinedConversion:
John McCall9320b872011-09-09 05:25:32 +00003386 case CK_CPointerToObjCPointerCast:
3387 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc7ad5c42013-06-28 00:23:34 +00003388 case CK_NoOp:
3389 case CK_LValueToRValue:
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003390 return EmitLValue(E->getSubExpr());
Craig Topper99e79272013-07-26 05:59:26 +00003391
John McCalle3027922010-08-25 11:45:40 +00003392 case CK_UncheckedDerivedToBase:
3393 case CK_DerivedToBase: {
Craig Topper99e79272013-07-26 05:59:26 +00003394 const RecordType *DerivedClassTy =
Anders Carlssond95f9602009-09-12 16:16:49 +00003395 E->getSubExpr()->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003396 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003397
Anders Carlssond95f9602009-09-12 16:16:49 +00003398 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003399 Address This = LV.getAddress();
Craig Topper99e79272013-07-26 05:59:26 +00003400
Anders Carlssond95f9602009-09-12 16:16:49 +00003401 // Perform the derived-to-base conversion
John McCall7f416cc2015-09-08 08:05:57 +00003402 Address Base = GetAddressOfBaseClass(
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00003403 This, DerivedClassDecl, E->path_begin(), E->path_end(),
3404 /*NullCheckValue=*/false, E->getExprLoc());
Craig Topper99e79272013-07-26 05:59:26 +00003405
John McCall7f416cc2015-09-08 08:05:57 +00003406 return MakeAddrLValue(Base, E->getType(), LV.getAlignmentSource());
Anders Carlssond95f9602009-09-12 16:16:49 +00003407 }
John McCalle3027922010-08-25 11:45:40 +00003408 case CK_ToUnion:
Daniel Dunbar9c4e4652010-02-05 20:02:42 +00003409 return EmitAggExprToLValue(E);
John McCalle3027922010-08-25 11:45:40 +00003410 case CK_BaseToDerived: {
Anders Carlsson8c793172009-11-23 17:57:54 +00003411 const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003412 auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
Craig Topper99e79272013-07-26 05:59:26 +00003413
Anders Carlsson8c793172009-11-23 17:57:54 +00003414 LValue LV = EmitLValue(E->getSubExpr());
Richard Smith2c5868c2013-02-13 21:18:23 +00003415
Anders Carlsson8c793172009-11-23 17:57:54 +00003416 // Perform the base-to-derived conversion
John McCall7f416cc2015-09-08 08:05:57 +00003417 Address Derived =
Craig Topper99e79272013-07-26 05:59:26 +00003418 GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
John McCallcf142162010-08-07 06:22:56 +00003419 E->path_begin(), E->path_end(),
3420 /*NullCheckValue=*/false);
Craig Topper99e79272013-07-26 05:59:26 +00003421
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003422 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
3423 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00003424 if (sanitizePerformTypeCheck())
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003425 EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00003426 Derived.getPointer(), E->getType());
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00003427
Peter Collingbourned2926c92015-03-14 02:42:25 +00003428 if (SanOpts.has(SanitizerKind::CFIDerivedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003429 EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
3430 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003431 CFITCK_DerivedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003432
John McCall7f416cc2015-09-08 08:05:57 +00003433 return MakeAddrLValue(Derived, E->getType(), LV.getAlignmentSource());
Eli Friedman8c98dff2009-11-16 05:48:01 +00003434 }
John McCalle3027922010-08-25 11:45:40 +00003435 case CK_LValueBitCast: {
Eli Friedman8c98dff2009-11-16 05:48:01 +00003436 // This must be a reinterpret_cast (or c-style equivalent).
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003437 const auto *CE = cast<ExplicitCastExpr>(E);
Craig Topper99e79272013-07-26 05:59:26 +00003438
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00003439 CGM.EmitExplicitCastExprType(CE, this);
Anders Carlsson50cb3212009-11-14 21:21:42 +00003440 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003441 Address V = Builder.CreateBitCast(LV.getAddress(),
3442 ConvertType(CE->getTypeAsWritten()));
Peter Collingbourned2926c92015-03-14 02:42:25 +00003443
3444 if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
John McCall7f416cc2015-09-08 08:05:57 +00003445 EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
3446 /*MayBeNull=*/false,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00003447 CFITCK_UnrelatedCast, E->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00003448
John McCall7f416cc2015-09-08 08:05:57 +00003449 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Anders Carlsson50cb3212009-11-14 21:21:42 +00003450 }
John McCalle3027922010-08-25 11:45:40 +00003451 case CK_ObjCObjectLValueCast: {
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003452 LValue LV = EmitLValue(E->getSubExpr());
John McCall7f416cc2015-09-08 08:05:57 +00003453 Address V = Builder.CreateElementBitCast(LV.getAddress(),
3454 ConvertType(E->getType()));
3455 return MakeAddrLValue(V, E->getType(), LV.getAlignmentSource());
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003456 }
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00003457 case CK_ZeroToOCLEvent:
3458 llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
Anders Carlssond95f9602009-09-12 16:16:49 +00003459 }
Craig Topper99e79272013-07-26 05:59:26 +00003460
Douglas Gregorcdb466e2010-07-15 18:58:16 +00003461 llvm_unreachable("Unhandled lvalue cast kind?");
Chris Lattner28bcf1a2009-03-18 18:28:57 +00003462}
3463
John McCall1bf58462011-02-16 08:02:54 +00003464LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
John McCall9a549612011-11-08 22:54:08 +00003465 assert(OpaqueValueMappingData::shouldBindAsLValue(e));
John McCallc07a0c72011-02-17 10:25:35 +00003466 return getOpaqueLValueMapping(e);
John McCall1bf58462011-02-16 08:02:54 +00003467}
3468
Eli Friedman7f1ff602012-04-16 03:54:45 +00003469RValue CodeGenFunction::EmitRValueForField(LValue LV,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003470 const FieldDecl *FD,
3471 SourceLocation Loc) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003472 QualType FT = FD->getType();
Eli Friedman7f1ff602012-04-16 03:54:45 +00003473 LValue FieldLV = EmitLValueForField(LV, FD);
John McCall47fb9502013-03-07 21:37:08 +00003474 switch (getEvaluationKind(FT)) {
3475 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003476 return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
John McCall47fb9502013-03-07 21:37:08 +00003477 case TEK_Aggregate:
Eli Friedman7f1ff602012-04-16 03:54:45 +00003478 return FieldLV.asAggregateRValue();
John McCall47fb9502013-03-07 21:37:08 +00003479 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003480 return EmitLoadOfLValue(FieldLV, Loc);
John McCall47fb9502013-03-07 21:37:08 +00003481 }
3482 llvm_unreachable("bad evaluation kind");
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00003483}
Douglas Gregorfe314812011-06-21 17:03:29 +00003484
Chris Lattnere47e4402007-06-01 18:02:12 +00003485//===--------------------------------------------------------------------===//
3486// Expression Emission
3487//===--------------------------------------------------------------------===//
3488
Craig Topper99e79272013-07-26 05:59:26 +00003489RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
Anders Carlsson17490832009-12-24 20:40:36 +00003490 ReturnValueSlot ReturnValue) {
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003491 // Builtins never have block type.
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003492 if (E->getCallee()->getType()->isBlockPointerType())
Anders Carlssonbfb36712009-12-24 21:13:40 +00003493 return EmitBlockCallExpr(E, ReturnValue);
Daniel Dunbarbb197e42009-01-09 16:50:52 +00003494
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003495 if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003496 return EmitCXXMemberCallExpr(CE, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003497
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003498 if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
Peter Collingbournefe883422011-10-06 18:29:37 +00003499 return EmitCUDAKernelCallExpr(CE, ReturnValue);
3500
Douglas Gregore0e96302011-09-06 21:41:04 +00003501 const Decl *TargetDecl = E->getCalleeDecl();
3502 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
3503 if (unsigned builtinID = FD->getBuiltinID())
Peter Collingbournef7706832014-12-12 23:41:25 +00003504 return EmitBuiltinExpr(FD, builtinID, E, ReturnValue);
Daniel Dunbarcdbb5e32009-02-20 18:06:48 +00003505 }
3506
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003507 if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
Anders Carlsson4034a952009-05-27 04:18:27 +00003508 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(TargetDecl))
Anders Carlssonbfb36712009-12-24 21:13:40 +00003509 return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
Mike Stump4a3999f2009-09-09 13:00:44 +00003510
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003511 if (const auto *PseudoDtor =
3512 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee()->IgnoreParens())) {
John McCall31168b02011-06-15 23:02:42 +00003513 QualType DestroyedType = PseudoDtor->getDestroyedType();
Richard Smith9c6890a2012-11-01 22:30:59 +00003514 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003515 DestroyedType->isObjCLifetimeType() &&
3516 (DestroyedType.getObjCLifetime() == Qualifiers::OCL_Strong ||
3517 DestroyedType.getObjCLifetime() == Qualifiers::OCL_Weak)) {
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003518 // Automatic Reference Counting:
3519 // If the pseudo-expression names a retainable object with weak or
3520 // strong lifetime, the object shall be released.
John McCall31168b02011-06-15 23:02:42 +00003521 Expr *BaseExpr = PseudoDtor->getBase();
John McCall7f416cc2015-09-08 08:05:57 +00003522 Address BaseValue = Address::invalid();
John McCall31168b02011-06-15 23:02:42 +00003523 Qualifiers BaseQuals;
Craig Topper99e79272013-07-26 05:59:26 +00003524
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003525 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
John McCall31168b02011-06-15 23:02:42 +00003526 if (PseudoDtor->isArrow()) {
John McCall7f416cc2015-09-08 08:05:57 +00003527 BaseValue = EmitPointerWithAlignment(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00003528 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
3529 BaseQuals = PTy->getPointeeType().getQualifiers();
3530 } else {
3531 LValue BaseLV = EmitLValue(BaseExpr);
John McCall31168b02011-06-15 23:02:42 +00003532 BaseValue = BaseLV.getAddress();
3533 QualType BaseTy = BaseExpr->getType();
3534 BaseQuals = BaseTy.getQualifiers();
3535 }
Craig Topper99e79272013-07-26 05:59:26 +00003536
John McCall31168b02011-06-15 23:02:42 +00003537 switch (PseudoDtor->getDestroyedType().getObjCLifetime()) {
3538 case Qualifiers::OCL_None:
3539 case Qualifiers::OCL_ExplicitNone:
3540 case Qualifiers::OCL_Autoreleasing:
3541 break;
Craig Topper99e79272013-07-26 05:59:26 +00003542
John McCall31168b02011-06-15 23:02:42 +00003543 case Qualifiers::OCL_Strong:
Craig Topper99e79272013-07-26 05:59:26 +00003544 EmitARCRelease(Builder.CreateLoad(BaseValue,
Benjamin Kramerdd19c012011-06-18 10:34:00 +00003545 PseudoDtor->getDestroyedType().isVolatileQualified()),
John McCallcdda29c2013-03-13 03:10:54 +00003546 ARCPreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00003547 break;
3548
3549 case Qualifiers::OCL_Weak:
3550 EmitARCDestroyWeak(BaseValue);
3551 break;
3552 }
3553 } else {
3554 // C++ [expr.pseudo]p1:
3555 // The result shall only be used as the operand for the function call
3556 // operator (), and the result of such a call has type void. The only
3557 // effect is the evaluation of the postfix-expression before the dot or
Craig Topper99e79272013-07-26 05:59:26 +00003558 // arrow.
John McCall31168b02011-06-15 23:02:42 +00003559 EmitScalarExpr(E->getCallee());
3560 }
Craig Topper99e79272013-07-26 05:59:26 +00003561
Craig Topper8a13c412014-05-21 05:09:00 +00003562 return RValue::get(nullptr);
Douglas Gregorad8a3362009-09-04 17:36:40 +00003563 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003564
Chris Lattner2da04b32007-08-24 05:35:26 +00003565 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003566 return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
3567 TargetDecl);
Chris Lattner9e47ead2007-08-31 04:44:06 +00003568}
3569
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003570LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
Chris Lattnere541ea32009-05-12 21:28:12 +00003571 // Comma expressions just emit their LHS then their RHS as an l-value.
John McCalle3027922010-08-25 11:45:40 +00003572 if (E->getOpcode() == BO_Comma) {
John McCalla2342eb2010-12-05 02:00:02 +00003573 EmitIgnoredExpr(E->getLHS());
Eli Friedman5445f6e2009-12-07 20:18:11 +00003574 EnsureInsertPoint();
Chris Lattnere541ea32009-05-12 21:28:12 +00003575 return EmitLValue(E->getRHS());
3576 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003577
John McCalle3027922010-08-25 11:45:40 +00003578 if (E->getOpcode() == BO_PtrMemD ||
3579 E->getOpcode() == BO_PtrMemI)
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003580 return EmitPointerToDataMemberBinaryExpr(E);
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003581
John McCalla2342eb2010-12-05 02:00:02 +00003582 assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
John McCall31168b02011-06-15 23:02:42 +00003583
3584 // Note that in all of these cases, __block variables need the RHS
3585 // evaluated first just in case the variable gets moved by the RHS.
John McCall47fb9502013-03-07 21:37:08 +00003586
3587 switch (getEvaluationKind(E->getType())) {
3588 case TEK_Scalar: {
John McCall31168b02011-06-15 23:02:42 +00003589 switch (E->getLHS()->getType().getObjCLifetime()) {
3590 case Qualifiers::OCL_Strong:
3591 return EmitARCStoreStrong(E, /*ignored*/ false).first;
3592
3593 case Qualifiers::OCL_Autoreleasing:
3594 return EmitARCStoreAutoreleasing(E).first;
3595
3596 // No reason to do any of these differently.
3597 case Qualifiers::OCL_None:
3598 case Qualifiers::OCL_ExplicitNone:
3599 case Qualifiers::OCL_Weak:
3600 break;
3601 }
3602
John McCalld0a30012010-12-06 06:10:02 +00003603 RValue RV = EmitAnyExpr(E->getRHS());
Richard Smithe30752c2012-10-09 19:52:38 +00003604 LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
John McCall55e1fbc2011-06-25 02:11:03 +00003605 EmitStoreThroughLValue(RV, LV);
Anders Carlsson0999aaf2009-10-19 18:28:22 +00003606 return LV;
3607 }
John McCall4f29b492010-11-16 23:07:28 +00003608
John McCall47fb9502013-03-07 21:37:08 +00003609 case TEK_Complex:
John McCall4f29b492010-11-16 23:07:28 +00003610 return EmitComplexAssignmentLValue(E);
3611
John McCall47fb9502013-03-07 21:37:08 +00003612 case TEK_Aggregate:
3613 return EmitAggExprToLValue(E);
3614 }
3615 llvm_unreachable("bad evaluation kind");
Daniel Dunbar8cde00a2008-09-04 03:20:13 +00003616}
3617
Christopher Lambd91c3d42007-12-29 05:02:41 +00003618LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
Christopher Lambd91c3d42007-12-29 05:02:41 +00003619 RValue RV = EmitCallExpr(E);
Anders Carlsson4ae70ff2009-05-27 01:45:47 +00003620
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003621 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00003622 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3623 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00003624
David Majnemerced8bdf2015-02-25 17:36:15 +00003625 assert(E->getCallReturnType(getContext())->isReferenceType() &&
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003626 "Can't have a scalar return unless the return type is a "
3627 "reference type!");
Mike Stump4a3999f2009-09-09 13:00:44 +00003628
John McCall7f416cc2015-09-08 08:05:57 +00003629 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Christopher Lambd91c3d42007-12-29 05:02:41 +00003630}
3631
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003632LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
3633 // FIXME: This shouldn't require another copy.
Daniel Dunbard0bc7b92010-02-05 19:38:31 +00003634 return EmitAggExprToLValue(E);
Daniel Dunbar8d9dc4a2009-02-11 20:59:32 +00003635}
3636
Anders Carlsson3be22e22009-05-30 23:23:33 +00003637LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003638 assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
3639 && "binding l-value to type which needs a temporary");
Benjamin Kramer76399eb2011-09-27 21:06:10 +00003640 AggValueSlot Slot = CreateAggTemp(E->getType());
John McCall7a626f62010-09-15 10:14:12 +00003641 EmitCXXConstructExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003642 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3643 AlignmentSource::Decl);
Anders Carlsson3be22e22009-05-30 23:23:33 +00003644}
3645
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003646LValue
Mike Stumpc9b231c2009-11-15 08:09:41 +00003647CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003648 return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
Mike Stumpc9b231c2009-11-15 08:09:41 +00003649}
3650
John McCall7f416cc2015-09-08 08:05:57 +00003651Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
3652 return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
3653 ConvertType(E->getType()));
Nico Webercf4ff5862012-10-11 10:13:44 +00003654}
3655
3656LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003657 return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
3658 AlignmentSource::Decl);
Nico Webercf4ff5862012-10-11 10:13:44 +00003659}
3660
Mike Stumpc9b231c2009-11-15 08:09:41 +00003661LValue
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003662CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
John McCall8ea46b62010-09-18 00:58:34 +00003663 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
John McCallcac93852011-08-26 08:02:37 +00003664 Slot.setExternallyDestructed();
John McCall8ea46b62010-09-18 00:58:34 +00003665 EmitAggExpr(E->getSubExpr(), Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003666 EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
3667 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3668 AlignmentSource::Decl);
Anders Carlssonfd2af0c2009-05-30 23:30:54 +00003669}
3670
Eli Friedman5bc17122012-02-08 05:34:55 +00003671LValue
3672CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
Eli Friedman5bc17122012-02-08 05:34:55 +00003673 AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
Eli Friedmanc370a7e2012-02-09 03:32:31 +00003674 EmitLambdaExpr(E, Slot);
John McCall7f416cc2015-09-08 08:05:57 +00003675 return MakeAddrLValue(Slot.getAddress(), E->getType(),
3676 AlignmentSource::Decl);
Eli Friedman5bc17122012-02-08 05:34:55 +00003677}
3678
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003679LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003680 RValue RV = EmitObjCMessageExpr(E);
Craig Topper99e79272013-07-26 05:59:26 +00003681
Anders Carlsson280e61f12010-06-21 20:59:55 +00003682 if (!RV.isScalar())
John McCall7f416cc2015-09-08 08:05:57 +00003683 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3684 AlignmentSource::Decl);
Craig Topper99e79272013-07-26 05:59:26 +00003685
Alp Toker314cc812014-01-25 16:55:45 +00003686 assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
Anders Carlsson280e61f12010-06-21 20:59:55 +00003687 "Can't have a scalar return unless the return type is a "
3688 "reference type!");
Craig Topper99e79272013-07-26 05:59:26 +00003689
John McCall7f416cc2015-09-08 08:05:57 +00003690 return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
Daniel Dunbarc8317a42008-08-23 10:51:21 +00003691}
3692
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003693LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003694 Address V =
3695 CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
3696 return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
Fariborz Jahanian9240f3d2010-06-17 19:56:20 +00003697}
3698
Daniel Dunbar722f4242009-04-22 05:08:15 +00003699llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003700 const ObjCIvarDecl *Ivar) {
Fariborz Jahanian21fc74c2009-02-10 19:02:04 +00003701 return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003702}
3703
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003704LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
3705 llvm::Value *BaseValue,
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003706 const ObjCIvarDecl *Ivar,
3707 unsigned CVRQualifiers) {
Chris Lattnerc4688d22009-04-17 17:44:48 +00003708 return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
Daniel Dunbar9ebf9512009-04-21 01:19:28 +00003709 Ivar, CVRQualifiers);
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003710}
3711
3712LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003713 // FIXME: A lot of the code below could be shared with EmitMemberExpr.
Craig Topper8a13c412014-05-21 05:09:00 +00003714 llvm::Value *BaseValue = nullptr;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003715 const Expr *BaseExpr = E->getBase();
John McCall8ccfcb52009-09-24 19:53:00 +00003716 Qualifiers BaseQuals;
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003717 QualType ObjectTy;
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003718 if (E->isArrow()) {
3719 BaseValue = EmitScalarExpr(BaseExpr);
Steve Naroff7cae42b2009-07-10 23:34:53 +00003720 ObjectTy = BaseExpr->getType()->getPointeeType();
John McCall8ccfcb52009-09-24 19:53:00 +00003721 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003722 } else {
3723 LValue BaseLV = EmitLValue(BaseExpr);
John McCall7f416cc2015-09-08 08:05:57 +00003724 BaseValue = BaseLV.getPointer();
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00003725 ObjectTy = BaseExpr->getType();
John McCall8ccfcb52009-09-24 19:53:00 +00003726 BaseQuals = ObjectTy.getQualifiers();
Anders Carlssonc13b85a2008-08-25 01:53:23 +00003727 }
Daniel Dunbar1c64e5d2008-09-24 04:00:38 +00003728
Craig Topper99e79272013-07-26 05:59:26 +00003729 LValue LV =
John McCall8ccfcb52009-09-24 19:53:00 +00003730 EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
3731 BaseQuals.getCVRQualifiers());
Fariborz Jahaniande1d3242009-09-16 23:11:23 +00003732 setObjCGCLValueClass(getContext(), E, LV);
3733 return LV;
Chris Lattner4bd55962008-03-30 23:03:07 +00003734}
3735
Chris Lattnera4185c52009-04-25 19:35:26 +00003736LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
Chris Lattnera4185c52009-04-25 19:35:26 +00003737 // Can only get l-value for message expression returning aggregate type
3738 RValue RV = EmitAnyExprToTemp(E);
John McCall7f416cc2015-09-08 08:05:57 +00003739 return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
3740 AlignmentSource::Decl);
Chris Lattnera4185c52009-04-25 19:35:26 +00003741}
3742
Anders Carlsson0435ed52009-12-24 19:08:58 +00003743RValue CodeGenFunction::EmitCall(QualType CalleeType, llvm::Value *Callee,
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003744 const CallExpr *E, ReturnValueSlot ReturnValue,
Peter Collingbournef7706832014-12-12 23:41:25 +00003745 const Decl *TargetDecl, llvm::Value *Chain) {
Mike Stump4a3999f2009-09-09 13:00:44 +00003746 // Get the actual function type. The callee type will always be a pointer to
3747 // function type or a block pointer type.
3748 assert(CalleeType->isFunctionPointerType() &&
Anders Carlssond8db8532009-04-07 18:53:02 +00003749 "Call must have function pointer type!");
3750
John McCall6fd4c232009-10-23 08:22:42 +00003751 CalleeType = getContext().getCanonicalType(CalleeType);
3752
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003753 const auto *FnType =
3754 cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
Daniel Dunbarc722b852008-08-30 03:02:31 +00003755
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003756 if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003757 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
3758 if (llvm::Constant *PrefixSig =
3759 CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003760 SanitizerScope SanScope(this);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003761 llvm::Constant *FTRTTIConst =
3762 CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
3763 llvm::Type *PrefixStructTyElems[] = {
3764 PrefixSig->getType(),
3765 FTRTTIConst->getType()
3766 };
3767 llvm::StructType *PrefixStructTy = llvm::StructType::get(
3768 CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
3769
3770 llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
3771 Callee, llvm::PointerType::getUnqual(PrefixStructTy));
3772 llvm::Value *CalleeSigPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00003773 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
John McCall7f416cc2015-09-08 08:05:57 +00003774 llvm::Value *CalleeSig =
3775 Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003776 llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
3777
3778 llvm::BasicBlock *Cont = createBasicBlock("cont");
3779 llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
3780 Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
3781
3782 EmitBlock(TypeCheck);
3783 llvm::Value *CalleeRTTIPtr =
David Blaikie17ea2662015-04-04 21:07:17 +00003784 Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
John McCall7f416cc2015-09-08 08:05:57 +00003785 llvm::Value *CalleeRTTI =
3786 Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003787 llvm::Value *CalleeRTTIMatch =
3788 Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
3789 llvm::Constant *StaticData[] = {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00003790 EmitCheckSourceLocation(E->getLocStart()),
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003791 EmitCheckTypeDescriptor(CalleeType)
3792 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003793 EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
3794 "function_type_mismatch", StaticData, Callee);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00003795
3796 Builder.CreateBr(Cont);
3797 EmitBlock(Cont);
3798 }
3799 }
3800
Peter Collingbourne2c7f7e32015-09-10 02:17:40 +00003801 // If we are checking indirect calls and this call is indirect, check that the
3802 // function pointer is a member of the bit set for the function type.
3803 if (SanOpts.has(SanitizerKind::CFIICall) &&
3804 (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
3805 SanitizerScope SanScope(this);
3806
3807 llvm::Value *BitSetName = llvm::MetadataAsValue::get(
3808 getLLVMContext(),
3809 CGM.CreateMetadataIdentifierForType(QualType(FnType, 0)));
3810
3811 llvm::Value *CastedCallee = Builder.CreateBitCast(Callee, Int8PtrTy);
3812 llvm::Value *BitSetTest =
3813 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::bitset_test),
3814 {CastedCallee, BitSetName});
3815
3816 llvm::Constant *StaticData[] = {
3817 EmitCheckSourceLocation(E->getLocStart()),
3818 EmitCheckTypeDescriptor(QualType(FnType, 0)),
3819 };
3820 EmitCheck(std::make_pair(BitSetTest, SanitizerKind::CFIICall),
3821 "cfi_bad_icall", StaticData, CastedCallee);
3822 }
3823
Daniel Dunbarc722b852008-08-30 03:02:31 +00003824 CallArgList Args;
Peter Collingbournef7706832014-12-12 23:41:25 +00003825 if (Chain)
3826 Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
3827 CGM.getContext().VoidPtrTy);
David Blaikief05779e2015-07-21 18:37:18 +00003828 EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
3829 E->getDirectCallee(), /*ParamsToSkip*/ 0);
Daniel Dunbarc722b852008-08-30 03:02:31 +00003830
Peter Collingbournef7706832014-12-12 23:41:25 +00003831 const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
3832 Args, FnType, /*isChainCall=*/Chain);
John McCallcbc038a2011-09-21 08:08:30 +00003833
3834 // C99 6.5.2.2p6:
3835 // If the expression that denotes the called function has a type
3836 // that does not include a prototype, [the default argument
3837 // promotions are performed]. If the number of arguments does not
3838 // equal the number of parameters, the behavior is undefined. If
3839 // the function is defined with a type that includes a prototype,
3840 // and either the prototype ends with an ellipsis (, ...) or the
3841 // types of the arguments after promotion are not compatible with
3842 // the types of the parameters, the behavior is undefined. If the
3843 // function is defined with a type that does not include a
3844 // prototype, and the types of the arguments after promotion are
3845 // not compatible with those of the parameters after promotion,
3846 // the behavior is undefined [except in some trivial cases].
3847 // That is, in the general case, we should assume that a call
3848 // through an unprototyped function type works like a *non-variadic*
3849 // call. The way we make this work is to cast to the exact type
3850 // of the promoted arguments.
Peter Collingbournef7706832014-12-12 23:41:25 +00003851 //
3852 // Chain calls use this same code path to add the invisible chain parameter
3853 // to the function type.
3854 if (isa<FunctionNoProtoType>(FnType) || Chain) {
John McCalla729c622012-02-17 03:33:10 +00003855 llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
John McCallcbc038a2011-09-21 08:08:30 +00003856 CalleeTy = CalleeTy->getPointerTo();
3857 Callee = Builder.CreateBitCast(Callee, CalleeTy, "callee.knr.cast");
3858 }
3859
3860 return EmitCall(FnInfo, Callee, ReturnValue, Args, TargetDecl);
Daniel Dunbar97db84c2008-08-23 03:46:30 +00003861}
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003862
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003863LValue CodeGenFunction::
3864EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
John McCall7f416cc2015-09-08 08:05:57 +00003865 Address BaseAddr = Address::invalid();
3866 if (E->getOpcode() == BO_PtrMemI) {
3867 BaseAddr = EmitPointerWithAlignment(E->getLHS());
3868 } else {
3869 BaseAddr = EmitLValue(E->getLHS()).getAddress();
3870 }
Chris Lattnerab5e0af2009-10-28 17:39:19 +00003871
John McCallc134eb52010-08-31 21:07:20 +00003872 llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
3873
3874 const MemberPointerType *MPT
3875 = E->getRHS()->getType()->getAs<MemberPointerType>();
3876
John McCall7f416cc2015-09-08 08:05:57 +00003877 AlignmentSource AlignSource;
3878 Address MemberAddr =
3879 EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT,
3880 &AlignSource);
John McCallc134eb52010-08-31 21:07:20 +00003881
John McCall7f416cc2015-09-08 08:05:57 +00003882 return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), AlignSource);
Fariborz Jahanianffba6622009-10-22 22:57:31 +00003883}
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003884
John McCall47fb9502013-03-07 21:37:08 +00003885/// Given the address of a temporary variable, produce an r-value of
3886/// its type.
John McCall7f416cc2015-09-08 08:05:57 +00003887RValue CodeGenFunction::convertTempToRValue(Address addr,
Nick Lewycky2d84e842013-10-02 02:29:49 +00003888 QualType type,
3889 SourceLocation loc) {
John McCall7f416cc2015-09-08 08:05:57 +00003890 LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
John McCall47fb9502013-03-07 21:37:08 +00003891 switch (getEvaluationKind(type)) {
3892 case TEK_Complex:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003893 return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00003894 case TEK_Aggregate:
3895 return lvalue.asAggregateRValue();
3896 case TEK_Scalar:
Nick Lewycky2d84e842013-10-02 02:29:49 +00003897 return RValue::get(EmitLoadOfScalar(lvalue, loc));
John McCall47fb9502013-03-07 21:37:08 +00003898 }
3899 llvm_unreachable("bad evaluation kind");
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003900}
3901
Duncan Sandse81111c2012-04-10 08:23:07 +00003902void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003903 assert(Val->getType()->isFPOrFPVectorTy());
Duncan Sandse81111c2012-04-10 08:23:07 +00003904 if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003905 return;
3906
Duncan Sands65229ed2012-04-16 16:29:47 +00003907 llvm::MDBuilder MDHelper(getLLVMContext());
3908 llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003909
Duncan Sands6fc46192012-04-14 12:37:26 +00003910 cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003911}
John McCallfe96e0b2011-11-06 09:01:30 +00003912
3913namespace {
3914 struct LValueOrRValue {
3915 LValue LV;
3916 RValue RV;
3917 };
3918}
3919
3920static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
3921 const PseudoObjectExpr *E,
3922 bool forLValue,
3923 AggValueSlot slot) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003924 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00003925
3926 // Find the result expression, if any.
3927 const Expr *resultExpr = E->getResultExpr();
3928 LValueOrRValue result;
3929
3930 for (PseudoObjectExpr::const_semantics_iterator
3931 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
3932 const Expr *semantic = *i;
3933
3934 // If this semantic expression is an opaque value, bind it
3935 // to the result of its source expression.
Rafael Espindola2ae250c2014-05-09 00:08:36 +00003936 if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
John McCallfe96e0b2011-11-06 09:01:30 +00003937
3938 // If this is the result expression, we may need to evaluate
3939 // directly into the slot.
3940 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
3941 OVMA opaqueData;
3942 if (ov == resultExpr && ov->isRValue() && !forLValue &&
John McCall47fb9502013-03-07 21:37:08 +00003943 CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
John McCallfe96e0b2011-11-06 09:01:30 +00003944 CGF.EmitAggExpr(ov->getSourceExpr(), slot);
3945
John McCall7f416cc2015-09-08 08:05:57 +00003946 LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
3947 AlignmentSource::Decl);
John McCallfe96e0b2011-11-06 09:01:30 +00003948 opaqueData = OVMA::bind(CGF, ov, LV);
3949 result.RV = slot.asRValue();
3950
3951 // Otherwise, emit as normal.
3952 } else {
3953 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
3954
3955 // If this is the result, also evaluate the result now.
3956 if (ov == resultExpr) {
3957 if (forLValue)
3958 result.LV = CGF.EmitLValue(ov);
3959 else
3960 result.RV = CGF.EmitAnyExpr(ov, slot);
3961 }
3962 }
3963
3964 opaques.push_back(opaqueData);
3965
3966 // Otherwise, if the expression is the result, evaluate it
3967 // and remember the result.
3968 } else if (semantic == resultExpr) {
3969 if (forLValue)
3970 result.LV = CGF.EmitLValue(semantic);
3971 else
3972 result.RV = CGF.EmitAnyExpr(semantic, slot);
3973
3974 // Otherwise, evaluate the expression in an ignored context.
3975 } else {
3976 CGF.EmitIgnoredExpr(semantic);
3977 }
3978 }
3979
3980 // Unbind all the opaques now.
3981 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
3982 opaques[i].unbind(CGF);
3983
3984 return result;
3985}
3986
3987RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
3988 AggValueSlot slot) {
3989 return emitPseudoObjectExpr(*this, E, false, slot).RV;
3990}
3991
3992LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
3993 return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
3994}