1*0b57cec5SDimitry Andric //===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // This contains code to emit Expr nodes as LLVM code.
10*0b57cec5SDimitry Andric //
11*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
12*0b57cec5SDimitry Andric 
13fe6060f1SDimitry Andric #include "CGCUDARuntime.h"
14*0b57cec5SDimitry Andric #include "CGCXXABI.h"
15*0b57cec5SDimitry Andric #include "CGCall.h"
16*0b57cec5SDimitry Andric #include "CGCleanup.h"
17*0b57cec5SDimitry Andric #include "CGDebugInfo.h"
18*0b57cec5SDimitry Andric #include "CGObjCRuntime.h"
19*0b57cec5SDimitry Andric #include "CGOpenMPRuntime.h"
20*0b57cec5SDimitry Andric #include "CGRecordLayout.h"
21*0b57cec5SDimitry Andric #include "CodeGenFunction.h"
22*0b57cec5SDimitry Andric #include "CodeGenModule.h"
23*0b57cec5SDimitry Andric #include "ConstantEmitter.h"
24*0b57cec5SDimitry Andric #include "TargetInfo.h"
25*0b57cec5SDimitry Andric #include "clang/AST/ASTContext.h"
26*0b57cec5SDimitry Andric #include "clang/AST/Attr.h"
27*0b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h"
28*0b57cec5SDimitry Andric #include "clang/AST/NSAPI.h"
29*0b57cec5SDimitry Andric #include "clang/Basic/Builtins.h"
30*0b57cec5SDimitry Andric #include "clang/Basic/CodeGenOptions.h"
315ffd83dbSDimitry Andric #include "clang/Basic/SourceManager.h"
32*0b57cec5SDimitry Andric #include "llvm/ADT/Hashing.h"
33*0b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
34*0b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
35*0b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
36*0b57cec5SDimitry Andric #include "llvm/IR/LLVMContext.h"
37*0b57cec5SDimitry Andric #include "llvm/IR/MDBuilder.h"
38349cc55cSDimitry Andric #include "llvm/IR/MatrixBuilder.h"
39*0b57cec5SDimitry Andric #include "llvm/Support/ConvertUTF.h"
40*0b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h"
41*0b57cec5SDimitry Andric #include "llvm/Support/Path.h"
42fe6060f1SDimitry Andric #include "llvm/Support/SaveAndRestore.h"
43*0b57cec5SDimitry Andric #include "llvm/Transforms/Utils/SanitizerStats.h"
44*0b57cec5SDimitry Andric 
45*0b57cec5SDimitry Andric #include <string>
46*0b57cec5SDimitry Andric 
47*0b57cec5SDimitry Andric using namespace clang;
48*0b57cec5SDimitry Andric using namespace CodeGen;
49*0b57cec5SDimitry Andric 
50*0b57cec5SDimitry Andric //===--------------------------------------------------------------------===//
51*0b57cec5SDimitry Andric //                        Miscellaneous Helper Methods
52*0b57cec5SDimitry Andric //===--------------------------------------------------------------------===//
53*0b57cec5SDimitry Andric 
54*0b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitCastToVoidPtr(llvm::Value *value) {
55*0b57cec5SDimitry Andric   unsigned addressSpace =
56*0b57cec5SDimitry Andric       cast<llvm::PointerType>(value->getType())->getAddressSpace();
57*0b57cec5SDimitry Andric 
58*0b57cec5SDimitry Andric   llvm::PointerType *destType = Int8PtrTy;
59*0b57cec5SDimitry Andric   if (addressSpace)
60*0b57cec5SDimitry Andric     destType = llvm::Type::getInt8PtrTy(getLLVMContext(), addressSpace);
61*0b57cec5SDimitry Andric 
62*0b57cec5SDimitry Andric   if (value->getType() == destType) return value;
63*0b57cec5SDimitry Andric   return Builder.CreateBitCast(value, destType);
64*0b57cec5SDimitry Andric }
65*0b57cec5SDimitry Andric 
66*0b57cec5SDimitry Andric /// CreateTempAlloca - This creates a alloca and inserts it into the entry
67*0b57cec5SDimitry Andric /// block.
68*0b57cec5SDimitry Andric Address CodeGenFunction::CreateTempAllocaWithoutCast(llvm::Type *Ty,
69*0b57cec5SDimitry Andric                                                      CharUnits Align,
70*0b57cec5SDimitry Andric                                                      const Twine &Name,
71*0b57cec5SDimitry Andric                                                      llvm::Value *ArraySize) {
72*0b57cec5SDimitry Andric   auto Alloca = CreateTempAlloca(Ty, Name, ArraySize);
73a7dea167SDimitry Andric   Alloca->setAlignment(Align.getAsAlign());
740eae32dcSDimitry Andric   return Address(Alloca, Ty, Align);
75*0b57cec5SDimitry Andric }
76*0b57cec5SDimitry Andric 
77*0b57cec5SDimitry Andric /// CreateTempAlloca - This creates a alloca and inserts it into the entry
78*0b57cec5SDimitry Andric /// block. The alloca is casted to default address space if necessary.
79*0b57cec5SDimitry Andric Address CodeGenFunction::CreateTempAlloca(llvm::Type *Ty, CharUnits Align,
80*0b57cec5SDimitry Andric                                           const Twine &Name,
81*0b57cec5SDimitry Andric                                           llvm::Value *ArraySize,
82*0b57cec5SDimitry Andric                                           Address *AllocaAddr) {
83*0b57cec5SDimitry Andric   auto Alloca = CreateTempAllocaWithoutCast(Ty, Align, Name, ArraySize);
84*0b57cec5SDimitry Andric   if (AllocaAddr)
85*0b57cec5SDimitry Andric     *AllocaAddr = Alloca;
86*0b57cec5SDimitry Andric   llvm::Value *V = Alloca.getPointer();
87*0b57cec5SDimitry Andric   // Alloca always returns a pointer in alloca address space, which may
88*0b57cec5SDimitry Andric   // be different from the type defined by the language. For example,
89*0b57cec5SDimitry Andric   // in C++ the auto variables are in the default address space. Therefore
90*0b57cec5SDimitry Andric   // cast alloca to the default address space when necessary.
91*0b57cec5SDimitry Andric   if (getASTAllocaAddressSpace() != LangAS::Default) {
92*0b57cec5SDimitry Andric     auto DestAddrSpace = getContext().getTargetAddressSpace(LangAS::Default);
93*0b57cec5SDimitry Andric     llvm::IRBuilderBase::InsertPointGuard IPG(Builder);
94*0b57cec5SDimitry Andric     // When ArraySize is nullptr, alloca is inserted at AllocaInsertPt,
95*0b57cec5SDimitry Andric     // otherwise alloca is inserted at the current insertion point of the
96*0b57cec5SDimitry Andric     // builder.
97*0b57cec5SDimitry Andric     if (!ArraySize)
98349cc55cSDimitry Andric       Builder.SetInsertPoint(getPostAllocaInsertPoint());
99*0b57cec5SDimitry Andric     V = getTargetHooks().performAddrSpaceCast(
100*0b57cec5SDimitry Andric         *this, V, getASTAllocaAddressSpace(), LangAS::Default,
101*0b57cec5SDimitry Andric         Ty->getPointerTo(DestAddrSpace), /*non-null*/ true);
102*0b57cec5SDimitry Andric   }
103*0b57cec5SDimitry Andric 
1040eae32dcSDimitry Andric   return Address(V, Ty, Align);
105*0b57cec5SDimitry Andric }
106*0b57cec5SDimitry Andric 
107*0b57cec5SDimitry Andric /// CreateTempAlloca - This creates an alloca and inserts it into the entry
108*0b57cec5SDimitry Andric /// block if \p ArraySize is nullptr, otherwise inserts it at the current
109*0b57cec5SDimitry Andric /// insertion point of the builder.
110*0b57cec5SDimitry Andric llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(llvm::Type *Ty,
111*0b57cec5SDimitry Andric                                                     const Twine &Name,
112*0b57cec5SDimitry Andric                                                     llvm::Value *ArraySize) {
113*0b57cec5SDimitry Andric   if (ArraySize)
114*0b57cec5SDimitry Andric     return Builder.CreateAlloca(Ty, ArraySize, Name);
115*0b57cec5SDimitry Andric   return new llvm::AllocaInst(Ty, CGM.getDataLayout().getAllocaAddrSpace(),
116*0b57cec5SDimitry Andric                               ArraySize, Name, AllocaInsertPt);
117*0b57cec5SDimitry Andric }
118*0b57cec5SDimitry Andric 
119*0b57cec5SDimitry Andric /// CreateDefaultAlignTempAlloca - This creates an alloca with the
120*0b57cec5SDimitry Andric /// default alignment of the corresponding LLVM type, which is *not*
121*0b57cec5SDimitry Andric /// guaranteed to be related in any way to the expected alignment of
122*0b57cec5SDimitry Andric /// an AST type that might have been lowered to Ty.
123*0b57cec5SDimitry Andric Address CodeGenFunction::CreateDefaultAlignTempAlloca(llvm::Type *Ty,
124*0b57cec5SDimitry Andric                                                       const Twine &Name) {
125*0b57cec5SDimitry Andric   CharUnits Align =
126349cc55cSDimitry Andric       CharUnits::fromQuantity(CGM.getDataLayout().getPrefTypeAlignment(Ty));
127*0b57cec5SDimitry Andric   return CreateTempAlloca(Ty, Align, Name);
128*0b57cec5SDimitry Andric }
129*0b57cec5SDimitry Andric 
130*0b57cec5SDimitry Andric Address CodeGenFunction::CreateIRTemp(QualType Ty, const Twine &Name) {
131*0b57cec5SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(Ty);
132*0b57cec5SDimitry Andric   return CreateTempAlloca(ConvertType(Ty), Align, Name);
133*0b57cec5SDimitry Andric }
134*0b57cec5SDimitry Andric 
135*0b57cec5SDimitry Andric Address CodeGenFunction::CreateMemTemp(QualType Ty, const Twine &Name,
136*0b57cec5SDimitry Andric                                        Address *Alloca) {
137*0b57cec5SDimitry Andric   // FIXME: Should we prefer the preferred type alignment here?
138*0b57cec5SDimitry Andric   return CreateMemTemp(Ty, getContext().getTypeAlignInChars(Ty), Name, Alloca);
139*0b57cec5SDimitry Andric }
140*0b57cec5SDimitry Andric 
141*0b57cec5SDimitry Andric Address CodeGenFunction::CreateMemTemp(QualType Ty, CharUnits Align,
142*0b57cec5SDimitry Andric                                        const Twine &Name, Address *Alloca) {
1435ffd83dbSDimitry Andric   Address Result = CreateTempAlloca(ConvertTypeForMem(Ty), Align, Name,
144*0b57cec5SDimitry Andric                                     /*ArraySize=*/nullptr, Alloca);
1455ffd83dbSDimitry Andric 
1465ffd83dbSDimitry Andric   if (Ty->isConstantMatrixType()) {
1470eae32dcSDimitry Andric     auto *ArrayTy = cast<llvm::ArrayType>(Result.getElementType());
1485ffd83dbSDimitry Andric     auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
1495ffd83dbSDimitry Andric                                                 ArrayTy->getNumElements());
1505ffd83dbSDimitry Andric 
1515ffd83dbSDimitry Andric     Result = Address(
1525ffd83dbSDimitry Andric         Builder.CreateBitCast(Result.getPointer(), VectorTy->getPointerTo()),
1535ffd83dbSDimitry Andric         Result.getAlignment());
1545ffd83dbSDimitry Andric   }
1555ffd83dbSDimitry Andric   return Result;
156*0b57cec5SDimitry Andric }
157*0b57cec5SDimitry Andric 
158*0b57cec5SDimitry Andric Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty, CharUnits Align,
159*0b57cec5SDimitry Andric                                                   const Twine &Name) {
160*0b57cec5SDimitry Andric   return CreateTempAllocaWithoutCast(ConvertTypeForMem(Ty), Align, Name);
161*0b57cec5SDimitry Andric }
162*0b57cec5SDimitry Andric 
163*0b57cec5SDimitry Andric Address CodeGenFunction::CreateMemTempWithoutCast(QualType Ty,
164*0b57cec5SDimitry Andric                                                   const Twine &Name) {
165*0b57cec5SDimitry Andric   return CreateMemTempWithoutCast(Ty, getContext().getTypeAlignInChars(Ty),
166*0b57cec5SDimitry Andric                                   Name);
167*0b57cec5SDimitry Andric }
168*0b57cec5SDimitry Andric 
169*0b57cec5SDimitry Andric /// EvaluateExprAsBool - Perform the usual unary conversions on the specified
170*0b57cec5SDimitry Andric /// expression and compare the result against zero, returning an Int1Ty value.
171*0b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
172*0b57cec5SDimitry Andric   PGO.setCurrentStmt(E);
173*0b57cec5SDimitry Andric   if (const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>()) {
174*0b57cec5SDimitry Andric     llvm::Value *MemPtr = EmitScalarExpr(E);
175*0b57cec5SDimitry Andric     return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, MemPtr, MPT);
176*0b57cec5SDimitry Andric   }
177*0b57cec5SDimitry Andric 
178*0b57cec5SDimitry Andric   QualType BoolTy = getContext().BoolTy;
179*0b57cec5SDimitry Andric   SourceLocation Loc = E->getExprLoc();
180e8d8bef9SDimitry Andric   CGFPOptionsRAII FPOptsRAII(*this, E);
181*0b57cec5SDimitry Andric   if (!E->getType()->isAnyComplexType())
182*0b57cec5SDimitry Andric     return EmitScalarConversion(EmitScalarExpr(E), E->getType(), BoolTy, Loc);
183*0b57cec5SDimitry Andric 
184*0b57cec5SDimitry Andric   return EmitComplexToScalarConversion(EmitComplexExpr(E), E->getType(), BoolTy,
185*0b57cec5SDimitry Andric                                        Loc);
186*0b57cec5SDimitry Andric }
187*0b57cec5SDimitry Andric 
188*0b57cec5SDimitry Andric /// EmitIgnoredExpr - Emit code to compute the specified expression,
189*0b57cec5SDimitry Andric /// ignoring the result.
190*0b57cec5SDimitry Andric void CodeGenFunction::EmitIgnoredExpr(const Expr *E) {
191fe6060f1SDimitry Andric   if (E->isPRValue())
192*0b57cec5SDimitry Andric     return (void) EmitAnyExpr(E, AggValueSlot::ignored(), true);
193*0b57cec5SDimitry Andric 
194*0b57cec5SDimitry Andric   // Just emit it as an l-value and drop the result.
195*0b57cec5SDimitry Andric   EmitLValue(E);
196*0b57cec5SDimitry Andric }
197*0b57cec5SDimitry Andric 
198*0b57cec5SDimitry Andric /// EmitAnyExpr - Emit code to compute the specified expression which
199*0b57cec5SDimitry Andric /// can have any type.  The result is returned as an RValue struct.
200*0b57cec5SDimitry Andric /// If this is an aggregate expression, AggSlot indicates where the
201*0b57cec5SDimitry Andric /// result should be returned.
202*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitAnyExpr(const Expr *E,
203*0b57cec5SDimitry Andric                                     AggValueSlot aggSlot,
204*0b57cec5SDimitry Andric                                     bool ignoreResult) {
205*0b57cec5SDimitry Andric   switch (getEvaluationKind(E->getType())) {
206*0b57cec5SDimitry Andric   case TEK_Scalar:
207*0b57cec5SDimitry Andric     return RValue::get(EmitScalarExpr(E, ignoreResult));
208*0b57cec5SDimitry Andric   case TEK_Complex:
209*0b57cec5SDimitry Andric     return RValue::getComplex(EmitComplexExpr(E, ignoreResult, ignoreResult));
210*0b57cec5SDimitry Andric   case TEK_Aggregate:
211*0b57cec5SDimitry Andric     if (!ignoreResult && aggSlot.isIgnored())
212*0b57cec5SDimitry Andric       aggSlot = CreateAggTemp(E->getType(), "agg-temp");
213*0b57cec5SDimitry Andric     EmitAggExpr(E, aggSlot);
214*0b57cec5SDimitry Andric     return aggSlot.asRValue();
215*0b57cec5SDimitry Andric   }
216*0b57cec5SDimitry Andric   llvm_unreachable("bad evaluation kind");
217*0b57cec5SDimitry Andric }
218*0b57cec5SDimitry Andric 
219*0b57cec5SDimitry Andric /// EmitAnyExprToTemp - Similar to EmitAnyExpr(), however, the result will
220*0b57cec5SDimitry Andric /// always be accessible even if no aggregate location is provided.
221*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitAnyExprToTemp(const Expr *E) {
222*0b57cec5SDimitry Andric   AggValueSlot AggSlot = AggValueSlot::ignored();
223*0b57cec5SDimitry Andric 
224*0b57cec5SDimitry Andric   if (hasAggregateEvaluationKind(E->getType()))
225*0b57cec5SDimitry Andric     AggSlot = CreateAggTemp(E->getType(), "agg.tmp");
226*0b57cec5SDimitry Andric   return EmitAnyExpr(E, AggSlot);
227*0b57cec5SDimitry Andric }
228*0b57cec5SDimitry Andric 
229*0b57cec5SDimitry Andric /// EmitAnyExprToMem - Evaluate an expression into a given memory
230*0b57cec5SDimitry Andric /// location.
231*0b57cec5SDimitry Andric void CodeGenFunction::EmitAnyExprToMem(const Expr *E,
232*0b57cec5SDimitry Andric                                        Address Location,
233*0b57cec5SDimitry Andric                                        Qualifiers Quals,
234*0b57cec5SDimitry Andric                                        bool IsInit) {
235*0b57cec5SDimitry Andric   // FIXME: This function should take an LValue as an argument.
236*0b57cec5SDimitry Andric   switch (getEvaluationKind(E->getType())) {
237*0b57cec5SDimitry Andric   case TEK_Complex:
238*0b57cec5SDimitry Andric     EmitComplexExprIntoLValue(E, MakeAddrLValue(Location, E->getType()),
239*0b57cec5SDimitry Andric                               /*isInit*/ false);
240*0b57cec5SDimitry Andric     return;
241*0b57cec5SDimitry Andric 
242*0b57cec5SDimitry Andric   case TEK_Aggregate: {
243*0b57cec5SDimitry Andric     EmitAggExpr(E, AggValueSlot::forAddr(Location, Quals,
244*0b57cec5SDimitry Andric                                          AggValueSlot::IsDestructed_t(IsInit),
245*0b57cec5SDimitry Andric                                          AggValueSlot::DoesNotNeedGCBarriers,
246*0b57cec5SDimitry Andric                                          AggValueSlot::IsAliased_t(!IsInit),
247*0b57cec5SDimitry Andric                                          AggValueSlot::MayOverlap));
248*0b57cec5SDimitry Andric     return;
249*0b57cec5SDimitry Andric   }
250*0b57cec5SDimitry Andric 
251*0b57cec5SDimitry Andric   case TEK_Scalar: {
252*0b57cec5SDimitry Andric     RValue RV = RValue::get(EmitScalarExpr(E, /*Ignore*/ false));
253*0b57cec5SDimitry Andric     LValue LV = MakeAddrLValue(Location, E->getType());
254*0b57cec5SDimitry Andric     EmitStoreThroughLValue(RV, LV);
255*0b57cec5SDimitry Andric     return;
256*0b57cec5SDimitry Andric   }
257*0b57cec5SDimitry Andric   }
258*0b57cec5SDimitry Andric   llvm_unreachable("bad evaluation kind");
259*0b57cec5SDimitry Andric }
260*0b57cec5SDimitry Andric 
261*0b57cec5SDimitry Andric static void
262*0b57cec5SDimitry Andric pushTemporaryCleanup(CodeGenFunction &CGF, const MaterializeTemporaryExpr *M,
263*0b57cec5SDimitry Andric                      const Expr *E, Address ReferenceTemporary) {
264*0b57cec5SDimitry Andric   // Objective-C++ ARC:
265*0b57cec5SDimitry Andric   //   If we are binding a reference to a temporary that has ownership, we
266*0b57cec5SDimitry Andric   //   need to perform retain/release operations on the temporary.
267*0b57cec5SDimitry Andric   //
268*0b57cec5SDimitry Andric   // FIXME: This should be looking at E, not M.
269*0b57cec5SDimitry Andric   if (auto Lifetime = M->getType().getObjCLifetime()) {
270*0b57cec5SDimitry Andric     switch (Lifetime) {
271*0b57cec5SDimitry Andric     case Qualifiers::OCL_None:
272*0b57cec5SDimitry Andric     case Qualifiers::OCL_ExplicitNone:
273*0b57cec5SDimitry Andric       // Carry on to normal cleanup handling.
274*0b57cec5SDimitry Andric       break;
275*0b57cec5SDimitry Andric 
276*0b57cec5SDimitry Andric     case Qualifiers::OCL_Autoreleasing:
277*0b57cec5SDimitry Andric       // Nothing to do; cleaned up by an autorelease pool.
278*0b57cec5SDimitry Andric       return;
279*0b57cec5SDimitry Andric 
280*0b57cec5SDimitry Andric     case Qualifiers::OCL_Strong:
281*0b57cec5SDimitry Andric     case Qualifiers::OCL_Weak:
282*0b57cec5SDimitry Andric       switch (StorageDuration Duration = M->getStorageDuration()) {
283*0b57cec5SDimitry Andric       case SD_Static:
284*0b57cec5SDimitry Andric         // Note: we intentionally do not register a cleanup to release
285*0b57cec5SDimitry Andric         // the object on program termination.
286*0b57cec5SDimitry Andric         return;
287*0b57cec5SDimitry Andric 
288*0b57cec5SDimitry Andric       case SD_Thread:
289*0b57cec5SDimitry Andric         // FIXME: We should probably register a cleanup in this case.
290*0b57cec5SDimitry Andric         return;
291*0b57cec5SDimitry Andric 
292*0b57cec5SDimitry Andric       case SD_Automatic:
293*0b57cec5SDimitry Andric       case SD_FullExpression:
294*0b57cec5SDimitry Andric         CodeGenFunction::Destroyer *Destroy;
295*0b57cec5SDimitry Andric         CleanupKind CleanupKind;
296*0b57cec5SDimitry Andric         if (Lifetime == Qualifiers::OCL_Strong) {
297*0b57cec5SDimitry Andric           const ValueDecl *VD = M->getExtendingDecl();
298*0b57cec5SDimitry Andric           bool Precise =
299*0b57cec5SDimitry Andric               VD && isa<VarDecl>(VD) && VD->hasAttr<ObjCPreciseLifetimeAttr>();
300*0b57cec5SDimitry Andric           CleanupKind = CGF.getARCCleanupKind();
301*0b57cec5SDimitry Andric           Destroy = Precise ? &CodeGenFunction::destroyARCStrongPrecise
302*0b57cec5SDimitry Andric                             : &CodeGenFunction::destroyARCStrongImprecise;
303*0b57cec5SDimitry Andric         } else {
304*0b57cec5SDimitry Andric           // __weak objects always get EH cleanups; otherwise, exceptions
305*0b57cec5SDimitry Andric           // could cause really nasty crashes instead of mere leaks.
306*0b57cec5SDimitry Andric           CleanupKind = NormalAndEHCleanup;
307*0b57cec5SDimitry Andric           Destroy = &CodeGenFunction::destroyARCWeak;
308*0b57cec5SDimitry Andric         }
309*0b57cec5SDimitry Andric         if (Duration == SD_FullExpression)
310*0b57cec5SDimitry Andric           CGF.pushDestroy(CleanupKind, ReferenceTemporary,
311*0b57cec5SDimitry Andric                           M->getType(), *Destroy,
312*0b57cec5SDimitry Andric                           CleanupKind & EHCleanup);
313*0b57cec5SDimitry Andric         else
314*0b57cec5SDimitry Andric           CGF.pushLifetimeExtendedDestroy(CleanupKind, ReferenceTemporary,
315*0b57cec5SDimitry Andric                                           M->getType(),
316*0b57cec5SDimitry Andric                                           *Destroy, CleanupKind & EHCleanup);
317*0b57cec5SDimitry Andric         return;
318*0b57cec5SDimitry Andric 
319*0b57cec5SDimitry Andric       case SD_Dynamic:
320*0b57cec5SDimitry Andric         llvm_unreachable("temporary cannot have dynamic storage duration");
321*0b57cec5SDimitry Andric       }
322*0b57cec5SDimitry Andric       llvm_unreachable("unknown storage duration");
323*0b57cec5SDimitry Andric     }
324*0b57cec5SDimitry Andric   }
325*0b57cec5SDimitry Andric 
326*0b57cec5SDimitry Andric   CXXDestructorDecl *ReferenceTemporaryDtor = nullptr;
327*0b57cec5SDimitry Andric   if (const RecordType *RT =
328*0b57cec5SDimitry Andric           E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
329*0b57cec5SDimitry Andric     // Get the destructor for the reference temporary.
330*0b57cec5SDimitry Andric     auto *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
331*0b57cec5SDimitry Andric     if (!ClassDecl->hasTrivialDestructor())
332*0b57cec5SDimitry Andric       ReferenceTemporaryDtor = ClassDecl->getDestructor();
333*0b57cec5SDimitry Andric   }
334*0b57cec5SDimitry Andric 
335*0b57cec5SDimitry Andric   if (!ReferenceTemporaryDtor)
336*0b57cec5SDimitry Andric     return;
337*0b57cec5SDimitry Andric 
338*0b57cec5SDimitry Andric   // Call the destructor for the temporary.
339*0b57cec5SDimitry Andric   switch (M->getStorageDuration()) {
340*0b57cec5SDimitry Andric   case SD_Static:
341*0b57cec5SDimitry Andric   case SD_Thread: {
342*0b57cec5SDimitry Andric     llvm::FunctionCallee CleanupFn;
343*0b57cec5SDimitry Andric     llvm::Constant *CleanupArg;
344*0b57cec5SDimitry Andric     if (E->getType()->isArrayType()) {
345*0b57cec5SDimitry Andric       CleanupFn = CodeGenFunction(CGF.CGM).generateDestroyHelper(
346*0b57cec5SDimitry Andric           ReferenceTemporary, E->getType(),
347*0b57cec5SDimitry Andric           CodeGenFunction::destroyCXXObject, CGF.getLangOpts().Exceptions,
348*0b57cec5SDimitry Andric           dyn_cast_or_null<VarDecl>(M->getExtendingDecl()));
349*0b57cec5SDimitry Andric       CleanupArg = llvm::Constant::getNullValue(CGF.Int8PtrTy);
350*0b57cec5SDimitry Andric     } else {
351*0b57cec5SDimitry Andric       CleanupFn = CGF.CGM.getAddrAndTypeOfCXXStructor(
352*0b57cec5SDimitry Andric           GlobalDecl(ReferenceTemporaryDtor, Dtor_Complete));
353*0b57cec5SDimitry Andric       CleanupArg = cast<llvm::Constant>(ReferenceTemporary.getPointer());
354*0b57cec5SDimitry Andric     }
355*0b57cec5SDimitry Andric     CGF.CGM.getCXXABI().registerGlobalDtor(
356*0b57cec5SDimitry Andric         CGF, *cast<VarDecl>(M->getExtendingDecl()), CleanupFn, CleanupArg);
357*0b57cec5SDimitry Andric     break;
358*0b57cec5SDimitry Andric   }
359*0b57cec5SDimitry Andric 
360*0b57cec5SDimitry Andric   case SD_FullExpression:
361*0b57cec5SDimitry Andric     CGF.pushDestroy(NormalAndEHCleanup, ReferenceTemporary, E->getType(),
362*0b57cec5SDimitry Andric                     CodeGenFunction::destroyCXXObject,
363*0b57cec5SDimitry Andric                     CGF.getLangOpts().Exceptions);
364*0b57cec5SDimitry Andric     break;
365*0b57cec5SDimitry Andric 
366*0b57cec5SDimitry Andric   case SD_Automatic:
367*0b57cec5SDimitry Andric     CGF.pushLifetimeExtendedDestroy(NormalAndEHCleanup,
368*0b57cec5SDimitry Andric                                     ReferenceTemporary, E->getType(),
369*0b57cec5SDimitry Andric                                     CodeGenFunction::destroyCXXObject,
370*0b57cec5SDimitry Andric                                     CGF.getLangOpts().Exceptions);
371*0b57cec5SDimitry Andric     break;
372*0b57cec5SDimitry Andric 
373*0b57cec5SDimitry Andric   case SD_Dynamic:
374*0b57cec5SDimitry Andric     llvm_unreachable("temporary cannot have dynamic storage duration");
375*0b57cec5SDimitry Andric   }
376*0b57cec5SDimitry Andric }
377*0b57cec5SDimitry Andric 
378*0b57cec5SDimitry Andric static Address createReferenceTemporary(CodeGenFunction &CGF,
379*0b57cec5SDimitry Andric                                         const MaterializeTemporaryExpr *M,
380*0b57cec5SDimitry Andric                                         const Expr *Inner,
381*0b57cec5SDimitry Andric                                         Address *Alloca = nullptr) {
382*0b57cec5SDimitry Andric   auto &TCG = CGF.getTargetHooks();
383*0b57cec5SDimitry Andric   switch (M->getStorageDuration()) {
384*0b57cec5SDimitry Andric   case SD_FullExpression:
385*0b57cec5SDimitry Andric   case SD_Automatic: {
386*0b57cec5SDimitry Andric     // If we have a constant temporary array or record try to promote it into a
387*0b57cec5SDimitry Andric     // constant global under the same rules a normal constant would've been
388*0b57cec5SDimitry Andric     // promoted. This is easier on the optimizer and generally emits fewer
389*0b57cec5SDimitry Andric     // instructions.
390*0b57cec5SDimitry Andric     QualType Ty = Inner->getType();
391*0b57cec5SDimitry Andric     if (CGF.CGM.getCodeGenOpts().MergeAllConstants &&
392*0b57cec5SDimitry Andric         (Ty->isArrayType() || Ty->isRecordType()) &&
393*0b57cec5SDimitry Andric         CGF.CGM.isTypeConstant(Ty, true))
394*0b57cec5SDimitry Andric       if (auto Init = ConstantEmitter(CGF).tryEmitAbstract(Inner, Ty)) {
395fe6060f1SDimitry Andric         auto AS = CGF.CGM.GetGlobalConstantAddressSpace();
396*0b57cec5SDimitry Andric         auto *GV = new llvm::GlobalVariable(
397*0b57cec5SDimitry Andric             CGF.CGM.getModule(), Init->getType(), /*isConstant=*/true,
398*0b57cec5SDimitry Andric             llvm::GlobalValue::PrivateLinkage, Init, ".ref.tmp", nullptr,
399*0b57cec5SDimitry Andric             llvm::GlobalValue::NotThreadLocal,
400*0b57cec5SDimitry Andric             CGF.getContext().getTargetAddressSpace(AS));
401*0b57cec5SDimitry Andric         CharUnits alignment = CGF.getContext().getTypeAlignInChars(Ty);
402a7dea167SDimitry Andric         GV->setAlignment(alignment.getAsAlign());
403*0b57cec5SDimitry Andric         llvm::Constant *C = GV;
404*0b57cec5SDimitry Andric         if (AS != LangAS::Default)
405*0b57cec5SDimitry Andric           C = TCG.performAddrSpaceCast(
406*0b57cec5SDimitry Andric               CGF.CGM, GV, AS, LangAS::Default,
407*0b57cec5SDimitry Andric               GV->getValueType()->getPointerTo(
408*0b57cec5SDimitry Andric                   CGF.getContext().getTargetAddressSpace(LangAS::Default)));
409*0b57cec5SDimitry Andric         // FIXME: Should we put the new global into a COMDAT?
410*0b57cec5SDimitry Andric         return Address(C, alignment);
411*0b57cec5SDimitry Andric       }
412*0b57cec5SDimitry Andric     return CGF.CreateMemTemp(Ty, "ref.tmp", Alloca);
413*0b57cec5SDimitry Andric   }
414*0b57cec5SDimitry Andric   case SD_Thread:
415*0b57cec5SDimitry Andric   case SD_Static:
416*0b57cec5SDimitry Andric     return CGF.CGM.GetAddrOfGlobalTemporary(M, Inner);
417*0b57cec5SDimitry Andric 
418*0b57cec5SDimitry Andric   case SD_Dynamic:
419*0b57cec5SDimitry Andric     llvm_unreachable("temporary can't have dynamic storage duration");
420*0b57cec5SDimitry Andric   }
421*0b57cec5SDimitry Andric   llvm_unreachable("unknown storage duration");
422*0b57cec5SDimitry Andric }
423*0b57cec5SDimitry Andric 
4245ffd83dbSDimitry Andric /// Helper method to check if the underlying ABI is AAPCS
4255ffd83dbSDimitry Andric static bool isAAPCS(const TargetInfo &TargetInfo) {
4265ffd83dbSDimitry Andric   return TargetInfo.getABI().startswith("aapcs");
4275ffd83dbSDimitry Andric }
4285ffd83dbSDimitry Andric 
429*0b57cec5SDimitry Andric LValue CodeGenFunction::
430*0b57cec5SDimitry Andric EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
431480093f4SDimitry Andric   const Expr *E = M->getSubExpr();
432*0b57cec5SDimitry Andric 
433*0b57cec5SDimitry Andric   assert((!M->getExtendingDecl() || !isa<VarDecl>(M->getExtendingDecl()) ||
434*0b57cec5SDimitry Andric           !cast<VarDecl>(M->getExtendingDecl())->isARCPseudoStrong()) &&
435*0b57cec5SDimitry Andric          "Reference should never be pseudo-strong!");
436*0b57cec5SDimitry Andric 
437*0b57cec5SDimitry Andric   // FIXME: ideally this would use EmitAnyExprToMem, however, we cannot do so
438*0b57cec5SDimitry Andric   // as that will cause the lifetime adjustment to be lost for ARC
439*0b57cec5SDimitry Andric   auto ownership = M->getType().getObjCLifetime();
440*0b57cec5SDimitry Andric   if (ownership != Qualifiers::OCL_None &&
441*0b57cec5SDimitry Andric       ownership != Qualifiers::OCL_ExplicitNone) {
442*0b57cec5SDimitry Andric     Address Object = createReferenceTemporary(*this, M, E);
443*0b57cec5SDimitry Andric     if (auto *Var = dyn_cast<llvm::GlobalVariable>(Object.getPointer())) {
444*0b57cec5SDimitry Andric       Object = Address(llvm::ConstantExpr::getBitCast(Var,
445*0b57cec5SDimitry Andric                            ConvertTypeForMem(E->getType())
446*0b57cec5SDimitry Andric                              ->getPointerTo(Object.getAddressSpace())),
447*0b57cec5SDimitry Andric                        Object.getAlignment());
448*0b57cec5SDimitry Andric 
449*0b57cec5SDimitry Andric       // createReferenceTemporary will promote the temporary to a global with a
450*0b57cec5SDimitry Andric       // constant initializer if it can.  It can only do this to a value of
451*0b57cec5SDimitry Andric       // ARC-manageable type if the value is global and therefore "immune" to
452*0b57cec5SDimitry Andric       // ref-counting operations.  Therefore we have no need to emit either a
453*0b57cec5SDimitry Andric       // dynamic initialization or a cleanup and we can just return the address
454*0b57cec5SDimitry Andric       // of the temporary.
455*0b57cec5SDimitry Andric       if (Var->hasInitializer())
456*0b57cec5SDimitry Andric         return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
457*0b57cec5SDimitry Andric 
458*0b57cec5SDimitry Andric       Var->setInitializer(CGM.EmitNullConstant(E->getType()));
459*0b57cec5SDimitry Andric     }
460*0b57cec5SDimitry Andric     LValue RefTempDst = MakeAddrLValue(Object, M->getType(),
461*0b57cec5SDimitry Andric                                        AlignmentSource::Decl);
462*0b57cec5SDimitry Andric 
463*0b57cec5SDimitry Andric     switch (getEvaluationKind(E->getType())) {
464*0b57cec5SDimitry Andric     default: llvm_unreachable("expected scalar or aggregate expression");
465*0b57cec5SDimitry Andric     case TEK_Scalar:
466*0b57cec5SDimitry Andric       EmitScalarInit(E, M->getExtendingDecl(), RefTempDst, false);
467*0b57cec5SDimitry Andric       break;
468*0b57cec5SDimitry Andric     case TEK_Aggregate: {
469*0b57cec5SDimitry Andric       EmitAggExpr(E, AggValueSlot::forAddr(Object,
470*0b57cec5SDimitry Andric                                            E->getType().getQualifiers(),
471*0b57cec5SDimitry Andric                                            AggValueSlot::IsDestructed,
472*0b57cec5SDimitry Andric                                            AggValueSlot::DoesNotNeedGCBarriers,
473*0b57cec5SDimitry Andric                                            AggValueSlot::IsNotAliased,
474*0b57cec5SDimitry Andric                                            AggValueSlot::DoesNotOverlap));
475*0b57cec5SDimitry Andric       break;
476*0b57cec5SDimitry Andric     }
477*0b57cec5SDimitry Andric     }
478*0b57cec5SDimitry Andric 
479*0b57cec5SDimitry Andric     pushTemporaryCleanup(*this, M, E, Object);
480*0b57cec5SDimitry Andric     return RefTempDst;
481*0b57cec5SDimitry Andric   }
482*0b57cec5SDimitry Andric 
483*0b57cec5SDimitry Andric   SmallVector<const Expr *, 2> CommaLHSs;
484*0b57cec5SDimitry Andric   SmallVector<SubobjectAdjustment, 2> Adjustments;
485*0b57cec5SDimitry Andric   E = E->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
486*0b57cec5SDimitry Andric 
487*0b57cec5SDimitry Andric   for (const auto &Ignored : CommaLHSs)
488*0b57cec5SDimitry Andric     EmitIgnoredExpr(Ignored);
489*0b57cec5SDimitry Andric 
490*0b57cec5SDimitry Andric   if (const auto *opaque = dyn_cast<OpaqueValueExpr>(E)) {
491*0b57cec5SDimitry Andric     if (opaque->getType()->isRecordType()) {
492*0b57cec5SDimitry Andric       assert(Adjustments.empty());
493*0b57cec5SDimitry Andric       return EmitOpaqueValueLValue(opaque);
494*0b57cec5SDimitry Andric     }
495*0b57cec5SDimitry Andric   }
496*0b57cec5SDimitry Andric 
497*0b57cec5SDimitry Andric   // Create and initialize the reference temporary.
498*0b57cec5SDimitry Andric   Address Alloca = Address::invalid();
499*0b57cec5SDimitry Andric   Address Object = createReferenceTemporary(*this, M, E, &Alloca);
500*0b57cec5SDimitry Andric   if (auto *Var = dyn_cast<llvm::GlobalVariable>(
501*0b57cec5SDimitry Andric           Object.getPointer()->stripPointerCasts())) {
502*0b57cec5SDimitry Andric     Object = Address(llvm::ConstantExpr::getBitCast(
503*0b57cec5SDimitry Andric                          cast<llvm::Constant>(Object.getPointer()),
504*0b57cec5SDimitry Andric                          ConvertTypeForMem(E->getType())->getPointerTo()),
505*0b57cec5SDimitry Andric                      Object.getAlignment());
506*0b57cec5SDimitry Andric     // If the temporary is a global and has a constant initializer or is a
507*0b57cec5SDimitry Andric     // constant temporary that we promoted to a global, we may have already
508*0b57cec5SDimitry Andric     // initialized it.
509*0b57cec5SDimitry Andric     if (!Var->hasInitializer()) {
510*0b57cec5SDimitry Andric       Var->setInitializer(CGM.EmitNullConstant(E->getType()));
511*0b57cec5SDimitry Andric       EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
512*0b57cec5SDimitry Andric     }
513*0b57cec5SDimitry Andric   } else {
514*0b57cec5SDimitry Andric     switch (M->getStorageDuration()) {
515*0b57cec5SDimitry Andric     case SD_Automatic:
516*0b57cec5SDimitry Andric       if (auto *Size = EmitLifetimeStart(
517*0b57cec5SDimitry Andric               CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
518*0b57cec5SDimitry Andric               Alloca.getPointer())) {
519*0b57cec5SDimitry Andric         pushCleanupAfterFullExpr<CallLifetimeEnd>(NormalEHLifetimeMarker,
520*0b57cec5SDimitry Andric                                                   Alloca, Size);
521*0b57cec5SDimitry Andric       }
522*0b57cec5SDimitry Andric       break;
523*0b57cec5SDimitry Andric 
524*0b57cec5SDimitry Andric     case SD_FullExpression: {
525*0b57cec5SDimitry Andric       if (!ShouldEmitLifetimeMarkers)
526*0b57cec5SDimitry Andric         break;
527*0b57cec5SDimitry Andric 
528*0b57cec5SDimitry Andric       // Avoid creating a conditional cleanup just to hold an llvm.lifetime.end
529*0b57cec5SDimitry Andric       // marker. Instead, start the lifetime of a conditional temporary earlier
530a7dea167SDimitry Andric       // so that it's unconditional. Don't do this with sanitizers which need
531a7dea167SDimitry Andric       // more precise lifetime marks.
532*0b57cec5SDimitry Andric       ConditionalEvaluation *OldConditional = nullptr;
533*0b57cec5SDimitry Andric       CGBuilderTy::InsertPoint OldIP;
534*0b57cec5SDimitry Andric       if (isInConditionalBranch() && !E->getType().isDestructedType() &&
535a7dea167SDimitry Andric           !SanOpts.has(SanitizerKind::HWAddress) &&
536a7dea167SDimitry Andric           !SanOpts.has(SanitizerKind::Memory) &&
537*0b57cec5SDimitry Andric           !CGM.getCodeGenOpts().SanitizeAddressUseAfterScope) {
538*0b57cec5SDimitry Andric         OldConditional = OutermostConditional;
539*0b57cec5SDimitry Andric         OutermostConditional = nullptr;
540*0b57cec5SDimitry Andric 
541*0b57cec5SDimitry Andric         OldIP = Builder.saveIP();
542*0b57cec5SDimitry Andric         llvm::BasicBlock *Block = OldConditional->getStartingBlock();
543*0b57cec5SDimitry Andric         Builder.restoreIP(CGBuilderTy::InsertPoint(
544*0b57cec5SDimitry Andric             Block, llvm::BasicBlock::iterator(Block->back())));
545*0b57cec5SDimitry Andric       }
546*0b57cec5SDimitry Andric 
547*0b57cec5SDimitry Andric       if (auto *Size = EmitLifetimeStart(
548*0b57cec5SDimitry Andric               CGM.getDataLayout().getTypeAllocSize(Alloca.getElementType()),
549*0b57cec5SDimitry Andric               Alloca.getPointer())) {
550*0b57cec5SDimitry Andric         pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, Alloca,
551*0b57cec5SDimitry Andric                                              Size);
552*0b57cec5SDimitry Andric       }
553*0b57cec5SDimitry Andric 
554*0b57cec5SDimitry Andric       if (OldConditional) {
555*0b57cec5SDimitry Andric         OutermostConditional = OldConditional;
556*0b57cec5SDimitry Andric         Builder.restoreIP(OldIP);
557*0b57cec5SDimitry Andric       }
558*0b57cec5SDimitry Andric       break;
559*0b57cec5SDimitry Andric     }
560*0b57cec5SDimitry Andric 
561*0b57cec5SDimitry Andric     default:
562*0b57cec5SDimitry Andric       break;
563*0b57cec5SDimitry Andric     }
564*0b57cec5SDimitry Andric     EmitAnyExprToMem(E, Object, Qualifiers(), /*IsInit*/true);
565*0b57cec5SDimitry Andric   }
566*0b57cec5SDimitry Andric   pushTemporaryCleanup(*this, M, E, Object);
567*0b57cec5SDimitry Andric 
568*0b57cec5SDimitry Andric   // Perform derived-to-base casts and/or field accesses, to get from the
569*0b57cec5SDimitry Andric   // temporary object we created (and, potentially, for which we extended
570*0b57cec5SDimitry Andric   // the lifetime) to the subobject we're binding the reference to.
571349cc55cSDimitry Andric   for (SubobjectAdjustment &Adjustment : llvm::reverse(Adjustments)) {
572*0b57cec5SDimitry Andric     switch (Adjustment.Kind) {
573*0b57cec5SDimitry Andric     case SubobjectAdjustment::DerivedToBaseAdjustment:
574*0b57cec5SDimitry Andric       Object =
575*0b57cec5SDimitry Andric           GetAddressOfBaseClass(Object, Adjustment.DerivedToBase.DerivedClass,
576*0b57cec5SDimitry Andric                                 Adjustment.DerivedToBase.BasePath->path_begin(),
577*0b57cec5SDimitry Andric                                 Adjustment.DerivedToBase.BasePath->path_end(),
578*0b57cec5SDimitry Andric                                 /*NullCheckValue=*/ false, E->getExprLoc());
579*0b57cec5SDimitry Andric       break;
580*0b57cec5SDimitry Andric 
581*0b57cec5SDimitry Andric     case SubobjectAdjustment::FieldAdjustment: {
582*0b57cec5SDimitry Andric       LValue LV = MakeAddrLValue(Object, E->getType(), AlignmentSource::Decl);
583*0b57cec5SDimitry Andric       LV = EmitLValueForField(LV, Adjustment.Field);
584*0b57cec5SDimitry Andric       assert(LV.isSimple() &&
585*0b57cec5SDimitry Andric              "materialized temporary field is not a simple lvalue");
586480093f4SDimitry Andric       Object = LV.getAddress(*this);
587*0b57cec5SDimitry Andric       break;
588*0b57cec5SDimitry Andric     }
589*0b57cec5SDimitry Andric 
590*0b57cec5SDimitry Andric     case SubobjectAdjustment::MemberPointerAdjustment: {
591*0b57cec5SDimitry Andric       llvm::Value *Ptr = EmitScalarExpr(Adjustment.Ptr.RHS);
592*0b57cec5SDimitry Andric       Object = EmitCXXMemberDataPointerAddress(E, Object, Ptr,
593*0b57cec5SDimitry Andric                                                Adjustment.Ptr.MPT);
594*0b57cec5SDimitry Andric       break;
595*0b57cec5SDimitry Andric     }
596*0b57cec5SDimitry Andric     }
597*0b57cec5SDimitry Andric   }
598*0b57cec5SDimitry Andric 
599*0b57cec5SDimitry Andric   return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
600*0b57cec5SDimitry Andric }
601*0b57cec5SDimitry Andric 
602*0b57cec5SDimitry Andric RValue
603*0b57cec5SDimitry Andric CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E) {
604*0b57cec5SDimitry Andric   // Emit the expression as an lvalue.
605*0b57cec5SDimitry Andric   LValue LV = EmitLValue(E);
606*0b57cec5SDimitry Andric   assert(LV.isSimple());
607480093f4SDimitry Andric   llvm::Value *Value = LV.getPointer(*this);
608*0b57cec5SDimitry Andric 
609*0b57cec5SDimitry Andric   if (sanitizePerformTypeCheck() && !E->getType()->isFunctionType()) {
610*0b57cec5SDimitry Andric     // C++11 [dcl.ref]p5 (as amended by core issue 453):
611*0b57cec5SDimitry Andric     //   If a glvalue to which a reference is directly bound designates neither
612*0b57cec5SDimitry Andric     //   an existing object or function of an appropriate type nor a region of
613*0b57cec5SDimitry Andric     //   storage of suitable size and alignment to contain an object of the
614*0b57cec5SDimitry Andric     //   reference's type, the behavior is undefined.
615*0b57cec5SDimitry Andric     QualType Ty = E->getType();
616*0b57cec5SDimitry Andric     EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
617*0b57cec5SDimitry Andric   }
618*0b57cec5SDimitry Andric 
619*0b57cec5SDimitry Andric   return RValue::get(Value);
620*0b57cec5SDimitry Andric }
621*0b57cec5SDimitry Andric 
622*0b57cec5SDimitry Andric 
623*0b57cec5SDimitry Andric /// getAccessedFieldNo - Given an encoded value and a result number, return the
624*0b57cec5SDimitry Andric /// input field number being accessed.
625*0b57cec5SDimitry Andric unsigned CodeGenFunction::getAccessedFieldNo(unsigned Idx,
626*0b57cec5SDimitry Andric                                              const llvm::Constant *Elts) {
627*0b57cec5SDimitry Andric   return cast<llvm::ConstantInt>(Elts->getAggregateElement(Idx))
628*0b57cec5SDimitry Andric       ->getZExtValue();
629*0b57cec5SDimitry Andric }
630*0b57cec5SDimitry Andric 
631*0b57cec5SDimitry Andric /// Emit the hash_16_bytes function from include/llvm/ADT/Hashing.h.
632*0b57cec5SDimitry Andric static llvm::Value *emitHash16Bytes(CGBuilderTy &Builder, llvm::Value *Low,
633*0b57cec5SDimitry Andric                                     llvm::Value *High) {
634*0b57cec5SDimitry Andric   llvm::Value *KMul = Builder.getInt64(0x9ddfea08eb382d69ULL);
635*0b57cec5SDimitry Andric   llvm::Value *K47 = Builder.getInt64(47);
636*0b57cec5SDimitry Andric   llvm::Value *A0 = Builder.CreateMul(Builder.CreateXor(Low, High), KMul);
637*0b57cec5SDimitry Andric   llvm::Value *A1 = Builder.CreateXor(Builder.CreateLShr(A0, K47), A0);
638*0b57cec5SDimitry Andric   llvm::Value *B0 = Builder.CreateMul(Builder.CreateXor(High, A1), KMul);
639*0b57cec5SDimitry Andric   llvm::Value *B1 = Builder.CreateXor(Builder.CreateLShr(B0, K47), B0);
640*0b57cec5SDimitry Andric   return Builder.CreateMul(B1, KMul);
641*0b57cec5SDimitry Andric }
642*0b57cec5SDimitry Andric 
643*0b57cec5SDimitry Andric bool CodeGenFunction::isNullPointerAllowed(TypeCheckKind TCK) {
644*0b57cec5SDimitry Andric   return TCK == TCK_DowncastPointer || TCK == TCK_Upcast ||
645*0b57cec5SDimitry Andric          TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation;
646*0b57cec5SDimitry Andric }
647*0b57cec5SDimitry Andric 
648*0b57cec5SDimitry Andric bool CodeGenFunction::isVptrCheckRequired(TypeCheckKind TCK, QualType Ty) {
649*0b57cec5SDimitry Andric   CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
650*0b57cec5SDimitry Andric   return (RD && RD->hasDefinition() && RD->isDynamicClass()) &&
651*0b57cec5SDimitry Andric          (TCK == TCK_MemberAccess || TCK == TCK_MemberCall ||
652*0b57cec5SDimitry Andric           TCK == TCK_DowncastPointer || TCK == TCK_DowncastReference ||
653*0b57cec5SDimitry Andric           TCK == TCK_UpcastToVirtualBase || TCK == TCK_DynamicOperation);
654*0b57cec5SDimitry Andric }
655*0b57cec5SDimitry Andric 
656*0b57cec5SDimitry Andric bool CodeGenFunction::sanitizePerformTypeCheck() const {
657349cc55cSDimitry Andric   return SanOpts.has(SanitizerKind::Null) ||
658349cc55cSDimitry Andric          SanOpts.has(SanitizerKind::Alignment) ||
659349cc55cSDimitry Andric          SanOpts.has(SanitizerKind::ObjectSize) ||
660*0b57cec5SDimitry Andric          SanOpts.has(SanitizerKind::Vptr);
661*0b57cec5SDimitry Andric }
662*0b57cec5SDimitry Andric 
663*0b57cec5SDimitry Andric void CodeGenFunction::EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc,
664*0b57cec5SDimitry Andric                                     llvm::Value *Ptr, QualType Ty,
665*0b57cec5SDimitry Andric                                     CharUnits Alignment,
666*0b57cec5SDimitry Andric                                     SanitizerSet SkippedChecks,
667*0b57cec5SDimitry Andric                                     llvm::Value *ArraySize) {
668*0b57cec5SDimitry Andric   if (!sanitizePerformTypeCheck())
669*0b57cec5SDimitry Andric     return;
670*0b57cec5SDimitry Andric 
671*0b57cec5SDimitry Andric   // Don't check pointers outside the default address space. The null check
672*0b57cec5SDimitry Andric   // isn't correct, the object-size check isn't supported by LLVM, and we can't
673*0b57cec5SDimitry Andric   // communicate the addresses to the runtime handler for the vptr check.
674*0b57cec5SDimitry Andric   if (Ptr->getType()->getPointerAddressSpace())
675*0b57cec5SDimitry Andric     return;
676*0b57cec5SDimitry Andric 
677*0b57cec5SDimitry Andric   // Don't check pointers to volatile data. The behavior here is implementation-
678*0b57cec5SDimitry Andric   // defined.
679*0b57cec5SDimitry Andric   if (Ty.isVolatileQualified())
680*0b57cec5SDimitry Andric     return;
681*0b57cec5SDimitry Andric 
682*0b57cec5SDimitry Andric   SanitizerScope SanScope(this);
683*0b57cec5SDimitry Andric 
684*0b57cec5SDimitry Andric   SmallVector<std::pair<llvm::Value *, SanitizerMask>, 3> Checks;
685*0b57cec5SDimitry Andric   llvm::BasicBlock *Done = nullptr;
686*0b57cec5SDimitry Andric 
687*0b57cec5SDimitry Andric   // Quickly determine whether we have a pointer to an alloca. It's possible
688*0b57cec5SDimitry Andric   // to skip null checks, and some alignment checks, for these pointers. This
689*0b57cec5SDimitry Andric   // can reduce compile-time significantly.
690a7dea167SDimitry Andric   auto PtrToAlloca = dyn_cast<llvm::AllocaInst>(Ptr->stripPointerCasts());
691*0b57cec5SDimitry Andric 
692*0b57cec5SDimitry Andric   llvm::Value *True = llvm::ConstantInt::getTrue(getLLVMContext());
693*0b57cec5SDimitry Andric   llvm::Value *IsNonNull = nullptr;
694*0b57cec5SDimitry Andric   bool IsGuaranteedNonNull =
695*0b57cec5SDimitry Andric       SkippedChecks.has(SanitizerKind::Null) || PtrToAlloca;
696*0b57cec5SDimitry Andric   bool AllowNullPointers = isNullPointerAllowed(TCK);
697*0b57cec5SDimitry Andric   if ((SanOpts.has(SanitizerKind::Null) || AllowNullPointers) &&
698*0b57cec5SDimitry Andric       !IsGuaranteedNonNull) {
699*0b57cec5SDimitry Andric     // The glvalue must not be an empty glvalue.
700*0b57cec5SDimitry Andric     IsNonNull = Builder.CreateIsNotNull(Ptr);
701*0b57cec5SDimitry Andric 
702*0b57cec5SDimitry Andric     // The IR builder can constant-fold the null check if the pointer points to
703*0b57cec5SDimitry Andric     // a constant.
704*0b57cec5SDimitry Andric     IsGuaranteedNonNull = IsNonNull == True;
705*0b57cec5SDimitry Andric 
706*0b57cec5SDimitry Andric     // Skip the null check if the pointer is known to be non-null.
707*0b57cec5SDimitry Andric     if (!IsGuaranteedNonNull) {
708*0b57cec5SDimitry Andric       if (AllowNullPointers) {
709*0b57cec5SDimitry Andric         // When performing pointer casts, it's OK if the value is null.
710*0b57cec5SDimitry Andric         // Skip the remaining checks in that case.
711*0b57cec5SDimitry Andric         Done = createBasicBlock("null");
712*0b57cec5SDimitry Andric         llvm::BasicBlock *Rest = createBasicBlock("not.null");
713*0b57cec5SDimitry Andric         Builder.CreateCondBr(IsNonNull, Rest, Done);
714*0b57cec5SDimitry Andric         EmitBlock(Rest);
715*0b57cec5SDimitry Andric       } else {
716*0b57cec5SDimitry Andric         Checks.push_back(std::make_pair(IsNonNull, SanitizerKind::Null));
717*0b57cec5SDimitry Andric       }
718*0b57cec5SDimitry Andric     }
719*0b57cec5SDimitry Andric   }
720*0b57cec5SDimitry Andric 
721*0b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::ObjectSize) &&
722*0b57cec5SDimitry Andric       !SkippedChecks.has(SanitizerKind::ObjectSize) &&
723*0b57cec5SDimitry Andric       !Ty->isIncompleteType()) {
7245ffd83dbSDimitry Andric     uint64_t TySize = CGM.getMinimumObjectSize(Ty).getQuantity();
725*0b57cec5SDimitry Andric     llvm::Value *Size = llvm::ConstantInt::get(IntPtrTy, TySize);
726*0b57cec5SDimitry Andric     if (ArraySize)
727*0b57cec5SDimitry Andric       Size = Builder.CreateMul(Size, ArraySize);
728*0b57cec5SDimitry Andric 
729*0b57cec5SDimitry Andric     // Degenerate case: new X[0] does not need an objectsize check.
730*0b57cec5SDimitry Andric     llvm::Constant *ConstantSize = dyn_cast<llvm::Constant>(Size);
731*0b57cec5SDimitry Andric     if (!ConstantSize || !ConstantSize->isNullValue()) {
732*0b57cec5SDimitry Andric       // The glvalue must refer to a large enough storage region.
733*0b57cec5SDimitry Andric       // FIXME: If Address Sanitizer is enabled, insert dynamic instrumentation
734*0b57cec5SDimitry Andric       //        to check this.
735*0b57cec5SDimitry Andric       // FIXME: Get object address space
736*0b57cec5SDimitry Andric       llvm::Type *Tys[2] = { IntPtrTy, Int8PtrTy };
737*0b57cec5SDimitry Andric       llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::objectsize, Tys);
738*0b57cec5SDimitry Andric       llvm::Value *Min = Builder.getFalse();
739*0b57cec5SDimitry Andric       llvm::Value *NullIsUnknown = Builder.getFalse();
740*0b57cec5SDimitry Andric       llvm::Value *Dynamic = Builder.getFalse();
741*0b57cec5SDimitry Andric       llvm::Value *CastAddr = Builder.CreateBitCast(Ptr, Int8PtrTy);
742*0b57cec5SDimitry Andric       llvm::Value *LargeEnough = Builder.CreateICmpUGE(
743*0b57cec5SDimitry Andric           Builder.CreateCall(F, {CastAddr, Min, NullIsUnknown, Dynamic}), Size);
744*0b57cec5SDimitry Andric       Checks.push_back(std::make_pair(LargeEnough, SanitizerKind::ObjectSize));
745*0b57cec5SDimitry Andric     }
746*0b57cec5SDimitry Andric   }
747*0b57cec5SDimitry Andric 
748*0b57cec5SDimitry Andric   uint64_t AlignVal = 0;
749*0b57cec5SDimitry Andric   llvm::Value *PtrAsInt = nullptr;
750*0b57cec5SDimitry Andric 
751*0b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::Alignment) &&
752*0b57cec5SDimitry Andric       !SkippedChecks.has(SanitizerKind::Alignment)) {
753*0b57cec5SDimitry Andric     AlignVal = Alignment.getQuantity();
754*0b57cec5SDimitry Andric     if (!Ty->isIncompleteType() && !AlignVal)
7555ffd83dbSDimitry Andric       AlignVal = CGM.getNaturalTypeAlignment(Ty, nullptr, nullptr,
7565ffd83dbSDimitry Andric                                              /*ForPointeeType=*/true)
7575ffd83dbSDimitry Andric                      .getQuantity();
758*0b57cec5SDimitry Andric 
759*0b57cec5SDimitry Andric     // The glvalue must be suitably aligned.
760*0b57cec5SDimitry Andric     if (AlignVal > 1 &&
761*0b57cec5SDimitry Andric         (!PtrToAlloca || PtrToAlloca->getAlignment() < AlignVal)) {
762*0b57cec5SDimitry Andric       PtrAsInt = Builder.CreatePtrToInt(Ptr, IntPtrTy);
763*0b57cec5SDimitry Andric       llvm::Value *Align = Builder.CreateAnd(
764*0b57cec5SDimitry Andric           PtrAsInt, llvm::ConstantInt::get(IntPtrTy, AlignVal - 1));
765*0b57cec5SDimitry Andric       llvm::Value *Aligned =
766*0b57cec5SDimitry Andric           Builder.CreateICmpEQ(Align, llvm::ConstantInt::get(IntPtrTy, 0));
767*0b57cec5SDimitry Andric       if (Aligned != True)
768*0b57cec5SDimitry Andric         Checks.push_back(std::make_pair(Aligned, SanitizerKind::Alignment));
769*0b57cec5SDimitry Andric     }
770*0b57cec5SDimitry Andric   }
771*0b57cec5SDimitry Andric 
772*0b57cec5SDimitry Andric   if (Checks.size() > 0) {
773*0b57cec5SDimitry Andric     // Make sure we're not losing information. Alignment needs to be a power of
774*0b57cec5SDimitry Andric     // 2
775*0b57cec5SDimitry Andric     assert(!AlignVal || (uint64_t)1 << llvm::Log2_64(AlignVal) == AlignVal);
776*0b57cec5SDimitry Andric     llvm::Constant *StaticData[] = {
777*0b57cec5SDimitry Andric         EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(Ty),
778*0b57cec5SDimitry Andric         llvm::ConstantInt::get(Int8Ty, AlignVal ? llvm::Log2_64(AlignVal) : 1),
779*0b57cec5SDimitry Andric         llvm::ConstantInt::get(Int8Ty, TCK)};
780*0b57cec5SDimitry Andric     EmitCheck(Checks, SanitizerHandler::TypeMismatch, StaticData,
781*0b57cec5SDimitry Andric               PtrAsInt ? PtrAsInt : Ptr);
782*0b57cec5SDimitry Andric   }
783*0b57cec5SDimitry Andric 
784*0b57cec5SDimitry Andric   // If possible, check that the vptr indicates that there is a subobject of
785*0b57cec5SDimitry Andric   // type Ty at offset zero within this object.
786*0b57cec5SDimitry Andric   //
787*0b57cec5SDimitry Andric   // C++11 [basic.life]p5,6:
788*0b57cec5SDimitry Andric   //   [For storage which does not refer to an object within its lifetime]
789*0b57cec5SDimitry Andric   //   The program has undefined behavior if:
790*0b57cec5SDimitry Andric   //    -- the [pointer or glvalue] is used to access a non-static data member
791*0b57cec5SDimitry Andric   //       or call a non-static member function
792*0b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::Vptr) &&
793*0b57cec5SDimitry Andric       !SkippedChecks.has(SanitizerKind::Vptr) && isVptrCheckRequired(TCK, Ty)) {
794*0b57cec5SDimitry Andric     // Ensure that the pointer is non-null before loading it. If there is no
795*0b57cec5SDimitry Andric     // compile-time guarantee, reuse the run-time null check or emit a new one.
796*0b57cec5SDimitry Andric     if (!IsGuaranteedNonNull) {
797*0b57cec5SDimitry Andric       if (!IsNonNull)
798*0b57cec5SDimitry Andric         IsNonNull = Builder.CreateIsNotNull(Ptr);
799*0b57cec5SDimitry Andric       if (!Done)
800*0b57cec5SDimitry Andric         Done = createBasicBlock("vptr.null");
801*0b57cec5SDimitry Andric       llvm::BasicBlock *VptrNotNull = createBasicBlock("vptr.not.null");
802*0b57cec5SDimitry Andric       Builder.CreateCondBr(IsNonNull, VptrNotNull, Done);
803*0b57cec5SDimitry Andric       EmitBlock(VptrNotNull);
804*0b57cec5SDimitry Andric     }
805*0b57cec5SDimitry Andric 
806*0b57cec5SDimitry Andric     // Compute a hash of the mangled name of the type.
807*0b57cec5SDimitry Andric     //
808*0b57cec5SDimitry Andric     // FIXME: This is not guaranteed to be deterministic! Move to a
809*0b57cec5SDimitry Andric     //        fingerprinting mechanism once LLVM provides one. For the time
810*0b57cec5SDimitry Andric     //        being the implementation happens to be deterministic.
811*0b57cec5SDimitry Andric     SmallString<64> MangledName;
812*0b57cec5SDimitry Andric     llvm::raw_svector_ostream Out(MangledName);
813*0b57cec5SDimitry Andric     CGM.getCXXABI().getMangleContext().mangleCXXRTTI(Ty.getUnqualifiedType(),
814*0b57cec5SDimitry Andric                                                      Out);
815*0b57cec5SDimitry Andric 
816fe6060f1SDimitry Andric     // Contained in NoSanitizeList based on the mangled type.
817fe6060f1SDimitry Andric     if (!CGM.getContext().getNoSanitizeList().containsType(SanitizerKind::Vptr,
818fe6060f1SDimitry Andric                                                            Out.str())) {
819*0b57cec5SDimitry Andric       llvm::hash_code TypeHash = hash_value(Out.str());
820*0b57cec5SDimitry Andric 
821*0b57cec5SDimitry Andric       // Load the vptr, and compute hash_16_bytes(TypeHash, vptr).
822*0b57cec5SDimitry Andric       llvm::Value *Low = llvm::ConstantInt::get(Int64Ty, TypeHash);
823*0b57cec5SDimitry Andric       llvm::Type *VPtrTy = llvm::PointerType::get(IntPtrTy, 0);
824*0b57cec5SDimitry Andric       Address VPtrAddr(Builder.CreateBitCast(Ptr, VPtrTy), getPointerAlign());
825*0b57cec5SDimitry Andric       llvm::Value *VPtrVal = Builder.CreateLoad(VPtrAddr);
826*0b57cec5SDimitry Andric       llvm::Value *High = Builder.CreateZExt(VPtrVal, Int64Ty);
827*0b57cec5SDimitry Andric 
828*0b57cec5SDimitry Andric       llvm::Value *Hash = emitHash16Bytes(Builder, Low, High);
829*0b57cec5SDimitry Andric       Hash = Builder.CreateTrunc(Hash, IntPtrTy);
830*0b57cec5SDimitry Andric 
831*0b57cec5SDimitry Andric       // Look the hash up in our cache.
832*0b57cec5SDimitry Andric       const int CacheSize = 128;
833*0b57cec5SDimitry Andric       llvm::Type *HashTable = llvm::ArrayType::get(IntPtrTy, CacheSize);
834*0b57cec5SDimitry Andric       llvm::Value *Cache = CGM.CreateRuntimeVariable(HashTable,
835*0b57cec5SDimitry Andric                                                      "__ubsan_vptr_type_cache");
836*0b57cec5SDimitry Andric       llvm::Value *Slot = Builder.CreateAnd(Hash,
837*0b57cec5SDimitry Andric                                             llvm::ConstantInt::get(IntPtrTy,
838*0b57cec5SDimitry Andric                                                                    CacheSize-1));
839*0b57cec5SDimitry Andric       llvm::Value *Indices[] = { Builder.getInt32(0), Slot };
840fe6060f1SDimitry Andric       llvm::Value *CacheVal = Builder.CreateAlignedLoad(
841fe6060f1SDimitry Andric           IntPtrTy, Builder.CreateInBoundsGEP(HashTable, Cache, Indices),
842*0b57cec5SDimitry Andric           getPointerAlign());
843*0b57cec5SDimitry Andric 
844*0b57cec5SDimitry Andric       // If the hash isn't in the cache, call a runtime handler to perform the
845*0b57cec5SDimitry Andric       // hard work of checking whether the vptr is for an object of the right
846*0b57cec5SDimitry Andric       // type. This will either fill in the cache and return, or produce a
847*0b57cec5SDimitry Andric       // diagnostic.
848*0b57cec5SDimitry Andric       llvm::Value *EqualHash = Builder.CreateICmpEQ(CacheVal, Hash);
849*0b57cec5SDimitry Andric       llvm::Constant *StaticData[] = {
850*0b57cec5SDimitry Andric         EmitCheckSourceLocation(Loc),
851*0b57cec5SDimitry Andric         EmitCheckTypeDescriptor(Ty),
852*0b57cec5SDimitry Andric         CGM.GetAddrOfRTTIDescriptor(Ty.getUnqualifiedType()),
853*0b57cec5SDimitry Andric         llvm::ConstantInt::get(Int8Ty, TCK)
854*0b57cec5SDimitry Andric       };
855*0b57cec5SDimitry Andric       llvm::Value *DynamicData[] = { Ptr, Hash };
856*0b57cec5SDimitry Andric       EmitCheck(std::make_pair(EqualHash, SanitizerKind::Vptr),
857*0b57cec5SDimitry Andric                 SanitizerHandler::DynamicTypeCacheMiss, StaticData,
858*0b57cec5SDimitry Andric                 DynamicData);
859*0b57cec5SDimitry Andric     }
860*0b57cec5SDimitry Andric   }
861*0b57cec5SDimitry Andric 
862*0b57cec5SDimitry Andric   if (Done) {
863*0b57cec5SDimitry Andric     Builder.CreateBr(Done);
864*0b57cec5SDimitry Andric     EmitBlock(Done);
865*0b57cec5SDimitry Andric   }
866*0b57cec5SDimitry Andric }
867*0b57cec5SDimitry Andric 
868*0b57cec5SDimitry Andric /// Determine whether this expression refers to a flexible array member in a
869*0b57cec5SDimitry Andric /// struct. We disable array bounds checks for such members.
870*0b57cec5SDimitry Andric static bool isFlexibleArrayMemberExpr(const Expr *E) {
871*0b57cec5SDimitry Andric   // For compatibility with existing code, we treat arrays of length 0 or
872*0b57cec5SDimitry Andric   // 1 as flexible array members.
8735ffd83dbSDimitry Andric   // FIXME: This is inconsistent with the warning code in SemaChecking. Unify
8745ffd83dbSDimitry Andric   // the two mechanisms.
875*0b57cec5SDimitry Andric   const ArrayType *AT = E->getType()->castAsArrayTypeUnsafe();
876*0b57cec5SDimitry Andric   if (const auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
8775ffd83dbSDimitry Andric     // FIXME: Sema doesn't treat [1] as a flexible array member if the bound
8785ffd83dbSDimitry Andric     // was produced by macro expansion.
879*0b57cec5SDimitry Andric     if (CAT->getSize().ugt(1))
880*0b57cec5SDimitry Andric       return false;
881*0b57cec5SDimitry Andric   } else if (!isa<IncompleteArrayType>(AT))
882*0b57cec5SDimitry Andric     return false;
883*0b57cec5SDimitry Andric 
884*0b57cec5SDimitry Andric   E = E->IgnoreParens();
885*0b57cec5SDimitry Andric 
886*0b57cec5SDimitry Andric   // A flexible array member must be the last member in the class.
887*0b57cec5SDimitry Andric   if (const auto *ME = dyn_cast<MemberExpr>(E)) {
888*0b57cec5SDimitry Andric     // FIXME: If the base type of the member expr is not FD->getParent(),
889*0b57cec5SDimitry Andric     // this should not be treated as a flexible array member access.
890*0b57cec5SDimitry Andric     if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
8915ffd83dbSDimitry Andric       // FIXME: Sema doesn't treat a T[1] union member as a flexible array
8925ffd83dbSDimitry Andric       // member, only a T[0] or T[] member gets that treatment.
8935ffd83dbSDimitry Andric       if (FD->getParent()->isUnion())
8945ffd83dbSDimitry Andric         return true;
895*0b57cec5SDimitry Andric       RecordDecl::field_iterator FI(
896*0b57cec5SDimitry Andric           DeclContext::decl_iterator(const_cast<FieldDecl *>(FD)));
897*0b57cec5SDimitry Andric       return ++FI == FD->getParent()->field_end();
898*0b57cec5SDimitry Andric     }
899*0b57cec5SDimitry Andric   } else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E)) {
900*0b57cec5SDimitry Andric     return IRE->getDecl()->getNextIvar() == nullptr;
901*0b57cec5SDimitry Andric   }
902*0b57cec5SDimitry Andric 
903*0b57cec5SDimitry Andric   return false;
904*0b57cec5SDimitry Andric }
905*0b57cec5SDimitry Andric 
906*0b57cec5SDimitry Andric llvm::Value *CodeGenFunction::LoadPassedObjectSize(const Expr *E,
907*0b57cec5SDimitry Andric                                                    QualType EltTy) {
908*0b57cec5SDimitry Andric   ASTContext &C = getContext();
909*0b57cec5SDimitry Andric   uint64_t EltSize = C.getTypeSizeInChars(EltTy).getQuantity();
910*0b57cec5SDimitry Andric   if (!EltSize)
911*0b57cec5SDimitry Andric     return nullptr;
912*0b57cec5SDimitry Andric 
913*0b57cec5SDimitry Andric   auto *ArrayDeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
914*0b57cec5SDimitry Andric   if (!ArrayDeclRef)
915*0b57cec5SDimitry Andric     return nullptr;
916*0b57cec5SDimitry Andric 
917*0b57cec5SDimitry Andric   auto *ParamDecl = dyn_cast<ParmVarDecl>(ArrayDeclRef->getDecl());
918*0b57cec5SDimitry Andric   if (!ParamDecl)
919*0b57cec5SDimitry Andric     return nullptr;
920*0b57cec5SDimitry Andric 
921*0b57cec5SDimitry Andric   auto *POSAttr = ParamDecl->getAttr<PassObjectSizeAttr>();
922*0b57cec5SDimitry Andric   if (!POSAttr)
923*0b57cec5SDimitry Andric     return nullptr;
924*0b57cec5SDimitry Andric 
925*0b57cec5SDimitry Andric   // Don't load the size if it's a lower bound.
926*0b57cec5SDimitry Andric   int POSType = POSAttr->getType();
927*0b57cec5SDimitry Andric   if (POSType != 0 && POSType != 1)
928*0b57cec5SDimitry Andric     return nullptr;
929*0b57cec5SDimitry Andric 
930*0b57cec5SDimitry Andric   // Find the implicit size parameter.
931*0b57cec5SDimitry Andric   auto PassedSizeIt = SizeArguments.find(ParamDecl);
932*0b57cec5SDimitry Andric   if (PassedSizeIt == SizeArguments.end())
933*0b57cec5SDimitry Andric     return nullptr;
934*0b57cec5SDimitry Andric 
935*0b57cec5SDimitry Andric   const ImplicitParamDecl *PassedSizeDecl = PassedSizeIt->second;
936*0b57cec5SDimitry Andric   assert(LocalDeclMap.count(PassedSizeDecl) && "Passed size not loadable");
937*0b57cec5SDimitry Andric   Address AddrOfSize = LocalDeclMap.find(PassedSizeDecl)->second;
938*0b57cec5SDimitry Andric   llvm::Value *SizeInBytes = EmitLoadOfScalar(AddrOfSize, /*Volatile=*/false,
939*0b57cec5SDimitry Andric                                               C.getSizeType(), E->getExprLoc());
940*0b57cec5SDimitry Andric   llvm::Value *SizeOfElement =
941*0b57cec5SDimitry Andric       llvm::ConstantInt::get(SizeInBytes->getType(), EltSize);
942*0b57cec5SDimitry Andric   return Builder.CreateUDiv(SizeInBytes, SizeOfElement);
943*0b57cec5SDimitry Andric }
944*0b57cec5SDimitry Andric 
945*0b57cec5SDimitry Andric /// If Base is known to point to the start of an array, return the length of
946*0b57cec5SDimitry Andric /// that array. Return 0 if the length cannot be determined.
947*0b57cec5SDimitry Andric static llvm::Value *getArrayIndexingBound(
948*0b57cec5SDimitry Andric     CodeGenFunction &CGF, const Expr *Base, QualType &IndexedType) {
949*0b57cec5SDimitry Andric   // For the vector indexing extension, the bound is the number of elements.
950*0b57cec5SDimitry Andric   if (const VectorType *VT = Base->getType()->getAs<VectorType>()) {
951*0b57cec5SDimitry Andric     IndexedType = Base->getType();
952*0b57cec5SDimitry Andric     return CGF.Builder.getInt32(VT->getNumElements());
953*0b57cec5SDimitry Andric   }
954*0b57cec5SDimitry Andric 
955*0b57cec5SDimitry Andric   Base = Base->IgnoreParens();
956*0b57cec5SDimitry Andric 
957*0b57cec5SDimitry Andric   if (const auto *CE = dyn_cast<CastExpr>(Base)) {
958*0b57cec5SDimitry Andric     if (CE->getCastKind() == CK_ArrayToPointerDecay &&
959*0b57cec5SDimitry Andric         !isFlexibleArrayMemberExpr(CE->getSubExpr())) {
960*0b57cec5SDimitry Andric       IndexedType = CE->getSubExpr()->getType();
961*0b57cec5SDimitry Andric       const ArrayType *AT = IndexedType->castAsArrayTypeUnsafe();
962*0b57cec5SDimitry Andric       if (const auto *CAT = dyn_cast<ConstantArrayType>(AT))
963*0b57cec5SDimitry Andric         return CGF.Builder.getInt(CAT->getSize());
964*0b57cec5SDimitry Andric       else if (const auto *VAT = dyn_cast<VariableArrayType>(AT))
965*0b57cec5SDimitry Andric         return CGF.getVLASize(VAT).NumElts;
966*0b57cec5SDimitry Andric       // Ignore pass_object_size here. It's not applicable on decayed pointers.
967*0b57cec5SDimitry Andric     }
968*0b57cec5SDimitry Andric   }
969*0b57cec5SDimitry Andric 
970*0b57cec5SDimitry Andric   QualType EltTy{Base->getType()->getPointeeOrArrayElementType(), 0};
971*0b57cec5SDimitry Andric   if (llvm::Value *POS = CGF.LoadPassedObjectSize(Base, EltTy)) {
972*0b57cec5SDimitry Andric     IndexedType = Base->getType();
973*0b57cec5SDimitry Andric     return POS;
974*0b57cec5SDimitry Andric   }
975*0b57cec5SDimitry Andric 
976*0b57cec5SDimitry Andric   return nullptr;
977*0b57cec5SDimitry Andric }
978*0b57cec5SDimitry Andric 
979*0b57cec5SDimitry Andric void CodeGenFunction::EmitBoundsCheck(const Expr *E, const Expr *Base,
980*0b57cec5SDimitry Andric                                       llvm::Value *Index, QualType IndexType,
981*0b57cec5SDimitry Andric                                       bool Accessed) {
982*0b57cec5SDimitry Andric   assert(SanOpts.has(SanitizerKind::ArrayBounds) &&
983*0b57cec5SDimitry Andric          "should not be called unless adding bounds checks");
984*0b57cec5SDimitry Andric   SanitizerScope SanScope(this);
985*0b57cec5SDimitry Andric 
986*0b57cec5SDimitry Andric   QualType IndexedType;
987*0b57cec5SDimitry Andric   llvm::Value *Bound = getArrayIndexingBound(*this, Base, IndexedType);
988*0b57cec5SDimitry Andric   if (!Bound)
989*0b57cec5SDimitry Andric     return;
990*0b57cec5SDimitry Andric 
991*0b57cec5SDimitry Andric   bool IndexSigned = IndexType->isSignedIntegerOrEnumerationType();
992*0b57cec5SDimitry Andric   llvm::Value *IndexVal = Builder.CreateIntCast(Index, SizeTy, IndexSigned);
993*0b57cec5SDimitry Andric   llvm::Value *BoundVal = Builder.CreateIntCast(Bound, SizeTy, false);
994*0b57cec5SDimitry Andric 
995*0b57cec5SDimitry Andric   llvm::Constant *StaticData[] = {
996*0b57cec5SDimitry Andric     EmitCheckSourceLocation(E->getExprLoc()),
997*0b57cec5SDimitry Andric     EmitCheckTypeDescriptor(IndexedType),
998*0b57cec5SDimitry Andric     EmitCheckTypeDescriptor(IndexType)
999*0b57cec5SDimitry Andric   };
1000*0b57cec5SDimitry Andric   llvm::Value *Check = Accessed ? Builder.CreateICmpULT(IndexVal, BoundVal)
1001*0b57cec5SDimitry Andric                                 : Builder.CreateICmpULE(IndexVal, BoundVal);
1002*0b57cec5SDimitry Andric   EmitCheck(std::make_pair(Check, SanitizerKind::ArrayBounds),
1003*0b57cec5SDimitry Andric             SanitizerHandler::OutOfBounds, StaticData, Index);
1004*0b57cec5SDimitry Andric }
1005*0b57cec5SDimitry Andric 
1006*0b57cec5SDimitry Andric 
1007*0b57cec5SDimitry Andric CodeGenFunction::ComplexPairTy CodeGenFunction::
1008*0b57cec5SDimitry Andric EmitComplexPrePostIncDec(const UnaryOperator *E, LValue LV,
1009*0b57cec5SDimitry Andric                          bool isInc, bool isPre) {
1010*0b57cec5SDimitry Andric   ComplexPairTy InVal = EmitLoadOfComplex(LV, E->getExprLoc());
1011*0b57cec5SDimitry Andric 
1012*0b57cec5SDimitry Andric   llvm::Value *NextVal;
1013*0b57cec5SDimitry Andric   if (isa<llvm::IntegerType>(InVal.first->getType())) {
1014*0b57cec5SDimitry Andric     uint64_t AmountVal = isInc ? 1 : -1;
1015*0b57cec5SDimitry Andric     NextVal = llvm::ConstantInt::get(InVal.first->getType(), AmountVal, true);
1016*0b57cec5SDimitry Andric 
1017*0b57cec5SDimitry Andric     // Add the inc/dec to the real part.
1018*0b57cec5SDimitry Andric     NextVal = Builder.CreateAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
1019*0b57cec5SDimitry Andric   } else {
1020a7dea167SDimitry Andric     QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
1021*0b57cec5SDimitry Andric     llvm::APFloat FVal(getContext().getFloatTypeSemantics(ElemTy), 1);
1022*0b57cec5SDimitry Andric     if (!isInc)
1023*0b57cec5SDimitry Andric       FVal.changeSign();
1024*0b57cec5SDimitry Andric     NextVal = llvm::ConstantFP::get(getLLVMContext(), FVal);
1025*0b57cec5SDimitry Andric 
1026*0b57cec5SDimitry Andric     // Add the inc/dec to the real part.
1027*0b57cec5SDimitry Andric     NextVal = Builder.CreateFAdd(InVal.first, NextVal, isInc ? "inc" : "dec");
1028*0b57cec5SDimitry Andric   }
1029*0b57cec5SDimitry Andric 
1030*0b57cec5SDimitry Andric   ComplexPairTy IncVal(NextVal, InVal.second);
1031*0b57cec5SDimitry Andric 
1032*0b57cec5SDimitry Andric   // Store the updated result through the lvalue.
1033*0b57cec5SDimitry Andric   EmitStoreOfComplex(IncVal, LV, /*init*/ false);
1034480093f4SDimitry Andric   if (getLangOpts().OpenMP)
1035480093f4SDimitry Andric     CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
1036480093f4SDimitry Andric                                                               E->getSubExpr());
1037*0b57cec5SDimitry Andric 
1038*0b57cec5SDimitry Andric   // If this is a postinc, return the value read from memory, otherwise use the
1039*0b57cec5SDimitry Andric   // updated value.
1040*0b57cec5SDimitry Andric   return isPre ? IncVal : InVal;
1041*0b57cec5SDimitry Andric }
1042*0b57cec5SDimitry Andric 
1043*0b57cec5SDimitry Andric void CodeGenModule::EmitExplicitCastExprType(const ExplicitCastExpr *E,
1044*0b57cec5SDimitry Andric                                              CodeGenFunction *CGF) {
1045*0b57cec5SDimitry Andric   // Bind VLAs in the cast type.
1046*0b57cec5SDimitry Andric   if (CGF && E->getType()->isVariablyModifiedType())
1047*0b57cec5SDimitry Andric     CGF->EmitVariablyModifiedType(E->getType());
1048*0b57cec5SDimitry Andric 
1049*0b57cec5SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
1050*0b57cec5SDimitry Andric     DI->EmitExplicitCastType(E->getType());
1051*0b57cec5SDimitry Andric }
1052*0b57cec5SDimitry Andric 
1053*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1054*0b57cec5SDimitry Andric //                         LValue Expression Emission
1055*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1056*0b57cec5SDimitry Andric 
1057*0b57cec5SDimitry Andric /// EmitPointerWithAlignment - Given an expression of pointer type, try to
1058*0b57cec5SDimitry Andric /// derive a more accurate bound on the alignment of the pointer.
1059*0b57cec5SDimitry Andric Address CodeGenFunction::EmitPointerWithAlignment(const Expr *E,
1060*0b57cec5SDimitry Andric                                                   LValueBaseInfo *BaseInfo,
1061*0b57cec5SDimitry Andric                                                   TBAAAccessInfo *TBAAInfo) {
1062*0b57cec5SDimitry Andric   // We allow this with ObjC object pointers because of fragile ABIs.
1063*0b57cec5SDimitry Andric   assert(E->getType()->isPointerType() ||
1064*0b57cec5SDimitry Andric          E->getType()->isObjCObjectPointerType());
1065*0b57cec5SDimitry Andric   E = E->IgnoreParens();
1066*0b57cec5SDimitry Andric 
1067*0b57cec5SDimitry Andric   // Casts:
1068*0b57cec5SDimitry Andric   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1069*0b57cec5SDimitry Andric     if (const auto *ECE = dyn_cast<ExplicitCastExpr>(CE))
1070*0b57cec5SDimitry Andric       CGM.EmitExplicitCastExprType(ECE, this);
1071*0b57cec5SDimitry Andric 
1072*0b57cec5SDimitry Andric     switch (CE->getCastKind()) {
1073*0b57cec5SDimitry Andric     // Non-converting casts (but not C's implicit conversion from void*).
1074*0b57cec5SDimitry Andric     case CK_BitCast:
1075*0b57cec5SDimitry Andric     case CK_NoOp:
1076*0b57cec5SDimitry Andric     case CK_AddressSpaceConversion:
1077*0b57cec5SDimitry Andric       if (auto PtrTy = CE->getSubExpr()->getType()->getAs<PointerType>()) {
1078*0b57cec5SDimitry Andric         if (PtrTy->getPointeeType()->isVoidType())
1079*0b57cec5SDimitry Andric           break;
1080*0b57cec5SDimitry Andric 
1081*0b57cec5SDimitry Andric         LValueBaseInfo InnerBaseInfo;
1082*0b57cec5SDimitry Andric         TBAAAccessInfo InnerTBAAInfo;
1083*0b57cec5SDimitry Andric         Address Addr = EmitPointerWithAlignment(CE->getSubExpr(),
1084*0b57cec5SDimitry Andric                                                 &InnerBaseInfo,
1085*0b57cec5SDimitry Andric                                                 &InnerTBAAInfo);
1086*0b57cec5SDimitry Andric         if (BaseInfo) *BaseInfo = InnerBaseInfo;
1087*0b57cec5SDimitry Andric         if (TBAAInfo) *TBAAInfo = InnerTBAAInfo;
1088*0b57cec5SDimitry Andric 
1089*0b57cec5SDimitry Andric         if (isa<ExplicitCastExpr>(CE)) {
1090*0b57cec5SDimitry Andric           LValueBaseInfo TargetTypeBaseInfo;
1091*0b57cec5SDimitry Andric           TBAAAccessInfo TargetTypeTBAAInfo;
10925ffd83dbSDimitry Andric           CharUnits Align = CGM.getNaturalPointeeTypeAlignment(
10935ffd83dbSDimitry Andric               E->getType(), &TargetTypeBaseInfo, &TargetTypeTBAAInfo);
1094*0b57cec5SDimitry Andric           if (TBAAInfo)
1095*0b57cec5SDimitry Andric             *TBAAInfo = CGM.mergeTBAAInfoForCast(*TBAAInfo,
1096*0b57cec5SDimitry Andric                                                  TargetTypeTBAAInfo);
1097*0b57cec5SDimitry Andric           // If the source l-value is opaque, honor the alignment of the
1098*0b57cec5SDimitry Andric           // casted-to type.
1099*0b57cec5SDimitry Andric           if (InnerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
1100*0b57cec5SDimitry Andric             if (BaseInfo)
1101*0b57cec5SDimitry Andric               BaseInfo->mergeForCast(TargetTypeBaseInfo);
11020eae32dcSDimitry Andric             Addr = Address(Addr.getPointer(), Addr.getElementType(), Align);
1103*0b57cec5SDimitry Andric           }
1104*0b57cec5SDimitry Andric         }
1105*0b57cec5SDimitry Andric 
1106*0b57cec5SDimitry Andric         if (SanOpts.has(SanitizerKind::CFIUnrelatedCast) &&
1107*0b57cec5SDimitry Andric             CE->getCastKind() == CK_BitCast) {
1108*0b57cec5SDimitry Andric           if (auto PT = E->getType()->getAs<PointerType>())
1109*0b57cec5SDimitry Andric             EmitVTablePtrCheckForCast(PT->getPointeeType(), Addr.getPointer(),
1110*0b57cec5SDimitry Andric                                       /*MayBeNull=*/true,
1111*0b57cec5SDimitry Andric                                       CodeGenFunction::CFITCK_UnrelatedCast,
1112*0b57cec5SDimitry Andric                                       CE->getBeginLoc());
1113*0b57cec5SDimitry Andric         }
11140eae32dcSDimitry Andric 
11150eae32dcSDimitry Andric         if (CE->getCastKind() == CK_AddressSpaceConversion)
11160eae32dcSDimitry Andric          return Builder.CreateAddrSpaceCast(Addr, ConvertType(E->getType()));
11170eae32dcSDimitry Andric 
11180eae32dcSDimitry Andric         llvm::Type *ElemTy = ConvertTypeForMem(E->getType()->getPointeeType());
11190eae32dcSDimitry Andric         return Builder.CreateElementBitCast(Addr, ElemTy);
1120*0b57cec5SDimitry Andric       }
1121*0b57cec5SDimitry Andric       break;
1122*0b57cec5SDimitry Andric 
1123*0b57cec5SDimitry Andric     // Array-to-pointer decay.
1124*0b57cec5SDimitry Andric     case CK_ArrayToPointerDecay:
1125*0b57cec5SDimitry Andric       return EmitArrayToPointerDecay(CE->getSubExpr(), BaseInfo, TBAAInfo);
1126*0b57cec5SDimitry Andric 
1127*0b57cec5SDimitry Andric     // Derived-to-base conversions.
1128*0b57cec5SDimitry Andric     case CK_UncheckedDerivedToBase:
1129*0b57cec5SDimitry Andric     case CK_DerivedToBase: {
1130*0b57cec5SDimitry Andric       // TODO: Support accesses to members of base classes in TBAA. For now, we
1131*0b57cec5SDimitry Andric       // conservatively pretend that the complete object is of the base class
1132*0b57cec5SDimitry Andric       // type.
1133*0b57cec5SDimitry Andric       if (TBAAInfo)
1134*0b57cec5SDimitry Andric         *TBAAInfo = CGM.getTBAAAccessInfo(E->getType());
1135*0b57cec5SDimitry Andric       Address Addr = EmitPointerWithAlignment(CE->getSubExpr(), BaseInfo);
1136*0b57cec5SDimitry Andric       auto Derived = CE->getSubExpr()->getType()->getPointeeCXXRecordDecl();
1137*0b57cec5SDimitry Andric       return GetAddressOfBaseClass(Addr, Derived,
1138*0b57cec5SDimitry Andric                                    CE->path_begin(), CE->path_end(),
1139*0b57cec5SDimitry Andric                                    ShouldNullCheckClassCastValue(CE),
1140*0b57cec5SDimitry Andric                                    CE->getExprLoc());
1141*0b57cec5SDimitry Andric     }
1142*0b57cec5SDimitry Andric 
1143*0b57cec5SDimitry Andric     // TODO: Is there any reason to treat base-to-derived conversions
1144*0b57cec5SDimitry Andric     // specially?
1145*0b57cec5SDimitry Andric     default:
1146*0b57cec5SDimitry Andric       break;
1147*0b57cec5SDimitry Andric     }
1148*0b57cec5SDimitry Andric   }
1149*0b57cec5SDimitry Andric 
1150*0b57cec5SDimitry Andric   // Unary &.
1151*0b57cec5SDimitry Andric   if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1152*0b57cec5SDimitry Andric     if (UO->getOpcode() == UO_AddrOf) {
1153*0b57cec5SDimitry Andric       LValue LV = EmitLValue(UO->getSubExpr());
1154*0b57cec5SDimitry Andric       if (BaseInfo) *BaseInfo = LV.getBaseInfo();
1155*0b57cec5SDimitry Andric       if (TBAAInfo) *TBAAInfo = LV.getTBAAInfo();
1156480093f4SDimitry Andric       return LV.getAddress(*this);
1157*0b57cec5SDimitry Andric     }
1158*0b57cec5SDimitry Andric   }
1159*0b57cec5SDimitry Andric 
1160*0b57cec5SDimitry Andric   // TODO: conditional operators, comma.
1161*0b57cec5SDimitry Andric 
1162*0b57cec5SDimitry Andric   // Otherwise, use the alignment of the type.
11635ffd83dbSDimitry Andric   CharUnits Align =
11645ffd83dbSDimitry Andric       CGM.getNaturalPointeeTypeAlignment(E->getType(), BaseInfo, TBAAInfo);
11650eae32dcSDimitry Andric   llvm::Type *ElemTy = ConvertTypeForMem(E->getType()->getPointeeType());
11660eae32dcSDimitry Andric   return Address(EmitScalarExpr(E), ElemTy, Align);
1167*0b57cec5SDimitry Andric }
1168*0b57cec5SDimitry Andric 
1169e8d8bef9SDimitry Andric llvm::Value *CodeGenFunction::EmitNonNullRValueCheck(RValue RV, QualType T) {
1170e8d8bef9SDimitry Andric   llvm::Value *V = RV.getScalarVal();
1171e8d8bef9SDimitry Andric   if (auto MPT = T->getAs<MemberPointerType>())
1172e8d8bef9SDimitry Andric     return CGM.getCXXABI().EmitMemberPointerIsNotNull(*this, V, MPT);
1173e8d8bef9SDimitry Andric   return Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
1174e8d8bef9SDimitry Andric }
1175e8d8bef9SDimitry Andric 
1176*0b57cec5SDimitry Andric RValue CodeGenFunction::GetUndefRValue(QualType Ty) {
1177*0b57cec5SDimitry Andric   if (Ty->isVoidType())
1178*0b57cec5SDimitry Andric     return RValue::get(nullptr);
1179*0b57cec5SDimitry Andric 
1180*0b57cec5SDimitry Andric   switch (getEvaluationKind(Ty)) {
1181*0b57cec5SDimitry Andric   case TEK_Complex: {
1182*0b57cec5SDimitry Andric     llvm::Type *EltTy =
1183*0b57cec5SDimitry Andric       ConvertType(Ty->castAs<ComplexType>()->getElementType());
1184*0b57cec5SDimitry Andric     llvm::Value *U = llvm::UndefValue::get(EltTy);
1185*0b57cec5SDimitry Andric     return RValue::getComplex(std::make_pair(U, U));
1186*0b57cec5SDimitry Andric   }
1187*0b57cec5SDimitry Andric 
1188*0b57cec5SDimitry Andric   // If this is a use of an undefined aggregate type, the aggregate must have an
1189*0b57cec5SDimitry Andric   // identifiable address.  Just because the contents of the value are undefined
1190*0b57cec5SDimitry Andric   // doesn't mean that the address can't be taken and compared.
1191*0b57cec5SDimitry Andric   case TEK_Aggregate: {
1192*0b57cec5SDimitry Andric     Address DestPtr = CreateMemTemp(Ty, "undef.agg.tmp");
1193*0b57cec5SDimitry Andric     return RValue::getAggregate(DestPtr);
1194*0b57cec5SDimitry Andric   }
1195*0b57cec5SDimitry Andric 
1196*0b57cec5SDimitry Andric   case TEK_Scalar:
1197*0b57cec5SDimitry Andric     return RValue::get(llvm::UndefValue::get(ConvertType(Ty)));
1198*0b57cec5SDimitry Andric   }
1199*0b57cec5SDimitry Andric   llvm_unreachable("bad evaluation kind");
1200*0b57cec5SDimitry Andric }
1201*0b57cec5SDimitry Andric 
1202*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitUnsupportedRValue(const Expr *E,
1203*0b57cec5SDimitry Andric                                               const char *Name) {
1204*0b57cec5SDimitry Andric   ErrorUnsupported(E, Name);
1205*0b57cec5SDimitry Andric   return GetUndefRValue(E->getType());
1206*0b57cec5SDimitry Andric }
1207*0b57cec5SDimitry Andric 
1208*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitUnsupportedLValue(const Expr *E,
1209*0b57cec5SDimitry Andric                                               const char *Name) {
1210*0b57cec5SDimitry Andric   ErrorUnsupported(E, Name);
1211*0b57cec5SDimitry Andric   llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
1212*0b57cec5SDimitry Andric   return MakeAddrLValue(Address(llvm::UndefValue::get(Ty), CharUnits::One()),
1213*0b57cec5SDimitry Andric                         E->getType());
1214*0b57cec5SDimitry Andric }
1215*0b57cec5SDimitry Andric 
1216*0b57cec5SDimitry Andric bool CodeGenFunction::IsWrappedCXXThis(const Expr *Obj) {
1217*0b57cec5SDimitry Andric   const Expr *Base = Obj;
1218*0b57cec5SDimitry Andric   while (!isa<CXXThisExpr>(Base)) {
1219*0b57cec5SDimitry Andric     // The result of a dynamic_cast can be null.
1220*0b57cec5SDimitry Andric     if (isa<CXXDynamicCastExpr>(Base))
1221*0b57cec5SDimitry Andric       return false;
1222*0b57cec5SDimitry Andric 
1223*0b57cec5SDimitry Andric     if (const auto *CE = dyn_cast<CastExpr>(Base)) {
1224*0b57cec5SDimitry Andric       Base = CE->getSubExpr();
1225*0b57cec5SDimitry Andric     } else if (const auto *PE = dyn_cast<ParenExpr>(Base)) {
1226*0b57cec5SDimitry Andric       Base = PE->getSubExpr();
1227*0b57cec5SDimitry Andric     } else if (const auto *UO = dyn_cast<UnaryOperator>(Base)) {
1228*0b57cec5SDimitry Andric       if (UO->getOpcode() == UO_Extension)
1229*0b57cec5SDimitry Andric         Base = UO->getSubExpr();
1230*0b57cec5SDimitry Andric       else
1231*0b57cec5SDimitry Andric         return false;
1232*0b57cec5SDimitry Andric     } else {
1233*0b57cec5SDimitry Andric       return false;
1234*0b57cec5SDimitry Andric     }
1235*0b57cec5SDimitry Andric   }
1236*0b57cec5SDimitry Andric   return true;
1237*0b57cec5SDimitry Andric }
1238*0b57cec5SDimitry Andric 
1239*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitCheckedLValue(const Expr *E, TypeCheckKind TCK) {
1240*0b57cec5SDimitry Andric   LValue LV;
1241*0b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::ArrayBounds) && isa<ArraySubscriptExpr>(E))
1242*0b57cec5SDimitry Andric     LV = EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E), /*Accessed*/true);
1243*0b57cec5SDimitry Andric   else
1244*0b57cec5SDimitry Andric     LV = EmitLValue(E);
1245*0b57cec5SDimitry Andric   if (!isa<DeclRefExpr>(E) && !LV.isBitField() && LV.isSimple()) {
1246*0b57cec5SDimitry Andric     SanitizerSet SkippedChecks;
1247*0b57cec5SDimitry Andric     if (const auto *ME = dyn_cast<MemberExpr>(E)) {
1248*0b57cec5SDimitry Andric       bool IsBaseCXXThis = IsWrappedCXXThis(ME->getBase());
1249*0b57cec5SDimitry Andric       if (IsBaseCXXThis)
1250*0b57cec5SDimitry Andric         SkippedChecks.set(SanitizerKind::Alignment, true);
1251*0b57cec5SDimitry Andric       if (IsBaseCXXThis || isa<DeclRefExpr>(ME->getBase()))
1252*0b57cec5SDimitry Andric         SkippedChecks.set(SanitizerKind::Null, true);
1253*0b57cec5SDimitry Andric     }
1254480093f4SDimitry Andric     EmitTypeCheck(TCK, E->getExprLoc(), LV.getPointer(*this), E->getType(),
1255480093f4SDimitry Andric                   LV.getAlignment(), SkippedChecks);
1256*0b57cec5SDimitry Andric   }
1257*0b57cec5SDimitry Andric   return LV;
1258*0b57cec5SDimitry Andric }
1259*0b57cec5SDimitry Andric 
1260*0b57cec5SDimitry Andric /// EmitLValue - Emit code to compute a designator that specifies the location
1261*0b57cec5SDimitry Andric /// of the expression.
1262*0b57cec5SDimitry Andric ///
1263*0b57cec5SDimitry Andric /// This can return one of two things: a simple address or a bitfield reference.
1264*0b57cec5SDimitry Andric /// In either case, the LLVM Value* in the LValue structure is guaranteed to be
1265*0b57cec5SDimitry Andric /// an LLVM pointer type.
1266*0b57cec5SDimitry Andric ///
1267*0b57cec5SDimitry Andric /// If this returns a bitfield reference, nothing about the pointee type of the
1268*0b57cec5SDimitry Andric /// LLVM value is known: For example, it may not be a pointer to an integer.
1269*0b57cec5SDimitry Andric ///
1270*0b57cec5SDimitry Andric /// If this returns a normal address, and if the lvalue's C type is fixed size,
1271*0b57cec5SDimitry Andric /// this method guarantees that the returned pointer type will point to an LLVM
1272*0b57cec5SDimitry Andric /// type of the same size of the lvalue's type.  If the lvalue has a variable
1273*0b57cec5SDimitry Andric /// length type, this is not possible.
1274*0b57cec5SDimitry Andric ///
1275*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitLValue(const Expr *E) {
1276*0b57cec5SDimitry Andric   ApplyDebugLocation DL(*this, E);
1277*0b57cec5SDimitry Andric   switch (E->getStmtClass()) {
1278*0b57cec5SDimitry Andric   default: return EmitUnsupportedLValue(E, "l-value expression");
1279*0b57cec5SDimitry Andric 
1280*0b57cec5SDimitry Andric   case Expr::ObjCPropertyRefExprClass:
1281*0b57cec5SDimitry Andric     llvm_unreachable("cannot emit a property reference directly");
1282*0b57cec5SDimitry Andric 
1283*0b57cec5SDimitry Andric   case Expr::ObjCSelectorExprClass:
1284*0b57cec5SDimitry Andric     return EmitObjCSelectorLValue(cast<ObjCSelectorExpr>(E));
1285*0b57cec5SDimitry Andric   case Expr::ObjCIsaExprClass:
1286*0b57cec5SDimitry Andric     return EmitObjCIsaExpr(cast<ObjCIsaExpr>(E));
1287*0b57cec5SDimitry Andric   case Expr::BinaryOperatorClass:
1288*0b57cec5SDimitry Andric     return EmitBinaryOperatorLValue(cast<BinaryOperator>(E));
1289*0b57cec5SDimitry Andric   case Expr::CompoundAssignOperatorClass: {
1290*0b57cec5SDimitry Andric     QualType Ty = E->getType();
1291*0b57cec5SDimitry Andric     if (const AtomicType *AT = Ty->getAs<AtomicType>())
1292*0b57cec5SDimitry Andric       Ty = AT->getValueType();
1293*0b57cec5SDimitry Andric     if (!Ty->isAnyComplexType())
1294*0b57cec5SDimitry Andric       return EmitCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1295*0b57cec5SDimitry Andric     return EmitComplexCompoundAssignmentLValue(cast<CompoundAssignOperator>(E));
1296*0b57cec5SDimitry Andric   }
1297*0b57cec5SDimitry Andric   case Expr::CallExprClass:
1298*0b57cec5SDimitry Andric   case Expr::CXXMemberCallExprClass:
1299*0b57cec5SDimitry Andric   case Expr::CXXOperatorCallExprClass:
1300*0b57cec5SDimitry Andric   case Expr::UserDefinedLiteralClass:
1301*0b57cec5SDimitry Andric     return EmitCallExprLValue(cast<CallExpr>(E));
1302a7dea167SDimitry Andric   case Expr::CXXRewrittenBinaryOperatorClass:
1303a7dea167SDimitry Andric     return EmitLValue(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm());
1304*0b57cec5SDimitry Andric   case Expr::VAArgExprClass:
1305*0b57cec5SDimitry Andric     return EmitVAArgExprLValue(cast<VAArgExpr>(E));
1306*0b57cec5SDimitry Andric   case Expr::DeclRefExprClass:
1307*0b57cec5SDimitry Andric     return EmitDeclRefLValue(cast<DeclRefExpr>(E));
13085ffd83dbSDimitry Andric   case Expr::ConstantExprClass: {
13095ffd83dbSDimitry Andric     const ConstantExpr *CE = cast<ConstantExpr>(E);
13105ffd83dbSDimitry Andric     if (llvm::Value *Result = ConstantEmitter(*this).tryEmitConstantExpr(CE)) {
13115ffd83dbSDimitry Andric       QualType RetType = cast<CallExpr>(CE->getSubExpr()->IgnoreImplicit())
13120eae32dcSDimitry Andric                              ->getCallReturnType(getContext())
13130eae32dcSDimitry Andric                              ->getPointeeType();
13145ffd83dbSDimitry Andric       return MakeNaturalAlignAddrLValue(Result, RetType);
13155ffd83dbSDimitry Andric     }
1316*0b57cec5SDimitry Andric     return EmitLValue(cast<ConstantExpr>(E)->getSubExpr());
13175ffd83dbSDimitry Andric   }
1318*0b57cec5SDimitry Andric   case Expr::ParenExprClass:
1319*0b57cec5SDimitry Andric     return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
1320*0b57cec5SDimitry Andric   case Expr::GenericSelectionExprClass:
1321*0b57cec5SDimitry Andric     return EmitLValue(cast<GenericSelectionExpr>(E)->getResultExpr());
1322*0b57cec5SDimitry Andric   case Expr::PredefinedExprClass:
1323*0b57cec5SDimitry Andric     return EmitPredefinedLValue(cast<PredefinedExpr>(E));
1324*0b57cec5SDimitry Andric   case Expr::StringLiteralClass:
1325*0b57cec5SDimitry Andric     return EmitStringLiteralLValue(cast<StringLiteral>(E));
1326*0b57cec5SDimitry Andric   case Expr::ObjCEncodeExprClass:
1327*0b57cec5SDimitry Andric     return EmitObjCEncodeExprLValue(cast<ObjCEncodeExpr>(E));
1328*0b57cec5SDimitry Andric   case Expr::PseudoObjectExprClass:
1329*0b57cec5SDimitry Andric     return EmitPseudoObjectLValue(cast<PseudoObjectExpr>(E));
1330*0b57cec5SDimitry Andric   case Expr::InitListExprClass:
1331*0b57cec5SDimitry Andric     return EmitInitListLValue(cast<InitListExpr>(E));
1332*0b57cec5SDimitry Andric   case Expr::CXXTemporaryObjectExprClass:
1333*0b57cec5SDimitry Andric   case Expr::CXXConstructExprClass:
1334*0b57cec5SDimitry Andric     return EmitCXXConstructLValue(cast<CXXConstructExpr>(E));
1335*0b57cec5SDimitry Andric   case Expr::CXXBindTemporaryExprClass:
1336*0b57cec5SDimitry Andric     return EmitCXXBindTemporaryLValue(cast<CXXBindTemporaryExpr>(E));
1337*0b57cec5SDimitry Andric   case Expr::CXXUuidofExprClass:
1338*0b57cec5SDimitry Andric     return EmitCXXUuidofLValue(cast<CXXUuidofExpr>(E));
1339*0b57cec5SDimitry Andric   case Expr::LambdaExprClass:
1340*0b57cec5SDimitry Andric     return EmitAggExprToLValue(E);
1341*0b57cec5SDimitry Andric 
1342*0b57cec5SDimitry Andric   case Expr::ExprWithCleanupsClass: {
1343*0b57cec5SDimitry Andric     const auto *cleanups = cast<ExprWithCleanups>(E);
1344*0b57cec5SDimitry Andric     RunCleanupsScope Scope(*this);
1345*0b57cec5SDimitry Andric     LValue LV = EmitLValue(cleanups->getSubExpr());
1346*0b57cec5SDimitry Andric     if (LV.isSimple()) {
1347*0b57cec5SDimitry Andric       // Defend against branches out of gnu statement expressions surrounded by
1348*0b57cec5SDimitry Andric       // cleanups.
13490eae32dcSDimitry Andric       Address Addr = LV.getAddress(*this);
13500eae32dcSDimitry Andric       llvm::Value *V = Addr.getPointer();
1351*0b57cec5SDimitry Andric       Scope.ForceCleanup({&V});
13520eae32dcSDimitry Andric       return LValue::MakeAddr(Addr.withPointer(V), LV.getType(), getContext(),
13530eae32dcSDimitry Andric                               LV.getBaseInfo(), LV.getTBAAInfo());
1354*0b57cec5SDimitry Andric     }
1355*0b57cec5SDimitry Andric     // FIXME: Is it possible to create an ExprWithCleanups that produces a
1356*0b57cec5SDimitry Andric     // bitfield lvalue or some other non-simple lvalue?
1357*0b57cec5SDimitry Andric     return LV;
1358*0b57cec5SDimitry Andric   }
1359*0b57cec5SDimitry Andric 
1360*0b57cec5SDimitry Andric   case Expr::CXXDefaultArgExprClass: {
1361*0b57cec5SDimitry Andric     auto *DAE = cast<CXXDefaultArgExpr>(E);
1362*0b57cec5SDimitry Andric     CXXDefaultArgExprScope Scope(*this, DAE);
1363*0b57cec5SDimitry Andric     return EmitLValue(DAE->getExpr());
1364*0b57cec5SDimitry Andric   }
1365*0b57cec5SDimitry Andric   case Expr::CXXDefaultInitExprClass: {
1366*0b57cec5SDimitry Andric     auto *DIE = cast<CXXDefaultInitExpr>(E);
1367*0b57cec5SDimitry Andric     CXXDefaultInitExprScope Scope(*this, DIE);
1368*0b57cec5SDimitry Andric     return EmitLValue(DIE->getExpr());
1369*0b57cec5SDimitry Andric   }
1370*0b57cec5SDimitry Andric   case Expr::CXXTypeidExprClass:
1371*0b57cec5SDimitry Andric     return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
1372*0b57cec5SDimitry Andric 
1373*0b57cec5SDimitry Andric   case Expr::ObjCMessageExprClass:
1374*0b57cec5SDimitry Andric     return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
1375*0b57cec5SDimitry Andric   case Expr::ObjCIvarRefExprClass:
1376*0b57cec5SDimitry Andric     return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
1377*0b57cec5SDimitry Andric   case Expr::StmtExprClass:
1378*0b57cec5SDimitry Andric     return EmitStmtExprLValue(cast<StmtExpr>(E));
1379*0b57cec5SDimitry Andric   case Expr::UnaryOperatorClass:
1380*0b57cec5SDimitry Andric     return EmitUnaryOpLValue(cast<UnaryOperator>(E));
1381*0b57cec5SDimitry Andric   case Expr::ArraySubscriptExprClass:
1382*0b57cec5SDimitry Andric     return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
13835ffd83dbSDimitry Andric   case Expr::MatrixSubscriptExprClass:
13845ffd83dbSDimitry Andric     return EmitMatrixSubscriptExpr(cast<MatrixSubscriptExpr>(E));
1385*0b57cec5SDimitry Andric   case Expr::OMPArraySectionExprClass:
1386*0b57cec5SDimitry Andric     return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
1387*0b57cec5SDimitry Andric   case Expr::ExtVectorElementExprClass:
1388*0b57cec5SDimitry Andric     return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
1389*0b57cec5SDimitry Andric   case Expr::MemberExprClass:
1390*0b57cec5SDimitry Andric     return EmitMemberExpr(cast<MemberExpr>(E));
1391*0b57cec5SDimitry Andric   case Expr::CompoundLiteralExprClass:
1392*0b57cec5SDimitry Andric     return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
1393*0b57cec5SDimitry Andric   case Expr::ConditionalOperatorClass:
1394*0b57cec5SDimitry Andric     return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
1395*0b57cec5SDimitry Andric   case Expr::BinaryConditionalOperatorClass:
1396*0b57cec5SDimitry Andric     return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
1397*0b57cec5SDimitry Andric   case Expr::ChooseExprClass:
1398*0b57cec5SDimitry Andric     return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
1399*0b57cec5SDimitry Andric   case Expr::OpaqueValueExprClass:
1400*0b57cec5SDimitry Andric     return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
1401*0b57cec5SDimitry Andric   case Expr::SubstNonTypeTemplateParmExprClass:
1402*0b57cec5SDimitry Andric     return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
1403*0b57cec5SDimitry Andric   case Expr::ImplicitCastExprClass:
1404*0b57cec5SDimitry Andric   case Expr::CStyleCastExprClass:
1405*0b57cec5SDimitry Andric   case Expr::CXXFunctionalCastExprClass:
1406*0b57cec5SDimitry Andric   case Expr::CXXStaticCastExprClass:
1407*0b57cec5SDimitry Andric   case Expr::CXXDynamicCastExprClass:
1408*0b57cec5SDimitry Andric   case Expr::CXXReinterpretCastExprClass:
1409*0b57cec5SDimitry Andric   case Expr::CXXConstCastExprClass:
14105ffd83dbSDimitry Andric   case Expr::CXXAddrspaceCastExprClass:
1411*0b57cec5SDimitry Andric   case Expr::ObjCBridgedCastExprClass:
1412*0b57cec5SDimitry Andric     return EmitCastLValue(cast<CastExpr>(E));
1413*0b57cec5SDimitry Andric 
1414*0b57cec5SDimitry Andric   case Expr::MaterializeTemporaryExprClass:
1415*0b57cec5SDimitry Andric     return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
1416*0b57cec5SDimitry Andric 
1417*0b57cec5SDimitry Andric   case Expr::CoawaitExprClass:
1418*0b57cec5SDimitry Andric     return EmitCoawaitLValue(cast<CoawaitExpr>(E));
1419*0b57cec5SDimitry Andric   case Expr::CoyieldExprClass:
1420*0b57cec5SDimitry Andric     return EmitCoyieldLValue(cast<CoyieldExpr>(E));
1421*0b57cec5SDimitry Andric   }
1422*0b57cec5SDimitry Andric }
1423*0b57cec5SDimitry Andric 
1424*0b57cec5SDimitry Andric /// Given an object of the given canonical type, can we safely copy a
1425*0b57cec5SDimitry Andric /// value out of it based on its initializer?
1426*0b57cec5SDimitry Andric static bool isConstantEmittableObjectType(QualType type) {
1427*0b57cec5SDimitry Andric   assert(type.isCanonical());
1428*0b57cec5SDimitry Andric   assert(!type->isReferenceType());
1429*0b57cec5SDimitry Andric 
1430*0b57cec5SDimitry Andric   // Must be const-qualified but non-volatile.
1431*0b57cec5SDimitry Andric   Qualifiers qs = type.getLocalQualifiers();
1432*0b57cec5SDimitry Andric   if (!qs.hasConst() || qs.hasVolatile()) return false;
1433*0b57cec5SDimitry Andric 
1434*0b57cec5SDimitry Andric   // Otherwise, all object types satisfy this except C++ classes with
1435*0b57cec5SDimitry Andric   // mutable subobjects or non-trivial copy/destroy behavior.
1436*0b57cec5SDimitry Andric   if (const auto *RT = dyn_cast<RecordType>(type))
1437*0b57cec5SDimitry Andric     if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1438*0b57cec5SDimitry Andric       if (RD->hasMutableFields() || !RD->isTrivial())
1439*0b57cec5SDimitry Andric         return false;
1440*0b57cec5SDimitry Andric 
1441*0b57cec5SDimitry Andric   return true;
1442*0b57cec5SDimitry Andric }
1443*0b57cec5SDimitry Andric 
1444*0b57cec5SDimitry Andric /// Can we constant-emit a load of a reference to a variable of the
1445*0b57cec5SDimitry Andric /// given type?  This is different from predicates like
1446*0b57cec5SDimitry Andric /// Decl::mightBeUsableInConstantExpressions because we do want it to apply
1447*0b57cec5SDimitry Andric /// in situations that don't necessarily satisfy the language's rules
1448*0b57cec5SDimitry Andric /// for this (e.g. C++'s ODR-use rules).  For example, we want to able
1449*0b57cec5SDimitry Andric /// to do this with const float variables even if those variables
1450*0b57cec5SDimitry Andric /// aren't marked 'constexpr'.
1451*0b57cec5SDimitry Andric enum ConstantEmissionKind {
1452*0b57cec5SDimitry Andric   CEK_None,
1453*0b57cec5SDimitry Andric   CEK_AsReferenceOnly,
1454*0b57cec5SDimitry Andric   CEK_AsValueOrReference,
1455*0b57cec5SDimitry Andric   CEK_AsValueOnly
1456*0b57cec5SDimitry Andric };
1457*0b57cec5SDimitry Andric static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1458*0b57cec5SDimitry Andric   type = type.getCanonicalType();
1459*0b57cec5SDimitry Andric   if (const auto *ref = dyn_cast<ReferenceType>(type)) {
1460*0b57cec5SDimitry Andric     if (isConstantEmittableObjectType(ref->getPointeeType()))
1461*0b57cec5SDimitry Andric       return CEK_AsValueOrReference;
1462*0b57cec5SDimitry Andric     return CEK_AsReferenceOnly;
1463*0b57cec5SDimitry Andric   }
1464*0b57cec5SDimitry Andric   if (isConstantEmittableObjectType(type))
1465*0b57cec5SDimitry Andric     return CEK_AsValueOnly;
1466*0b57cec5SDimitry Andric   return CEK_None;
1467*0b57cec5SDimitry Andric }
1468*0b57cec5SDimitry Andric 
1469*0b57cec5SDimitry Andric /// Try to emit a reference to the given value without producing it as
1470*0b57cec5SDimitry Andric /// an l-value.  This is just an optimization, but it avoids us needing
1471*0b57cec5SDimitry Andric /// to emit global copies of variables if they're named without triggering
1472*0b57cec5SDimitry Andric /// a formal use in a context where we can't emit a direct reference to them,
1473*0b57cec5SDimitry Andric /// for instance if a block or lambda or a member of a local class uses a
1474*0b57cec5SDimitry Andric /// const int variable or constexpr variable from an enclosing function.
1475*0b57cec5SDimitry Andric CodeGenFunction::ConstantEmission
1476*0b57cec5SDimitry Andric CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1477*0b57cec5SDimitry Andric   ValueDecl *value = refExpr->getDecl();
1478*0b57cec5SDimitry Andric 
1479*0b57cec5SDimitry Andric   // The value needs to be an enum constant or a constant variable.
1480*0b57cec5SDimitry Andric   ConstantEmissionKind CEK;
1481*0b57cec5SDimitry Andric   if (isa<ParmVarDecl>(value)) {
1482*0b57cec5SDimitry Andric     CEK = CEK_None;
1483*0b57cec5SDimitry Andric   } else if (auto *var = dyn_cast<VarDecl>(value)) {
1484*0b57cec5SDimitry Andric     CEK = checkVarTypeForConstantEmission(var->getType());
1485*0b57cec5SDimitry Andric   } else if (isa<EnumConstantDecl>(value)) {
1486*0b57cec5SDimitry Andric     CEK = CEK_AsValueOnly;
1487*0b57cec5SDimitry Andric   } else {
1488*0b57cec5SDimitry Andric     CEK = CEK_None;
1489*0b57cec5SDimitry Andric   }
1490*0b57cec5SDimitry Andric   if (CEK == CEK_None) return ConstantEmission();
1491*0b57cec5SDimitry Andric 
1492*0b57cec5SDimitry Andric   Expr::EvalResult result;
1493*0b57cec5SDimitry Andric   bool resultIsReference;
1494*0b57cec5SDimitry Andric   QualType resultType;
1495*0b57cec5SDimitry Andric 
1496*0b57cec5SDimitry Andric   // It's best to evaluate all the way as an r-value if that's permitted.
1497*0b57cec5SDimitry Andric   if (CEK != CEK_AsReferenceOnly &&
1498*0b57cec5SDimitry Andric       refExpr->EvaluateAsRValue(result, getContext())) {
1499*0b57cec5SDimitry Andric     resultIsReference = false;
1500*0b57cec5SDimitry Andric     resultType = refExpr->getType();
1501*0b57cec5SDimitry Andric 
1502*0b57cec5SDimitry Andric   // Otherwise, try to evaluate as an l-value.
1503*0b57cec5SDimitry Andric   } else if (CEK != CEK_AsValueOnly &&
1504*0b57cec5SDimitry Andric              refExpr->EvaluateAsLValue(result, getContext())) {
1505*0b57cec5SDimitry Andric     resultIsReference = true;
1506*0b57cec5SDimitry Andric     resultType = value->getType();
1507*0b57cec5SDimitry Andric 
1508*0b57cec5SDimitry Andric   // Failure.
1509*0b57cec5SDimitry Andric   } else {
1510*0b57cec5SDimitry Andric     return ConstantEmission();
1511*0b57cec5SDimitry Andric   }
1512*0b57cec5SDimitry Andric 
1513*0b57cec5SDimitry Andric   // In any case, if the initializer has side-effects, abandon ship.
1514*0b57cec5SDimitry Andric   if (result.HasSideEffects)
1515*0b57cec5SDimitry Andric     return ConstantEmission();
1516*0b57cec5SDimitry Andric 
1517e8d8bef9SDimitry Andric   // In CUDA/HIP device compilation, a lambda may capture a reference variable
1518e8d8bef9SDimitry Andric   // referencing a global host variable by copy. In this case the lambda should
1519e8d8bef9SDimitry Andric   // make a copy of the value of the global host variable. The DRE of the
1520e8d8bef9SDimitry Andric   // captured reference variable cannot be emitted as load from the host
1521e8d8bef9SDimitry Andric   // global variable as compile time constant, since the host variable is not
1522e8d8bef9SDimitry Andric   // accessible on device. The DRE of the captured reference variable has to be
1523e8d8bef9SDimitry Andric   // loaded from captures.
1524e8d8bef9SDimitry Andric   if (CGM.getLangOpts().CUDAIsDevice && result.Val.isLValue() &&
1525e8d8bef9SDimitry Andric       refExpr->refersToEnclosingVariableOrCapture()) {
1526e8d8bef9SDimitry Andric     auto *MD = dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl);
1527e8d8bef9SDimitry Andric     if (MD && MD->getParent()->isLambda() &&
1528e8d8bef9SDimitry Andric         MD->getOverloadedOperator() == OO_Call) {
1529e8d8bef9SDimitry Andric       const APValue::LValueBase &base = result.Val.getLValueBase();
1530e8d8bef9SDimitry Andric       if (const ValueDecl *D = base.dyn_cast<const ValueDecl *>()) {
1531e8d8bef9SDimitry Andric         if (const VarDecl *VD = dyn_cast<const VarDecl>(D)) {
1532e8d8bef9SDimitry Andric           if (!VD->hasAttr<CUDADeviceAttr>()) {
1533e8d8bef9SDimitry Andric             return ConstantEmission();
1534e8d8bef9SDimitry Andric           }
1535e8d8bef9SDimitry Andric         }
1536e8d8bef9SDimitry Andric       }
1537e8d8bef9SDimitry Andric     }
1538e8d8bef9SDimitry Andric   }
1539e8d8bef9SDimitry Andric 
1540*0b57cec5SDimitry Andric   // Emit as a constant.
1541*0b57cec5SDimitry Andric   auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
1542*0b57cec5SDimitry Andric                                                result.Val, resultType);
1543*0b57cec5SDimitry Andric 
1544*0b57cec5SDimitry Andric   // Make sure we emit a debug reference to the global variable.
1545*0b57cec5SDimitry Andric   // This should probably fire even for
1546*0b57cec5SDimitry Andric   if (isa<VarDecl>(value)) {
1547*0b57cec5SDimitry Andric     if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1548*0b57cec5SDimitry Andric       EmitDeclRefExprDbgValue(refExpr, result.Val);
1549*0b57cec5SDimitry Andric   } else {
1550*0b57cec5SDimitry Andric     assert(isa<EnumConstantDecl>(value));
1551*0b57cec5SDimitry Andric     EmitDeclRefExprDbgValue(refExpr, result.Val);
1552*0b57cec5SDimitry Andric   }
1553*0b57cec5SDimitry Andric 
1554*0b57cec5SDimitry Andric   // If we emitted a reference constant, we need to dereference that.
1555*0b57cec5SDimitry Andric   if (resultIsReference)
1556*0b57cec5SDimitry Andric     return ConstantEmission::forReference(C);
1557*0b57cec5SDimitry Andric 
1558*0b57cec5SDimitry Andric   return ConstantEmission::forValue(C);
1559*0b57cec5SDimitry Andric }
1560*0b57cec5SDimitry Andric 
1561*0b57cec5SDimitry Andric static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
1562*0b57cec5SDimitry Andric                                                         const MemberExpr *ME) {
1563*0b57cec5SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
1564*0b57cec5SDimitry Andric     // Try to emit static variable member expressions as DREs.
1565*0b57cec5SDimitry Andric     return DeclRefExpr::Create(
1566*0b57cec5SDimitry Andric         CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD,
1567*0b57cec5SDimitry Andric         /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
1568*0b57cec5SDimitry Andric         ME->getType(), ME->getValueKind(), nullptr, nullptr, ME->isNonOdrUse());
1569*0b57cec5SDimitry Andric   }
1570*0b57cec5SDimitry Andric   return nullptr;
1571*0b57cec5SDimitry Andric }
1572*0b57cec5SDimitry Andric 
1573*0b57cec5SDimitry Andric CodeGenFunction::ConstantEmission
1574*0b57cec5SDimitry Andric CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
1575*0b57cec5SDimitry Andric   if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
1576*0b57cec5SDimitry Andric     return tryEmitAsConstant(DRE);
1577*0b57cec5SDimitry Andric   return ConstantEmission();
1578*0b57cec5SDimitry Andric }
1579*0b57cec5SDimitry Andric 
1580*0b57cec5SDimitry Andric llvm::Value *CodeGenFunction::emitScalarConstant(
1581*0b57cec5SDimitry Andric     const CodeGenFunction::ConstantEmission &Constant, Expr *E) {
1582*0b57cec5SDimitry Andric   assert(Constant && "not a constant");
1583*0b57cec5SDimitry Andric   if (Constant.isReference())
1584*0b57cec5SDimitry Andric     return EmitLoadOfLValue(Constant.getReferenceLValue(*this, E),
1585*0b57cec5SDimitry Andric                             E->getExprLoc())
1586*0b57cec5SDimitry Andric         .getScalarVal();
1587*0b57cec5SDimitry Andric   return Constant.getValue();
1588*0b57cec5SDimitry Andric }
1589*0b57cec5SDimitry Andric 
1590*0b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1591*0b57cec5SDimitry Andric                                                SourceLocation Loc) {
1592480093f4SDimitry Andric   return EmitLoadOfScalar(lvalue.getAddress(*this), lvalue.isVolatile(),
1593*0b57cec5SDimitry Andric                           lvalue.getType(), Loc, lvalue.getBaseInfo(),
1594*0b57cec5SDimitry Andric                           lvalue.getTBAAInfo(), lvalue.isNontemporal());
1595*0b57cec5SDimitry Andric }
1596*0b57cec5SDimitry Andric 
1597*0b57cec5SDimitry Andric static bool hasBooleanRepresentation(QualType Ty) {
1598*0b57cec5SDimitry Andric   if (Ty->isBooleanType())
1599*0b57cec5SDimitry Andric     return true;
1600*0b57cec5SDimitry Andric 
1601*0b57cec5SDimitry Andric   if (const EnumType *ET = Ty->getAs<EnumType>())
1602*0b57cec5SDimitry Andric     return ET->getDecl()->getIntegerType()->isBooleanType();
1603*0b57cec5SDimitry Andric 
1604*0b57cec5SDimitry Andric   if (const AtomicType *AT = Ty->getAs<AtomicType>())
1605*0b57cec5SDimitry Andric     return hasBooleanRepresentation(AT->getValueType());
1606*0b57cec5SDimitry Andric 
1607*0b57cec5SDimitry Andric   return false;
1608*0b57cec5SDimitry Andric }
1609*0b57cec5SDimitry Andric 
1610*0b57cec5SDimitry Andric static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1611*0b57cec5SDimitry Andric                             llvm::APInt &Min, llvm::APInt &End,
1612*0b57cec5SDimitry Andric                             bool StrictEnums, bool IsBool) {
1613*0b57cec5SDimitry Andric   const EnumType *ET = Ty->getAs<EnumType>();
1614*0b57cec5SDimitry Andric   bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1615*0b57cec5SDimitry Andric                                 ET && !ET->getDecl()->isFixed();
1616*0b57cec5SDimitry Andric   if (!IsBool && !IsRegularCPlusPlusEnum)
1617*0b57cec5SDimitry Andric     return false;
1618*0b57cec5SDimitry Andric 
1619*0b57cec5SDimitry Andric   if (IsBool) {
1620*0b57cec5SDimitry Andric     Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1621*0b57cec5SDimitry Andric     End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
1622*0b57cec5SDimitry Andric   } else {
1623*0b57cec5SDimitry Andric     const EnumDecl *ED = ET->getDecl();
1624*0b57cec5SDimitry Andric     llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
1625*0b57cec5SDimitry Andric     unsigned Bitwidth = LTy->getScalarSizeInBits();
1626*0b57cec5SDimitry Andric     unsigned NumNegativeBits = ED->getNumNegativeBits();
1627*0b57cec5SDimitry Andric     unsigned NumPositiveBits = ED->getNumPositiveBits();
1628*0b57cec5SDimitry Andric 
1629*0b57cec5SDimitry Andric     if (NumNegativeBits) {
1630*0b57cec5SDimitry Andric       unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1631*0b57cec5SDimitry Andric       assert(NumBits <= Bitwidth);
1632*0b57cec5SDimitry Andric       End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1633*0b57cec5SDimitry Andric       Min = -End;
1634*0b57cec5SDimitry Andric     } else {
1635*0b57cec5SDimitry Andric       assert(NumPositiveBits <= Bitwidth);
1636*0b57cec5SDimitry Andric       End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1637349cc55cSDimitry Andric       Min = llvm::APInt::getZero(Bitwidth);
1638*0b57cec5SDimitry Andric     }
1639*0b57cec5SDimitry Andric   }
1640*0b57cec5SDimitry Andric   return true;
1641*0b57cec5SDimitry Andric }
1642*0b57cec5SDimitry Andric 
1643*0b57cec5SDimitry Andric llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1644*0b57cec5SDimitry Andric   llvm::APInt Min, End;
1645*0b57cec5SDimitry Andric   if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1646*0b57cec5SDimitry Andric                        hasBooleanRepresentation(Ty)))
1647*0b57cec5SDimitry Andric     return nullptr;
1648*0b57cec5SDimitry Andric 
1649*0b57cec5SDimitry Andric   llvm::MDBuilder MDHelper(getLLVMContext());
1650*0b57cec5SDimitry Andric   return MDHelper.createRange(Min, End);
1651*0b57cec5SDimitry Andric }
1652*0b57cec5SDimitry Andric 
1653*0b57cec5SDimitry Andric bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1654*0b57cec5SDimitry Andric                                            SourceLocation Loc) {
1655*0b57cec5SDimitry Andric   bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1656*0b57cec5SDimitry Andric   bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1657*0b57cec5SDimitry Andric   if (!HasBoolCheck && !HasEnumCheck)
1658*0b57cec5SDimitry Andric     return false;
1659*0b57cec5SDimitry Andric 
1660*0b57cec5SDimitry Andric   bool IsBool = hasBooleanRepresentation(Ty) ||
1661*0b57cec5SDimitry Andric                 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1662*0b57cec5SDimitry Andric   bool NeedsBoolCheck = HasBoolCheck && IsBool;
1663*0b57cec5SDimitry Andric   bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1664*0b57cec5SDimitry Andric   if (!NeedsBoolCheck && !NeedsEnumCheck)
1665*0b57cec5SDimitry Andric     return false;
1666*0b57cec5SDimitry Andric 
1667*0b57cec5SDimitry Andric   // Single-bit booleans don't need to be checked. Special-case this to avoid
1668*0b57cec5SDimitry Andric   // a bit width mismatch when handling bitfield values. This is handled by
1669*0b57cec5SDimitry Andric   // EmitFromMemory for the non-bitfield case.
1670*0b57cec5SDimitry Andric   if (IsBool &&
1671*0b57cec5SDimitry Andric       cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1672*0b57cec5SDimitry Andric     return false;
1673*0b57cec5SDimitry Andric 
1674*0b57cec5SDimitry Andric   llvm::APInt Min, End;
1675*0b57cec5SDimitry Andric   if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1676*0b57cec5SDimitry Andric     return true;
1677*0b57cec5SDimitry Andric 
1678*0b57cec5SDimitry Andric   auto &Ctx = getLLVMContext();
1679*0b57cec5SDimitry Andric   SanitizerScope SanScope(this);
1680*0b57cec5SDimitry Andric   llvm::Value *Check;
1681*0b57cec5SDimitry Andric   --End;
1682*0b57cec5SDimitry Andric   if (!Min) {
1683*0b57cec5SDimitry Andric     Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
1684*0b57cec5SDimitry Andric   } else {
1685*0b57cec5SDimitry Andric     llvm::Value *Upper =
1686*0b57cec5SDimitry Andric         Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
1687*0b57cec5SDimitry Andric     llvm::Value *Lower =
1688*0b57cec5SDimitry Andric         Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
1689*0b57cec5SDimitry Andric     Check = Builder.CreateAnd(Upper, Lower);
1690*0b57cec5SDimitry Andric   }
1691*0b57cec5SDimitry Andric   llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1692*0b57cec5SDimitry Andric                                   EmitCheckTypeDescriptor(Ty)};
1693*0b57cec5SDimitry Andric   SanitizerMask Kind =
1694*0b57cec5SDimitry Andric       NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1695*0b57cec5SDimitry Andric   EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1696*0b57cec5SDimitry Andric             StaticArgs, EmitCheckValue(Value));
1697*0b57cec5SDimitry Andric   return true;
1698*0b57cec5SDimitry Andric }
1699*0b57cec5SDimitry Andric 
1700*0b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1701*0b57cec5SDimitry Andric                                                QualType Ty,
1702*0b57cec5SDimitry Andric                                                SourceLocation Loc,
1703*0b57cec5SDimitry Andric                                                LValueBaseInfo BaseInfo,
1704*0b57cec5SDimitry Andric                                                TBAAAccessInfo TBAAInfo,
1705*0b57cec5SDimitry Andric                                                bool isNontemporal) {
1706*0b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1707*0b57cec5SDimitry Andric     // For better performance, handle vector loads differently.
1708*0b57cec5SDimitry Andric     if (Ty->isVectorType()) {
1709*0b57cec5SDimitry Andric       const llvm::Type *EltTy = Addr.getElementType();
1710*0b57cec5SDimitry Andric 
1711e8d8bef9SDimitry Andric       const auto *VTy = cast<llvm::FixedVectorType>(EltTy);
1712*0b57cec5SDimitry Andric 
1713*0b57cec5SDimitry Andric       // Handle vectors of size 3 like size 4 for better performance.
1714*0b57cec5SDimitry Andric       if (VTy->getNumElements() == 3) {
1715*0b57cec5SDimitry Andric 
1716*0b57cec5SDimitry Andric         // Bitcast to vec4 type.
17175ffd83dbSDimitry Andric         auto *vec4Ty = llvm::FixedVectorType::get(VTy->getElementType(), 4);
1718*0b57cec5SDimitry Andric         Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1719*0b57cec5SDimitry Andric         // Now load value.
1720*0b57cec5SDimitry Andric         llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
1721*0b57cec5SDimitry Andric 
1722*0b57cec5SDimitry Andric         // Shuffle vector to get vec3.
1723e8d8bef9SDimitry Andric         V = Builder.CreateShuffleVector(V, ArrayRef<int>{0, 1, 2},
1724e8d8bef9SDimitry Andric                                         "extractVec");
1725*0b57cec5SDimitry Andric         return EmitFromMemory(V, Ty);
1726*0b57cec5SDimitry Andric       }
1727*0b57cec5SDimitry Andric     }
1728*0b57cec5SDimitry Andric   }
1729*0b57cec5SDimitry Andric 
1730*0b57cec5SDimitry Andric   // Atomic operations have to be done on integral types.
1731*0b57cec5SDimitry Andric   LValue AtomicLValue =
1732*0b57cec5SDimitry Andric       LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1733*0b57cec5SDimitry Andric   if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1734*0b57cec5SDimitry Andric     return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
1735*0b57cec5SDimitry Andric   }
1736*0b57cec5SDimitry Andric 
1737*0b57cec5SDimitry Andric   llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
1738*0b57cec5SDimitry Andric   if (isNontemporal) {
1739*0b57cec5SDimitry Andric     llvm::MDNode *Node = llvm::MDNode::get(
1740*0b57cec5SDimitry Andric         Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1741*0b57cec5SDimitry Andric     Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1742*0b57cec5SDimitry Andric   }
1743*0b57cec5SDimitry Andric 
1744*0b57cec5SDimitry Andric   CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
1745*0b57cec5SDimitry Andric 
1746*0b57cec5SDimitry Andric   if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1747*0b57cec5SDimitry Andric     // In order to prevent the optimizer from throwing away the check, don't
1748*0b57cec5SDimitry Andric     // attach range metadata to the load.
1749*0b57cec5SDimitry Andric   } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1750*0b57cec5SDimitry Andric     if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1751*0b57cec5SDimitry Andric       Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1752*0b57cec5SDimitry Andric 
1753*0b57cec5SDimitry Andric   return EmitFromMemory(Load, Ty);
1754*0b57cec5SDimitry Andric }
1755*0b57cec5SDimitry Andric 
1756*0b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1757*0b57cec5SDimitry Andric   // Bool has a different representation in memory than in registers.
1758*0b57cec5SDimitry Andric   if (hasBooleanRepresentation(Ty)) {
1759*0b57cec5SDimitry Andric     // This should really always be an i1, but sometimes it's already
1760*0b57cec5SDimitry Andric     // an i8, and it's awkward to track those cases down.
1761*0b57cec5SDimitry Andric     if (Value->getType()->isIntegerTy(1))
1762*0b57cec5SDimitry Andric       return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1763*0b57cec5SDimitry Andric     assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1764*0b57cec5SDimitry Andric            "wrong value rep of bool");
1765*0b57cec5SDimitry Andric   }
1766*0b57cec5SDimitry Andric 
1767*0b57cec5SDimitry Andric   return Value;
1768*0b57cec5SDimitry Andric }
1769*0b57cec5SDimitry Andric 
1770*0b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1771*0b57cec5SDimitry Andric   // Bool has a different representation in memory than in registers.
1772*0b57cec5SDimitry Andric   if (hasBooleanRepresentation(Ty)) {
1773*0b57cec5SDimitry Andric     assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1774*0b57cec5SDimitry Andric            "wrong value rep of bool");
1775*0b57cec5SDimitry Andric     return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1776*0b57cec5SDimitry Andric   }
1777*0b57cec5SDimitry Andric 
1778*0b57cec5SDimitry Andric   return Value;
1779*0b57cec5SDimitry Andric }
1780*0b57cec5SDimitry Andric 
17815ffd83dbSDimitry Andric // Convert the pointer of \p Addr to a pointer to a vector (the value type of
17825ffd83dbSDimitry Andric // MatrixType), if it points to a array (the memory type of MatrixType).
17835ffd83dbSDimitry Andric static Address MaybeConvertMatrixAddress(Address Addr, CodeGenFunction &CGF,
17845ffd83dbSDimitry Andric                                          bool IsVector = true) {
17850eae32dcSDimitry Andric   auto *ArrayTy = dyn_cast<llvm::ArrayType>(Addr.getElementType());
17865ffd83dbSDimitry Andric   if (ArrayTy && IsVector) {
17875ffd83dbSDimitry Andric     auto *VectorTy = llvm::FixedVectorType::get(ArrayTy->getElementType(),
17885ffd83dbSDimitry Andric                                                 ArrayTy->getNumElements());
17895ffd83dbSDimitry Andric 
17905ffd83dbSDimitry Andric     return Address(CGF.Builder.CreateElementBitCast(Addr, VectorTy));
17915ffd83dbSDimitry Andric   }
17920eae32dcSDimitry Andric   auto *VectorTy = dyn_cast<llvm::VectorType>(Addr.getElementType());
17935ffd83dbSDimitry Andric   if (VectorTy && !IsVector) {
1794e8d8bef9SDimitry Andric     auto *ArrayTy = llvm::ArrayType::get(
1795e8d8bef9SDimitry Andric         VectorTy->getElementType(),
1796e8d8bef9SDimitry Andric         cast<llvm::FixedVectorType>(VectorTy)->getNumElements());
17975ffd83dbSDimitry Andric 
17985ffd83dbSDimitry Andric     return Address(CGF.Builder.CreateElementBitCast(Addr, ArrayTy));
17995ffd83dbSDimitry Andric   }
18005ffd83dbSDimitry Andric 
18015ffd83dbSDimitry Andric   return Addr;
18025ffd83dbSDimitry Andric }
18035ffd83dbSDimitry Andric 
18045ffd83dbSDimitry Andric // Emit a store of a matrix LValue. This may require casting the original
18055ffd83dbSDimitry Andric // pointer to memory address (ArrayType) to a pointer to the value type
18065ffd83dbSDimitry Andric // (VectorType).
18075ffd83dbSDimitry Andric static void EmitStoreOfMatrixScalar(llvm::Value *value, LValue lvalue,
18085ffd83dbSDimitry Andric                                     bool isInit, CodeGenFunction &CGF) {
18095ffd83dbSDimitry Andric   Address Addr = MaybeConvertMatrixAddress(lvalue.getAddress(CGF), CGF,
18105ffd83dbSDimitry Andric                                            value->getType()->isVectorTy());
18115ffd83dbSDimitry Andric   CGF.EmitStoreOfScalar(value, Addr, lvalue.isVolatile(), lvalue.getType(),
18125ffd83dbSDimitry Andric                         lvalue.getBaseInfo(), lvalue.getTBAAInfo(), isInit,
18135ffd83dbSDimitry Andric                         lvalue.isNontemporal());
18145ffd83dbSDimitry Andric }
18155ffd83dbSDimitry Andric 
1816*0b57cec5SDimitry Andric void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1817*0b57cec5SDimitry Andric                                         bool Volatile, QualType Ty,
1818*0b57cec5SDimitry Andric                                         LValueBaseInfo BaseInfo,
1819*0b57cec5SDimitry Andric                                         TBAAAccessInfo TBAAInfo,
1820*0b57cec5SDimitry Andric                                         bool isInit, bool isNontemporal) {
1821*0b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1822*0b57cec5SDimitry Andric     // Handle vectors differently to get better performance.
1823*0b57cec5SDimitry Andric     if (Ty->isVectorType()) {
1824*0b57cec5SDimitry Andric       llvm::Type *SrcTy = Value->getType();
1825*0b57cec5SDimitry Andric       auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
1826*0b57cec5SDimitry Andric       // Handle vec3 special.
1827e8d8bef9SDimitry Andric       if (VecTy && cast<llvm::FixedVectorType>(VecTy)->getNumElements() == 3) {
1828*0b57cec5SDimitry Andric         // Our source is a vec3, do a shuffle vector to make it a vec4.
1829e8d8bef9SDimitry Andric         Value = Builder.CreateShuffleVector(Value, ArrayRef<int>{0, 1, 2, -1},
18305ffd83dbSDimitry Andric                                             "extractVec");
18315ffd83dbSDimitry Andric         SrcTy = llvm::FixedVectorType::get(VecTy->getElementType(), 4);
1832*0b57cec5SDimitry Andric       }
1833*0b57cec5SDimitry Andric       if (Addr.getElementType() != SrcTy) {
1834*0b57cec5SDimitry Andric         Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1835*0b57cec5SDimitry Andric       }
1836*0b57cec5SDimitry Andric     }
1837*0b57cec5SDimitry Andric   }
1838*0b57cec5SDimitry Andric 
1839*0b57cec5SDimitry Andric   Value = EmitToMemory(Value, Ty);
1840*0b57cec5SDimitry Andric 
1841*0b57cec5SDimitry Andric   LValue AtomicLValue =
1842*0b57cec5SDimitry Andric       LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1843*0b57cec5SDimitry Andric   if (Ty->isAtomicType() ||
1844*0b57cec5SDimitry Andric       (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1845*0b57cec5SDimitry Andric     EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
1846*0b57cec5SDimitry Andric     return;
1847*0b57cec5SDimitry Andric   }
1848*0b57cec5SDimitry Andric 
1849*0b57cec5SDimitry Andric   llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1850*0b57cec5SDimitry Andric   if (isNontemporal) {
1851*0b57cec5SDimitry Andric     llvm::MDNode *Node =
1852*0b57cec5SDimitry Andric         llvm::MDNode::get(Store->getContext(),
1853*0b57cec5SDimitry Andric                           llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1854*0b57cec5SDimitry Andric     Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1855*0b57cec5SDimitry Andric   }
1856*0b57cec5SDimitry Andric 
1857*0b57cec5SDimitry Andric   CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
1858*0b57cec5SDimitry Andric }
1859*0b57cec5SDimitry Andric 
1860*0b57cec5SDimitry Andric void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1861*0b57cec5SDimitry Andric                                         bool isInit) {
18625ffd83dbSDimitry Andric   if (lvalue.getType()->isConstantMatrixType()) {
18635ffd83dbSDimitry Andric     EmitStoreOfMatrixScalar(value, lvalue, isInit, *this);
18645ffd83dbSDimitry Andric     return;
18655ffd83dbSDimitry Andric   }
18665ffd83dbSDimitry Andric 
1867480093f4SDimitry Andric   EmitStoreOfScalar(value, lvalue.getAddress(*this), lvalue.isVolatile(),
1868*0b57cec5SDimitry Andric                     lvalue.getType(), lvalue.getBaseInfo(),
1869*0b57cec5SDimitry Andric                     lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
1870*0b57cec5SDimitry Andric }
1871*0b57cec5SDimitry Andric 
18725ffd83dbSDimitry Andric // Emit a load of a LValue of matrix type. This may require casting the pointer
18735ffd83dbSDimitry Andric // to memory address (ArrayType) to a pointer to the value type (VectorType).
18745ffd83dbSDimitry Andric static RValue EmitLoadOfMatrixLValue(LValue LV, SourceLocation Loc,
18755ffd83dbSDimitry Andric                                      CodeGenFunction &CGF) {
18765ffd83dbSDimitry Andric   assert(LV.getType()->isConstantMatrixType());
18775ffd83dbSDimitry Andric   Address Addr = MaybeConvertMatrixAddress(LV.getAddress(CGF), CGF);
18785ffd83dbSDimitry Andric   LV.setAddress(Addr);
18795ffd83dbSDimitry Andric   return RValue::get(CGF.EmitLoadOfScalar(LV, Loc));
18805ffd83dbSDimitry Andric }
18815ffd83dbSDimitry Andric 
1882*0b57cec5SDimitry Andric /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1883*0b57cec5SDimitry Andric /// method emits the address of the lvalue, then loads the result as an rvalue,
1884*0b57cec5SDimitry Andric /// returning the rvalue.
1885*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
1886*0b57cec5SDimitry Andric   if (LV.isObjCWeak()) {
1887*0b57cec5SDimitry Andric     // load of a __weak object.
1888480093f4SDimitry Andric     Address AddrWeakObj = LV.getAddress(*this);
1889*0b57cec5SDimitry Andric     return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1890*0b57cec5SDimitry Andric                                                              AddrWeakObj));
1891*0b57cec5SDimitry Andric   }
1892*0b57cec5SDimitry Andric   if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1893*0b57cec5SDimitry Andric     // In MRC mode, we do a load+autorelease.
1894*0b57cec5SDimitry Andric     if (!getLangOpts().ObjCAutoRefCount) {
1895480093f4SDimitry Andric       return RValue::get(EmitARCLoadWeak(LV.getAddress(*this)));
1896*0b57cec5SDimitry Andric     }
1897*0b57cec5SDimitry Andric 
1898*0b57cec5SDimitry Andric     // In ARC mode, we load retained and then consume the value.
1899480093f4SDimitry Andric     llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress(*this));
1900*0b57cec5SDimitry Andric     Object = EmitObjCConsumeObject(LV.getType(), Object);
1901*0b57cec5SDimitry Andric     return RValue::get(Object);
1902*0b57cec5SDimitry Andric   }
1903*0b57cec5SDimitry Andric 
1904*0b57cec5SDimitry Andric   if (LV.isSimple()) {
1905*0b57cec5SDimitry Andric     assert(!LV.getType()->isFunctionType());
1906*0b57cec5SDimitry Andric 
19075ffd83dbSDimitry Andric     if (LV.getType()->isConstantMatrixType())
19085ffd83dbSDimitry Andric       return EmitLoadOfMatrixLValue(LV, Loc, *this);
19095ffd83dbSDimitry Andric 
1910*0b57cec5SDimitry Andric     // Everything needs a load.
1911*0b57cec5SDimitry Andric     return RValue::get(EmitLoadOfScalar(LV, Loc));
1912*0b57cec5SDimitry Andric   }
1913*0b57cec5SDimitry Andric 
1914*0b57cec5SDimitry Andric   if (LV.isVectorElt()) {
1915*0b57cec5SDimitry Andric     llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
1916*0b57cec5SDimitry Andric                                               LV.isVolatileQualified());
1917*0b57cec5SDimitry Andric     return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1918*0b57cec5SDimitry Andric                                                     "vecext"));
1919*0b57cec5SDimitry Andric   }
1920*0b57cec5SDimitry Andric 
1921*0b57cec5SDimitry Andric   // If this is a reference to a subset of the elements of a vector, either
1922*0b57cec5SDimitry Andric   // shuffle the input or extract/insert them as appropriate.
19235ffd83dbSDimitry Andric   if (LV.isExtVectorElt()) {
1924*0b57cec5SDimitry Andric     return EmitLoadOfExtVectorElementLValue(LV);
19255ffd83dbSDimitry Andric   }
1926*0b57cec5SDimitry Andric 
1927*0b57cec5SDimitry Andric   // Global Register variables always invoke intrinsics
1928*0b57cec5SDimitry Andric   if (LV.isGlobalReg())
1929*0b57cec5SDimitry Andric     return EmitLoadOfGlobalRegLValue(LV);
1930*0b57cec5SDimitry Andric 
19315ffd83dbSDimitry Andric   if (LV.isMatrixElt()) {
1932349cc55cSDimitry Andric     llvm::Value *Idx = LV.getMatrixIdx();
1933349cc55cSDimitry Andric     if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
1934349cc55cSDimitry Andric       const auto *const MatTy = LV.getType()->getAs<ConstantMatrixType>();
1935349cc55cSDimitry Andric       llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
1936349cc55cSDimitry Andric       MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
1937349cc55cSDimitry Andric     }
19385ffd83dbSDimitry Andric     llvm::LoadInst *Load =
19395ffd83dbSDimitry Andric         Builder.CreateLoad(LV.getMatrixAddress(), LV.isVolatileQualified());
1940349cc55cSDimitry Andric     return RValue::get(Builder.CreateExtractElement(Load, Idx, "matrixext"));
19415ffd83dbSDimitry Andric   }
19425ffd83dbSDimitry Andric 
1943*0b57cec5SDimitry Andric   assert(LV.isBitField() && "Unknown LValue type!");
1944*0b57cec5SDimitry Andric   return EmitLoadOfBitfieldLValue(LV, Loc);
1945*0b57cec5SDimitry Andric }
1946*0b57cec5SDimitry Andric 
1947*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1948*0b57cec5SDimitry Andric                                                  SourceLocation Loc) {
1949*0b57cec5SDimitry Andric   const CGBitFieldInfo &Info = LV.getBitFieldInfo();
1950*0b57cec5SDimitry Andric 
1951*0b57cec5SDimitry Andric   // Get the output type.
1952*0b57cec5SDimitry Andric   llvm::Type *ResLTy = ConvertType(LV.getType());
1953*0b57cec5SDimitry Andric 
1954*0b57cec5SDimitry Andric   Address Ptr = LV.getBitFieldAddress();
1955e8d8bef9SDimitry Andric   llvm::Value *Val =
1956e8d8bef9SDimitry Andric       Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
1957*0b57cec5SDimitry Andric 
1958e8d8bef9SDimitry Andric   bool UseVolatile = LV.isVolatileQualified() &&
1959e8d8bef9SDimitry Andric                      Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
1960e8d8bef9SDimitry Andric   const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
1961e8d8bef9SDimitry Andric   const unsigned StorageSize =
1962e8d8bef9SDimitry Andric       UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
1963*0b57cec5SDimitry Andric   if (Info.IsSigned) {
1964e8d8bef9SDimitry Andric     assert(static_cast<unsigned>(Offset + Info.Size) <= StorageSize);
1965e8d8bef9SDimitry Andric     unsigned HighBits = StorageSize - Offset - Info.Size;
1966*0b57cec5SDimitry Andric     if (HighBits)
1967*0b57cec5SDimitry Andric       Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1968e8d8bef9SDimitry Andric     if (Offset + HighBits)
1969e8d8bef9SDimitry Andric       Val = Builder.CreateAShr(Val, Offset + HighBits, "bf.ashr");
1970*0b57cec5SDimitry Andric   } else {
1971e8d8bef9SDimitry Andric     if (Offset)
1972e8d8bef9SDimitry Andric       Val = Builder.CreateLShr(Val, Offset, "bf.lshr");
1973e8d8bef9SDimitry Andric     if (static_cast<unsigned>(Offset) + Info.Size < StorageSize)
1974e8d8bef9SDimitry Andric       Val = Builder.CreateAnd(
1975e8d8bef9SDimitry Andric           Val, llvm::APInt::getLowBitsSet(StorageSize, Info.Size), "bf.clear");
1976*0b57cec5SDimitry Andric   }
1977*0b57cec5SDimitry Andric   Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
1978*0b57cec5SDimitry Andric   EmitScalarRangeCheck(Val, LV.getType(), Loc);
1979*0b57cec5SDimitry Andric   return RValue::get(Val);
1980*0b57cec5SDimitry Andric }
1981*0b57cec5SDimitry Andric 
1982*0b57cec5SDimitry Andric // If this is a reference to a subset of the elements of a vector, create an
1983*0b57cec5SDimitry Andric // appropriate shufflevector.
1984*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
1985*0b57cec5SDimitry Andric   llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1986*0b57cec5SDimitry Andric                                         LV.isVolatileQualified());
1987*0b57cec5SDimitry Andric 
1988*0b57cec5SDimitry Andric   const llvm::Constant *Elts = LV.getExtVectorElts();
1989*0b57cec5SDimitry Andric 
1990*0b57cec5SDimitry Andric   // If the result of the expression is a non-vector type, we must be extracting
1991*0b57cec5SDimitry Andric   // a single element.  Just codegen as an extractelement.
1992*0b57cec5SDimitry Andric   const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1993*0b57cec5SDimitry Andric   if (!ExprVT) {
1994*0b57cec5SDimitry Andric     unsigned InIdx = getAccessedFieldNo(0, Elts);
1995*0b57cec5SDimitry Andric     llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1996*0b57cec5SDimitry Andric     return RValue::get(Builder.CreateExtractElement(Vec, Elt));
1997*0b57cec5SDimitry Andric   }
1998*0b57cec5SDimitry Andric 
1999*0b57cec5SDimitry Andric   // Always use shuffle vector to try to retain the original program structure
2000*0b57cec5SDimitry Andric   unsigned NumResultElts = ExprVT->getNumElements();
2001*0b57cec5SDimitry Andric 
20025ffd83dbSDimitry Andric   SmallVector<int, 4> Mask;
2003*0b57cec5SDimitry Andric   for (unsigned i = 0; i != NumResultElts; ++i)
20045ffd83dbSDimitry Andric     Mask.push_back(getAccessedFieldNo(i, Elts));
2005*0b57cec5SDimitry Andric 
2006e8d8bef9SDimitry Andric   Vec = Builder.CreateShuffleVector(Vec, Mask);
2007*0b57cec5SDimitry Andric   return RValue::get(Vec);
2008*0b57cec5SDimitry Andric }
2009*0b57cec5SDimitry Andric 
2010*0b57cec5SDimitry Andric /// Generates lvalue for partial ext_vector access.
2011*0b57cec5SDimitry Andric Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
2012*0b57cec5SDimitry Andric   Address VectorAddress = LV.getExtVectorAddress();
2013480093f4SDimitry Andric   QualType EQT = LV.getType()->castAs<VectorType>()->getElementType();
2014*0b57cec5SDimitry Andric   llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
2015*0b57cec5SDimitry Andric 
2016*0b57cec5SDimitry Andric   Address CastToPointerElement =
2017*0b57cec5SDimitry Andric     Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
2018*0b57cec5SDimitry Andric                                  "conv.ptr.element");
2019*0b57cec5SDimitry Andric 
2020*0b57cec5SDimitry Andric   const llvm::Constant *Elts = LV.getExtVectorElts();
2021*0b57cec5SDimitry Andric   unsigned ix = getAccessedFieldNo(0, Elts);
2022*0b57cec5SDimitry Andric 
2023*0b57cec5SDimitry Andric   Address VectorBasePtrPlusIx =
2024*0b57cec5SDimitry Andric     Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
2025*0b57cec5SDimitry Andric                                    "vector.elt");
2026*0b57cec5SDimitry Andric 
2027*0b57cec5SDimitry Andric   return VectorBasePtrPlusIx;
2028*0b57cec5SDimitry Andric }
2029*0b57cec5SDimitry Andric 
2030*0b57cec5SDimitry Andric /// Load of global gamed gegisters are always calls to intrinsics.
2031*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
2032*0b57cec5SDimitry Andric   assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
2033*0b57cec5SDimitry Andric          "Bad type for register variable");
2034*0b57cec5SDimitry Andric   llvm::MDNode *RegName = cast<llvm::MDNode>(
2035*0b57cec5SDimitry Andric       cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
2036*0b57cec5SDimitry Andric 
2037*0b57cec5SDimitry Andric   // We accept integer and pointer types only
2038*0b57cec5SDimitry Andric   llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
2039*0b57cec5SDimitry Andric   llvm::Type *Ty = OrigTy;
2040*0b57cec5SDimitry Andric   if (OrigTy->isPointerTy())
2041*0b57cec5SDimitry Andric     Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2042*0b57cec5SDimitry Andric   llvm::Type *Types[] = { Ty };
2043*0b57cec5SDimitry Andric 
2044*0b57cec5SDimitry Andric   llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
2045*0b57cec5SDimitry Andric   llvm::Value *Call = Builder.CreateCall(
2046*0b57cec5SDimitry Andric       F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
2047*0b57cec5SDimitry Andric   if (OrigTy->isPointerTy())
2048*0b57cec5SDimitry Andric     Call = Builder.CreateIntToPtr(Call, OrigTy);
2049*0b57cec5SDimitry Andric   return RValue::get(Call);
2050*0b57cec5SDimitry Andric }
2051*0b57cec5SDimitry Andric 
2052*0b57cec5SDimitry Andric /// EmitStoreThroughLValue - Store the specified rvalue into the specified
2053*0b57cec5SDimitry Andric /// lvalue, where both are guaranteed to the have the same type, and that type
2054*0b57cec5SDimitry Andric /// is 'Ty'.
2055*0b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
2056*0b57cec5SDimitry Andric                                              bool isInit) {
2057*0b57cec5SDimitry Andric   if (!Dst.isSimple()) {
2058*0b57cec5SDimitry Andric     if (Dst.isVectorElt()) {
2059*0b57cec5SDimitry Andric       // Read/modify/write the vector, inserting the new element.
2060*0b57cec5SDimitry Andric       llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
2061*0b57cec5SDimitry Andric                                             Dst.isVolatileQualified());
2062*0b57cec5SDimitry Andric       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
2063*0b57cec5SDimitry Andric                                         Dst.getVectorIdx(), "vecins");
2064*0b57cec5SDimitry Andric       Builder.CreateStore(Vec, Dst.getVectorAddress(),
2065*0b57cec5SDimitry Andric                           Dst.isVolatileQualified());
2066*0b57cec5SDimitry Andric       return;
2067*0b57cec5SDimitry Andric     }
2068*0b57cec5SDimitry Andric 
2069*0b57cec5SDimitry Andric     // If this is an update of extended vector elements, insert them as
2070*0b57cec5SDimitry Andric     // appropriate.
2071*0b57cec5SDimitry Andric     if (Dst.isExtVectorElt())
2072*0b57cec5SDimitry Andric       return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
2073*0b57cec5SDimitry Andric 
2074*0b57cec5SDimitry Andric     if (Dst.isGlobalReg())
2075*0b57cec5SDimitry Andric       return EmitStoreThroughGlobalRegLValue(Src, Dst);
2076*0b57cec5SDimitry Andric 
20775ffd83dbSDimitry Andric     if (Dst.isMatrixElt()) {
2078349cc55cSDimitry Andric       llvm::Value *Idx = Dst.getMatrixIdx();
2079349cc55cSDimitry Andric       if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
2080349cc55cSDimitry Andric         const auto *const MatTy = Dst.getType()->getAs<ConstantMatrixType>();
2081349cc55cSDimitry Andric         llvm::MatrixBuilder<CGBuilderTy> MB(Builder);
2082349cc55cSDimitry Andric         MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2083349cc55cSDimitry Andric       }
2084349cc55cSDimitry Andric       llvm::Instruction *Load = Builder.CreateLoad(Dst.getMatrixAddress());
2085349cc55cSDimitry Andric       llvm::Value *Vec =
2086349cc55cSDimitry Andric           Builder.CreateInsertElement(Load, Src.getScalarVal(), Idx, "matins");
20875ffd83dbSDimitry Andric       Builder.CreateStore(Vec, Dst.getMatrixAddress(),
20885ffd83dbSDimitry Andric                           Dst.isVolatileQualified());
20895ffd83dbSDimitry Andric       return;
20905ffd83dbSDimitry Andric     }
20915ffd83dbSDimitry Andric 
2092*0b57cec5SDimitry Andric     assert(Dst.isBitField() && "Unknown LValue type");
2093*0b57cec5SDimitry Andric     return EmitStoreThroughBitfieldLValue(Src, Dst);
2094*0b57cec5SDimitry Andric   }
2095*0b57cec5SDimitry Andric 
2096*0b57cec5SDimitry Andric   // There's special magic for assigning into an ARC-qualified l-value.
2097*0b57cec5SDimitry Andric   if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
2098*0b57cec5SDimitry Andric     switch (Lifetime) {
2099*0b57cec5SDimitry Andric     case Qualifiers::OCL_None:
2100*0b57cec5SDimitry Andric       llvm_unreachable("present but none");
2101*0b57cec5SDimitry Andric 
2102*0b57cec5SDimitry Andric     case Qualifiers::OCL_ExplicitNone:
2103*0b57cec5SDimitry Andric       // nothing special
2104*0b57cec5SDimitry Andric       break;
2105*0b57cec5SDimitry Andric 
2106*0b57cec5SDimitry Andric     case Qualifiers::OCL_Strong:
2107*0b57cec5SDimitry Andric       if (isInit) {
2108*0b57cec5SDimitry Andric         Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
2109*0b57cec5SDimitry Andric         break;
2110*0b57cec5SDimitry Andric       }
2111*0b57cec5SDimitry Andric       EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
2112*0b57cec5SDimitry Andric       return;
2113*0b57cec5SDimitry Andric 
2114*0b57cec5SDimitry Andric     case Qualifiers::OCL_Weak:
2115*0b57cec5SDimitry Andric       if (isInit)
2116*0b57cec5SDimitry Andric         // Initialize and then skip the primitive store.
2117480093f4SDimitry Andric         EmitARCInitWeak(Dst.getAddress(*this), Src.getScalarVal());
2118*0b57cec5SDimitry Andric       else
2119480093f4SDimitry Andric         EmitARCStoreWeak(Dst.getAddress(*this), Src.getScalarVal(),
2120480093f4SDimitry Andric                          /*ignore*/ true);
2121*0b57cec5SDimitry Andric       return;
2122*0b57cec5SDimitry Andric 
2123*0b57cec5SDimitry Andric     case Qualifiers::OCL_Autoreleasing:
2124*0b57cec5SDimitry Andric       Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
2125*0b57cec5SDimitry Andric                                                      Src.getScalarVal()));
2126*0b57cec5SDimitry Andric       // fall into the normal path
2127*0b57cec5SDimitry Andric       break;
2128*0b57cec5SDimitry Andric     }
2129*0b57cec5SDimitry Andric   }
2130*0b57cec5SDimitry Andric 
2131*0b57cec5SDimitry Andric   if (Dst.isObjCWeak() && !Dst.isNonGC()) {
2132*0b57cec5SDimitry Andric     // load of a __weak object.
2133480093f4SDimitry Andric     Address LvalueDst = Dst.getAddress(*this);
2134*0b57cec5SDimitry Andric     llvm::Value *src = Src.getScalarVal();
2135*0b57cec5SDimitry Andric      CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
2136*0b57cec5SDimitry Andric     return;
2137*0b57cec5SDimitry Andric   }
2138*0b57cec5SDimitry Andric 
2139*0b57cec5SDimitry Andric   if (Dst.isObjCStrong() && !Dst.isNonGC()) {
2140*0b57cec5SDimitry Andric     // load of a __strong object.
2141480093f4SDimitry Andric     Address LvalueDst = Dst.getAddress(*this);
2142*0b57cec5SDimitry Andric     llvm::Value *src = Src.getScalarVal();
2143*0b57cec5SDimitry Andric     if (Dst.isObjCIvar()) {
2144*0b57cec5SDimitry Andric       assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
2145*0b57cec5SDimitry Andric       llvm::Type *ResultType = IntPtrTy;
2146*0b57cec5SDimitry Andric       Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
2147*0b57cec5SDimitry Andric       llvm::Value *RHS = dst.getPointer();
2148*0b57cec5SDimitry Andric       RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
2149*0b57cec5SDimitry Andric       llvm::Value *LHS =
2150*0b57cec5SDimitry Andric         Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
2151*0b57cec5SDimitry Andric                                "sub.ptr.lhs.cast");
2152*0b57cec5SDimitry Andric       llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
2153*0b57cec5SDimitry Andric       CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
2154*0b57cec5SDimitry Andric                                               BytesBetween);
2155*0b57cec5SDimitry Andric     } else if (Dst.isGlobalObjCRef()) {
2156*0b57cec5SDimitry Andric       CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
2157*0b57cec5SDimitry Andric                                                 Dst.isThreadLocalRef());
2158*0b57cec5SDimitry Andric     }
2159*0b57cec5SDimitry Andric     else
2160*0b57cec5SDimitry Andric       CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
2161*0b57cec5SDimitry Andric     return;
2162*0b57cec5SDimitry Andric   }
2163*0b57cec5SDimitry Andric 
2164*0b57cec5SDimitry Andric   assert(Src.isScalar() && "Can't emit an agg store with this method");
2165*0b57cec5SDimitry Andric   EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
2166*0b57cec5SDimitry Andric }
2167*0b57cec5SDimitry Andric 
2168*0b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
2169*0b57cec5SDimitry Andric                                                      llvm::Value **Result) {
2170*0b57cec5SDimitry Andric   const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
2171*0b57cec5SDimitry Andric   llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
2172*0b57cec5SDimitry Andric   Address Ptr = Dst.getBitFieldAddress();
2173*0b57cec5SDimitry Andric 
2174*0b57cec5SDimitry Andric   // Get the source value, truncated to the width of the bit-field.
2175*0b57cec5SDimitry Andric   llvm::Value *SrcVal = Src.getScalarVal();
2176*0b57cec5SDimitry Andric 
2177*0b57cec5SDimitry Andric   // Cast the source to the storage type and shift it into place.
2178*0b57cec5SDimitry Andric   SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
2179*0b57cec5SDimitry Andric                                  /*isSigned=*/false);
2180*0b57cec5SDimitry Andric   llvm::Value *MaskedVal = SrcVal;
2181*0b57cec5SDimitry Andric 
2182e8d8bef9SDimitry Andric   const bool UseVolatile =
2183e8d8bef9SDimitry Andric       CGM.getCodeGenOpts().AAPCSBitfieldWidth && Dst.isVolatileQualified() &&
2184e8d8bef9SDimitry Andric       Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
2185e8d8bef9SDimitry Andric   const unsigned StorageSize =
2186e8d8bef9SDimitry Andric       UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
2187e8d8bef9SDimitry Andric   const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
2188*0b57cec5SDimitry Andric   // See if there are other bits in the bitfield's storage we'll need to load
2189*0b57cec5SDimitry Andric   // and mask together with source before storing.
2190e8d8bef9SDimitry Andric   if (StorageSize != Info.Size) {
2191e8d8bef9SDimitry Andric     assert(StorageSize > Info.Size && "Invalid bitfield size.");
2192*0b57cec5SDimitry Andric     llvm::Value *Val =
2193*0b57cec5SDimitry Andric         Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
2194*0b57cec5SDimitry Andric 
2195*0b57cec5SDimitry Andric     // Mask the source value as needed.
2196*0b57cec5SDimitry Andric     if (!hasBooleanRepresentation(Dst.getType()))
2197e8d8bef9SDimitry Andric       SrcVal = Builder.CreateAnd(
2198e8d8bef9SDimitry Andric           SrcVal, llvm::APInt::getLowBitsSet(StorageSize, Info.Size),
2199*0b57cec5SDimitry Andric           "bf.value");
2200*0b57cec5SDimitry Andric     MaskedVal = SrcVal;
2201e8d8bef9SDimitry Andric     if (Offset)
2202e8d8bef9SDimitry Andric       SrcVal = Builder.CreateShl(SrcVal, Offset, "bf.shl");
2203*0b57cec5SDimitry Andric 
2204*0b57cec5SDimitry Andric     // Mask out the original value.
2205e8d8bef9SDimitry Andric     Val = Builder.CreateAnd(
2206e8d8bef9SDimitry Andric         Val, ~llvm::APInt::getBitsSet(StorageSize, Offset, Offset + Info.Size),
2207*0b57cec5SDimitry Andric         "bf.clear");
2208*0b57cec5SDimitry Andric 
2209*0b57cec5SDimitry Andric     // Or together the unchanged values and the source value.
2210*0b57cec5SDimitry Andric     SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
2211*0b57cec5SDimitry Andric   } else {
2212e8d8bef9SDimitry Andric     assert(Offset == 0);
22135ffd83dbSDimitry Andric     // According to the AACPS:
22145ffd83dbSDimitry Andric     // When a volatile bit-field is written, and its container does not overlap
2215e8d8bef9SDimitry Andric     // with any non-bit-field member, its container must be read exactly once
2216e8d8bef9SDimitry Andric     // and written exactly once using the access width appropriate to the type
2217e8d8bef9SDimitry Andric     // of the container. The two accesses are not atomic.
22185ffd83dbSDimitry Andric     if (Dst.isVolatileQualified() && isAAPCS(CGM.getTarget()) &&
22195ffd83dbSDimitry Andric         CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad)
22205ffd83dbSDimitry Andric       Builder.CreateLoad(Ptr, true, "bf.load");
2221*0b57cec5SDimitry Andric   }
2222*0b57cec5SDimitry Andric 
2223*0b57cec5SDimitry Andric   // Write the new value back out.
2224*0b57cec5SDimitry Andric   Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
2225*0b57cec5SDimitry Andric 
2226*0b57cec5SDimitry Andric   // Return the new value of the bit-field, if requested.
2227*0b57cec5SDimitry Andric   if (Result) {
2228*0b57cec5SDimitry Andric     llvm::Value *ResultVal = MaskedVal;
2229*0b57cec5SDimitry Andric 
2230*0b57cec5SDimitry Andric     // Sign extend the value if needed.
2231*0b57cec5SDimitry Andric     if (Info.IsSigned) {
2232e8d8bef9SDimitry Andric       assert(Info.Size <= StorageSize);
2233e8d8bef9SDimitry Andric       unsigned HighBits = StorageSize - Info.Size;
2234*0b57cec5SDimitry Andric       if (HighBits) {
2235*0b57cec5SDimitry Andric         ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
2236*0b57cec5SDimitry Andric         ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
2237*0b57cec5SDimitry Andric       }
2238*0b57cec5SDimitry Andric     }
2239*0b57cec5SDimitry Andric 
2240*0b57cec5SDimitry Andric     ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
2241*0b57cec5SDimitry Andric                                       "bf.result.cast");
2242*0b57cec5SDimitry Andric     *Result = EmitFromMemory(ResultVal, Dst.getType());
2243*0b57cec5SDimitry Andric   }
2244*0b57cec5SDimitry Andric }
2245*0b57cec5SDimitry Andric 
2246*0b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
2247*0b57cec5SDimitry Andric                                                                LValue Dst) {
2248*0b57cec5SDimitry Andric   // This access turns into a read/modify/write of the vector.  Load the input
2249*0b57cec5SDimitry Andric   // value now.
2250*0b57cec5SDimitry Andric   llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
2251*0b57cec5SDimitry Andric                                         Dst.isVolatileQualified());
2252*0b57cec5SDimitry Andric   const llvm::Constant *Elts = Dst.getExtVectorElts();
2253*0b57cec5SDimitry Andric 
2254*0b57cec5SDimitry Andric   llvm::Value *SrcVal = Src.getScalarVal();
2255*0b57cec5SDimitry Andric 
2256*0b57cec5SDimitry Andric   if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
2257*0b57cec5SDimitry Andric     unsigned NumSrcElts = VTy->getNumElements();
22585ffd83dbSDimitry Andric     unsigned NumDstElts =
2259e8d8bef9SDimitry Andric         cast<llvm::FixedVectorType>(Vec->getType())->getNumElements();
2260*0b57cec5SDimitry Andric     if (NumDstElts == NumSrcElts) {
2261*0b57cec5SDimitry Andric       // Use shuffle vector is the src and destination are the same number of
2262*0b57cec5SDimitry Andric       // elements and restore the vector mask since it is on the side it will be
2263*0b57cec5SDimitry Andric       // stored.
22645ffd83dbSDimitry Andric       SmallVector<int, 4> Mask(NumDstElts);
2265*0b57cec5SDimitry Andric       for (unsigned i = 0; i != NumSrcElts; ++i)
22665ffd83dbSDimitry Andric         Mask[getAccessedFieldNo(i, Elts)] = i;
2267*0b57cec5SDimitry Andric 
2268e8d8bef9SDimitry Andric       Vec = Builder.CreateShuffleVector(SrcVal, Mask);
2269*0b57cec5SDimitry Andric     } else if (NumDstElts > NumSrcElts) {
2270*0b57cec5SDimitry Andric       // Extended the source vector to the same length and then shuffle it
2271*0b57cec5SDimitry Andric       // into the destination.
2272*0b57cec5SDimitry Andric       // FIXME: since we're shuffling with undef, can we just use the indices
2273*0b57cec5SDimitry Andric       //        into that?  This could be simpler.
22745ffd83dbSDimitry Andric       SmallVector<int, 4> ExtMask;
2275*0b57cec5SDimitry Andric       for (unsigned i = 0; i != NumSrcElts; ++i)
22765ffd83dbSDimitry Andric         ExtMask.push_back(i);
22775ffd83dbSDimitry Andric       ExtMask.resize(NumDstElts, -1);
2278e8d8bef9SDimitry Andric       llvm::Value *ExtSrcVal = Builder.CreateShuffleVector(SrcVal, ExtMask);
2279*0b57cec5SDimitry Andric       // build identity
22805ffd83dbSDimitry Andric       SmallVector<int, 4> Mask;
2281*0b57cec5SDimitry Andric       for (unsigned i = 0; i != NumDstElts; ++i)
22825ffd83dbSDimitry Andric         Mask.push_back(i);
2283*0b57cec5SDimitry Andric 
2284*0b57cec5SDimitry Andric       // When the vector size is odd and .odd or .hi is used, the last element
2285*0b57cec5SDimitry Andric       // of the Elts constant array will be one past the size of the vector.
2286*0b57cec5SDimitry Andric       // Ignore the last element here, if it is greater than the mask size.
2287*0b57cec5SDimitry Andric       if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
2288*0b57cec5SDimitry Andric         NumSrcElts--;
2289*0b57cec5SDimitry Andric 
2290*0b57cec5SDimitry Andric       // modify when what gets shuffled in
2291*0b57cec5SDimitry Andric       for (unsigned i = 0; i != NumSrcElts; ++i)
22925ffd83dbSDimitry Andric         Mask[getAccessedFieldNo(i, Elts)] = i + NumDstElts;
22935ffd83dbSDimitry Andric       Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, Mask);
2294*0b57cec5SDimitry Andric     } else {
2295*0b57cec5SDimitry Andric       // We should never shorten the vector
2296*0b57cec5SDimitry Andric       llvm_unreachable("unexpected shorten vector length");
2297*0b57cec5SDimitry Andric     }
2298*0b57cec5SDimitry Andric   } else {
2299*0b57cec5SDimitry Andric     // If the Src is a scalar (not a vector) it must be updating one element.
2300*0b57cec5SDimitry Andric     unsigned InIdx = getAccessedFieldNo(0, Elts);
2301*0b57cec5SDimitry Andric     llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
2302*0b57cec5SDimitry Andric     Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
2303*0b57cec5SDimitry Andric   }
2304*0b57cec5SDimitry Andric 
2305*0b57cec5SDimitry Andric   Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
2306*0b57cec5SDimitry Andric                       Dst.isVolatileQualified());
2307*0b57cec5SDimitry Andric }
2308*0b57cec5SDimitry Andric 
2309*0b57cec5SDimitry Andric /// Store of global named registers are always calls to intrinsics.
2310*0b57cec5SDimitry Andric void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
2311*0b57cec5SDimitry Andric   assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
2312*0b57cec5SDimitry Andric          "Bad type for register variable");
2313*0b57cec5SDimitry Andric   llvm::MDNode *RegName = cast<llvm::MDNode>(
2314*0b57cec5SDimitry Andric       cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
2315*0b57cec5SDimitry Andric   assert(RegName && "Register LValue is not metadata");
2316*0b57cec5SDimitry Andric 
2317*0b57cec5SDimitry Andric   // We accept integer and pointer types only
2318*0b57cec5SDimitry Andric   llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
2319*0b57cec5SDimitry Andric   llvm::Type *Ty = OrigTy;
2320*0b57cec5SDimitry Andric   if (OrigTy->isPointerTy())
2321*0b57cec5SDimitry Andric     Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2322*0b57cec5SDimitry Andric   llvm::Type *Types[] = { Ty };
2323*0b57cec5SDimitry Andric 
2324*0b57cec5SDimitry Andric   llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
2325*0b57cec5SDimitry Andric   llvm::Value *Value = Src.getScalarVal();
2326*0b57cec5SDimitry Andric   if (OrigTy->isPointerTy())
2327*0b57cec5SDimitry Andric     Value = Builder.CreatePtrToInt(Value, Ty);
2328*0b57cec5SDimitry Andric   Builder.CreateCall(
2329*0b57cec5SDimitry Andric       F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
2330*0b57cec5SDimitry Andric }
2331*0b57cec5SDimitry Andric 
2332*0b57cec5SDimitry Andric // setObjCGCLValueClass - sets class of the lvalue for the purpose of
2333*0b57cec5SDimitry Andric // generating write-barries API. It is currently a global, ivar,
2334*0b57cec5SDimitry Andric // or neither.
2335*0b57cec5SDimitry Andric static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
2336*0b57cec5SDimitry Andric                                  LValue &LV,
2337*0b57cec5SDimitry Andric                                  bool IsMemberAccess=false) {
2338*0b57cec5SDimitry Andric   if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
2339*0b57cec5SDimitry Andric     return;
2340*0b57cec5SDimitry Andric 
2341*0b57cec5SDimitry Andric   if (isa<ObjCIvarRefExpr>(E)) {
2342*0b57cec5SDimitry Andric     QualType ExpTy = E->getType();
2343*0b57cec5SDimitry Andric     if (IsMemberAccess && ExpTy->isPointerType()) {
2344*0b57cec5SDimitry Andric       // If ivar is a structure pointer, assigning to field of
2345*0b57cec5SDimitry Andric       // this struct follows gcc's behavior and makes it a non-ivar
2346*0b57cec5SDimitry Andric       // writer-barrier conservatively.
2347a7dea167SDimitry Andric       ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
2348*0b57cec5SDimitry Andric       if (ExpTy->isRecordType()) {
2349*0b57cec5SDimitry Andric         LV.setObjCIvar(false);
2350*0b57cec5SDimitry Andric         return;
2351*0b57cec5SDimitry Andric       }
2352*0b57cec5SDimitry Andric     }
2353*0b57cec5SDimitry Andric     LV.setObjCIvar(true);
2354*0b57cec5SDimitry Andric     auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
2355*0b57cec5SDimitry Andric     LV.setBaseIvarExp(Exp->getBase());
2356*0b57cec5SDimitry Andric     LV.setObjCArray(E->getType()->isArrayType());
2357*0b57cec5SDimitry Andric     return;
2358*0b57cec5SDimitry Andric   }
2359*0b57cec5SDimitry Andric 
2360*0b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
2361*0b57cec5SDimitry Andric     if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
2362*0b57cec5SDimitry Andric       if (VD->hasGlobalStorage()) {
2363*0b57cec5SDimitry Andric         LV.setGlobalObjCRef(true);
2364*0b57cec5SDimitry Andric         LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
2365*0b57cec5SDimitry Andric       }
2366*0b57cec5SDimitry Andric     }
2367*0b57cec5SDimitry Andric     LV.setObjCArray(E->getType()->isArrayType());
2368*0b57cec5SDimitry Andric     return;
2369*0b57cec5SDimitry Andric   }
2370*0b57cec5SDimitry Andric 
2371*0b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
2372*0b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2373*0b57cec5SDimitry Andric     return;
2374*0b57cec5SDimitry Andric   }
2375*0b57cec5SDimitry Andric 
2376*0b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
2377*0b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2378*0b57cec5SDimitry Andric     if (LV.isObjCIvar()) {
2379*0b57cec5SDimitry Andric       // If cast is to a structure pointer, follow gcc's behavior and make it
2380*0b57cec5SDimitry Andric       // a non-ivar write-barrier.
2381*0b57cec5SDimitry Andric       QualType ExpTy = E->getType();
2382*0b57cec5SDimitry Andric       if (ExpTy->isPointerType())
2383a7dea167SDimitry Andric         ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
2384*0b57cec5SDimitry Andric       if (ExpTy->isRecordType())
2385*0b57cec5SDimitry Andric         LV.setObjCIvar(false);
2386*0b57cec5SDimitry Andric     }
2387*0b57cec5SDimitry Andric     return;
2388*0b57cec5SDimitry Andric   }
2389*0b57cec5SDimitry Andric 
2390*0b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
2391*0b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2392*0b57cec5SDimitry Andric     return;
2393*0b57cec5SDimitry Andric   }
2394*0b57cec5SDimitry Andric 
2395*0b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
2396*0b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2397*0b57cec5SDimitry Andric     return;
2398*0b57cec5SDimitry Andric   }
2399*0b57cec5SDimitry Andric 
2400*0b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
2401*0b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2402*0b57cec5SDimitry Andric     return;
2403*0b57cec5SDimitry Andric   }
2404*0b57cec5SDimitry Andric 
2405*0b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
2406*0b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2407*0b57cec5SDimitry Andric     return;
2408*0b57cec5SDimitry Andric   }
2409*0b57cec5SDimitry Andric 
2410*0b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
2411*0b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
2412*0b57cec5SDimitry Andric     if (LV.isObjCIvar() && !LV.isObjCArray())
2413*0b57cec5SDimitry Andric       // Using array syntax to assigning to what an ivar points to is not
2414*0b57cec5SDimitry Andric       // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
2415*0b57cec5SDimitry Andric       LV.setObjCIvar(false);
2416*0b57cec5SDimitry Andric     else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
2417*0b57cec5SDimitry Andric       // Using array syntax to assigning to what global points to is not
2418*0b57cec5SDimitry Andric       // same as assigning to the global itself. {id *G;} G[i] = 0;
2419*0b57cec5SDimitry Andric       LV.setGlobalObjCRef(false);
2420*0b57cec5SDimitry Andric     return;
2421*0b57cec5SDimitry Andric   }
2422*0b57cec5SDimitry Andric 
2423*0b57cec5SDimitry Andric   if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
2424*0b57cec5SDimitry Andric     setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
2425*0b57cec5SDimitry Andric     // We don't know if member is an 'ivar', but this flag is looked at
2426*0b57cec5SDimitry Andric     // only in the context of LV.isObjCIvar().
2427*0b57cec5SDimitry Andric     LV.setObjCArray(E->getType()->isArrayType());
2428*0b57cec5SDimitry Andric     return;
2429*0b57cec5SDimitry Andric   }
2430*0b57cec5SDimitry Andric }
2431*0b57cec5SDimitry Andric 
2432*0b57cec5SDimitry Andric static llvm::Value *
2433*0b57cec5SDimitry Andric EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
2434*0b57cec5SDimitry Andric                                 llvm::Value *V, llvm::Type *IRType,
2435*0b57cec5SDimitry Andric                                 StringRef Name = StringRef()) {
2436*0b57cec5SDimitry Andric   unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
2437*0b57cec5SDimitry Andric   return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
2438*0b57cec5SDimitry Andric }
2439*0b57cec5SDimitry Andric 
2440*0b57cec5SDimitry Andric static LValue EmitThreadPrivateVarDeclLValue(
2441*0b57cec5SDimitry Andric     CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2442*0b57cec5SDimitry Andric     llvm::Type *RealVarTy, SourceLocation Loc) {
24435ffd83dbSDimitry Andric   if (CGF.CGM.getLangOpts().OpenMPIRBuilder)
24445ffd83dbSDimitry Andric     Addr = CodeGenFunction::OMPBuilderCBHelpers::getAddrOfThreadPrivate(
24455ffd83dbSDimitry Andric         CGF, VD, Addr, Loc);
24465ffd83dbSDimitry Andric   else
24475ffd83dbSDimitry Andric     Addr =
24485ffd83dbSDimitry Andric         CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
24495ffd83dbSDimitry Andric 
2450*0b57cec5SDimitry Andric   Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
2451*0b57cec5SDimitry Andric   return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2452*0b57cec5SDimitry Andric }
2453*0b57cec5SDimitry Andric 
2454*0b57cec5SDimitry Andric static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF,
2455*0b57cec5SDimitry Andric                                            const VarDecl *VD, QualType T) {
2456*0b57cec5SDimitry Andric   llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2457*0b57cec5SDimitry Andric       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2458*0b57cec5SDimitry Andric   // Return an invalid address if variable is MT_To and unified
2459*0b57cec5SDimitry Andric   // memory is not enabled. For all other cases: MT_Link and
2460*0b57cec5SDimitry Andric   // MT_To with unified memory, return a valid address.
2461*0b57cec5SDimitry Andric   if (!Res || (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2462*0b57cec5SDimitry Andric                !CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory()))
2463*0b57cec5SDimitry Andric     return Address::invalid();
2464*0b57cec5SDimitry Andric   assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
2465*0b57cec5SDimitry Andric           (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2466*0b57cec5SDimitry Andric            CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) &&
2467*0b57cec5SDimitry Andric          "Expected link clause OR to clause with unified memory enabled.");
2468*0b57cec5SDimitry Andric   QualType PtrTy = CGF.getContext().getPointerType(VD->getType());
2469*0b57cec5SDimitry Andric   Address Addr = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
2470*0b57cec5SDimitry Andric   return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>());
2471*0b57cec5SDimitry Andric }
2472*0b57cec5SDimitry Andric 
2473*0b57cec5SDimitry Andric Address
2474*0b57cec5SDimitry Andric CodeGenFunction::EmitLoadOfReference(LValue RefLVal,
2475*0b57cec5SDimitry Andric                                      LValueBaseInfo *PointeeBaseInfo,
2476*0b57cec5SDimitry Andric                                      TBAAAccessInfo *PointeeTBAAInfo) {
2477480093f4SDimitry Andric   llvm::LoadInst *Load =
2478480093f4SDimitry Andric       Builder.CreateLoad(RefLVal.getAddress(*this), RefLVal.isVolatile());
2479*0b57cec5SDimitry Andric   CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
2480*0b57cec5SDimitry Andric 
24810eae32dcSDimitry Andric   QualType PointeeType = RefLVal.getType()->getPointeeType();
24825ffd83dbSDimitry Andric   CharUnits Align = CGM.getNaturalTypeAlignment(
24830eae32dcSDimitry Andric       PointeeType, PointeeBaseInfo, PointeeTBAAInfo,
2484*0b57cec5SDimitry Andric       /* forPointeeType= */ true);
24850eae32dcSDimitry Andric   return Address(Load, ConvertTypeForMem(PointeeType), Align);
2486*0b57cec5SDimitry Andric }
2487*0b57cec5SDimitry Andric 
2488*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) {
2489*0b57cec5SDimitry Andric   LValueBaseInfo PointeeBaseInfo;
2490*0b57cec5SDimitry Andric   TBAAAccessInfo PointeeTBAAInfo;
2491*0b57cec5SDimitry Andric   Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
2492*0b57cec5SDimitry Andric                                             &PointeeTBAAInfo);
2493*0b57cec5SDimitry Andric   return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
2494*0b57cec5SDimitry Andric                         PointeeBaseInfo, PointeeTBAAInfo);
2495*0b57cec5SDimitry Andric }
2496*0b57cec5SDimitry Andric 
2497*0b57cec5SDimitry Andric Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2498*0b57cec5SDimitry Andric                                            const PointerType *PtrTy,
2499*0b57cec5SDimitry Andric                                            LValueBaseInfo *BaseInfo,
2500*0b57cec5SDimitry Andric                                            TBAAAccessInfo *TBAAInfo) {
2501*0b57cec5SDimitry Andric   llvm::Value *Addr = Builder.CreateLoad(Ptr);
25025ffd83dbSDimitry Andric   return Address(Addr, CGM.getNaturalTypeAlignment(PtrTy->getPointeeType(),
2503*0b57cec5SDimitry Andric                                                    BaseInfo, TBAAInfo,
2504*0b57cec5SDimitry Andric                                                    /*forPointeeType=*/true));
2505*0b57cec5SDimitry Andric }
2506*0b57cec5SDimitry Andric 
2507*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2508*0b57cec5SDimitry Andric                                                 const PointerType *PtrTy) {
2509*0b57cec5SDimitry Andric   LValueBaseInfo BaseInfo;
2510*0b57cec5SDimitry Andric   TBAAAccessInfo TBAAInfo;
2511*0b57cec5SDimitry Andric   Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
2512*0b57cec5SDimitry Andric   return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
2513*0b57cec5SDimitry Andric }
2514*0b57cec5SDimitry Andric 
2515*0b57cec5SDimitry Andric static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2516*0b57cec5SDimitry Andric                                       const Expr *E, const VarDecl *VD) {
2517*0b57cec5SDimitry Andric   QualType T = E->getType();
2518*0b57cec5SDimitry Andric 
2519*0b57cec5SDimitry Andric   // If it's thread_local, emit a call to its wrapper function instead.
2520*0b57cec5SDimitry Andric   if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2521a7dea167SDimitry Andric       CGF.CGM.getCXXABI().usesThreadWrapperFunction(VD))
2522*0b57cec5SDimitry Andric     return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2523*0b57cec5SDimitry Andric   // Check if the variable is marked as declare target with link clause in
2524*0b57cec5SDimitry Andric   // device codegen.
2525*0b57cec5SDimitry Andric   if (CGF.getLangOpts().OpenMPIsDevice) {
2526*0b57cec5SDimitry Andric     Address Addr = emitDeclTargetVarDeclLValue(CGF, VD, T);
2527*0b57cec5SDimitry Andric     if (Addr.isValid())
2528*0b57cec5SDimitry Andric       return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2529*0b57cec5SDimitry Andric   }
2530*0b57cec5SDimitry Andric 
2531*0b57cec5SDimitry Andric   llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2532*0b57cec5SDimitry Andric   llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2533*0b57cec5SDimitry Andric   V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
2534*0b57cec5SDimitry Andric   CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
25350eae32dcSDimitry Andric   Address Addr(V, RealVarTy, Alignment);
2536*0b57cec5SDimitry Andric   // Emit reference to the private copy of the variable if it is an OpenMP
2537*0b57cec5SDimitry Andric   // threadprivate variable.
2538*0b57cec5SDimitry Andric   if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
2539*0b57cec5SDimitry Andric       VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2540*0b57cec5SDimitry Andric     return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
2541*0b57cec5SDimitry Andric                                           E->getExprLoc());
2542*0b57cec5SDimitry Andric   }
2543*0b57cec5SDimitry Andric   LValue LV = VD->getType()->isReferenceType() ?
2544*0b57cec5SDimitry Andric       CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
2545*0b57cec5SDimitry Andric                                     AlignmentSource::Decl) :
2546*0b57cec5SDimitry Andric       CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2547*0b57cec5SDimitry Andric   setObjCGCLValueClass(CGF.getContext(), E, LV);
2548*0b57cec5SDimitry Andric   return LV;
2549*0b57cec5SDimitry Andric }
2550*0b57cec5SDimitry Andric 
2551*0b57cec5SDimitry Andric static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
25525ffd83dbSDimitry Andric                                                GlobalDecl GD) {
25535ffd83dbSDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2554*0b57cec5SDimitry Andric   if (FD->hasAttr<WeakRefAttr>()) {
2555*0b57cec5SDimitry Andric     ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2556*0b57cec5SDimitry Andric     return aliasee.getPointer();
2557*0b57cec5SDimitry Andric   }
2558*0b57cec5SDimitry Andric 
25595ffd83dbSDimitry Andric   llvm::Constant *V = CGM.GetAddrOfFunction(GD);
2560*0b57cec5SDimitry Andric   if (!FD->hasPrototype()) {
2561*0b57cec5SDimitry Andric     if (const FunctionProtoType *Proto =
2562*0b57cec5SDimitry Andric             FD->getType()->getAs<FunctionProtoType>()) {
2563*0b57cec5SDimitry Andric       // Ugly case: for a K&R-style definition, the type of the definition
2564*0b57cec5SDimitry Andric       // isn't the same as the type of a use.  Correct for this with a
2565*0b57cec5SDimitry Andric       // bitcast.
2566*0b57cec5SDimitry Andric       QualType NoProtoType =
2567*0b57cec5SDimitry Andric           CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2568*0b57cec5SDimitry Andric       NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2569*0b57cec5SDimitry Andric       V = llvm::ConstantExpr::getBitCast(V,
2570*0b57cec5SDimitry Andric                                       CGM.getTypes().ConvertType(NoProtoType));
2571*0b57cec5SDimitry Andric     }
2572*0b57cec5SDimitry Andric   }
2573*0b57cec5SDimitry Andric   return V;
2574*0b57cec5SDimitry Andric }
2575*0b57cec5SDimitry Andric 
25765ffd83dbSDimitry Andric static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E,
25775ffd83dbSDimitry Andric                                      GlobalDecl GD) {
25785ffd83dbSDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
25795ffd83dbSDimitry Andric   llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, GD);
2580*0b57cec5SDimitry Andric   CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
2581*0b57cec5SDimitry Andric   return CGF.MakeAddrLValue(V, E->getType(), Alignment,
2582*0b57cec5SDimitry Andric                             AlignmentSource::Decl);
2583*0b57cec5SDimitry Andric }
2584*0b57cec5SDimitry Andric 
2585*0b57cec5SDimitry Andric static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2586*0b57cec5SDimitry Andric                                       llvm::Value *ThisValue) {
2587*0b57cec5SDimitry Andric   QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2588*0b57cec5SDimitry Andric   LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2589*0b57cec5SDimitry Andric   return CGF.EmitLValueForField(LV, FD);
2590*0b57cec5SDimitry Andric }
2591*0b57cec5SDimitry Andric 
2592*0b57cec5SDimitry Andric /// Named Registers are named metadata pointing to the register name
2593*0b57cec5SDimitry Andric /// which will be read from/written to as an argument to the intrinsic
2594*0b57cec5SDimitry Andric /// @llvm.read/write_register.
2595*0b57cec5SDimitry Andric /// So far, only the name is being passed down, but other options such as
2596*0b57cec5SDimitry Andric /// register type, allocation type or even optimization options could be
2597*0b57cec5SDimitry Andric /// passed down via the metadata node.
2598*0b57cec5SDimitry Andric static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
2599*0b57cec5SDimitry Andric   SmallString<64> Name("llvm.named.register.");
2600*0b57cec5SDimitry Andric   AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
2601*0b57cec5SDimitry Andric   assert(Asm->getLabel().size() < 64-Name.size() &&
2602*0b57cec5SDimitry Andric       "Register name too big");
2603*0b57cec5SDimitry Andric   Name.append(Asm->getLabel());
2604*0b57cec5SDimitry Andric   llvm::NamedMDNode *M =
2605*0b57cec5SDimitry Andric     CGM.getModule().getOrInsertNamedMetadata(Name);
2606*0b57cec5SDimitry Andric   if (M->getNumOperands() == 0) {
2607*0b57cec5SDimitry Andric     llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2608*0b57cec5SDimitry Andric                                               Asm->getLabel());
2609*0b57cec5SDimitry Andric     llvm::Metadata *Ops[] = {Str};
2610*0b57cec5SDimitry Andric     M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2611*0b57cec5SDimitry Andric   }
2612*0b57cec5SDimitry Andric 
2613*0b57cec5SDimitry Andric   CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2614*0b57cec5SDimitry Andric 
2615*0b57cec5SDimitry Andric   llvm::Value *Ptr =
2616*0b57cec5SDimitry Andric     llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
26170eae32dcSDimitry Andric   return LValue::MakeGlobalReg(Ptr, Alignment, VD->getType());
2618*0b57cec5SDimitry Andric }
2619*0b57cec5SDimitry Andric 
2620*0b57cec5SDimitry Andric /// Determine whether we can emit a reference to \p VD from the current
2621*0b57cec5SDimitry Andric /// context, despite not necessarily having seen an odr-use of the variable in
2622*0b57cec5SDimitry Andric /// this context.
2623*0b57cec5SDimitry Andric static bool canEmitSpuriousReferenceToVariable(CodeGenFunction &CGF,
2624*0b57cec5SDimitry Andric                                                const DeclRefExpr *E,
2625*0b57cec5SDimitry Andric                                                const VarDecl *VD,
2626*0b57cec5SDimitry Andric                                                bool IsConstant) {
2627*0b57cec5SDimitry Andric   // For a variable declared in an enclosing scope, do not emit a spurious
2628*0b57cec5SDimitry Andric   // reference even if we have a capture, as that will emit an unwarranted
2629*0b57cec5SDimitry Andric   // reference to our capture state, and will likely generate worse code than
2630*0b57cec5SDimitry Andric   // emitting a local copy.
2631*0b57cec5SDimitry Andric   if (E->refersToEnclosingVariableOrCapture())
2632*0b57cec5SDimitry Andric     return false;
2633*0b57cec5SDimitry Andric 
2634*0b57cec5SDimitry Andric   // For a local declaration declared in this function, we can always reference
2635*0b57cec5SDimitry Andric   // it even if we don't have an odr-use.
2636*0b57cec5SDimitry Andric   if (VD->hasLocalStorage()) {
2637*0b57cec5SDimitry Andric     return VD->getDeclContext() ==
2638*0b57cec5SDimitry Andric            dyn_cast_or_null<DeclContext>(CGF.CurCodeDecl);
2639*0b57cec5SDimitry Andric   }
2640*0b57cec5SDimitry Andric 
2641*0b57cec5SDimitry Andric   // For a global declaration, we can emit a reference to it if we know
2642*0b57cec5SDimitry Andric   // for sure that we are able to emit a definition of it.
2643*0b57cec5SDimitry Andric   VD = VD->getDefinition(CGF.getContext());
2644*0b57cec5SDimitry Andric   if (!VD)
2645*0b57cec5SDimitry Andric     return false;
2646*0b57cec5SDimitry Andric 
2647*0b57cec5SDimitry Andric   // Don't emit a spurious reference if it might be to a variable that only
2648*0b57cec5SDimitry Andric   // exists on a different device / target.
2649*0b57cec5SDimitry Andric   // FIXME: This is unnecessarily broad. Check whether this would actually be a
2650*0b57cec5SDimitry Andric   // cross-target reference.
2651*0b57cec5SDimitry Andric   if (CGF.getLangOpts().OpenMP || CGF.getLangOpts().CUDA ||
2652*0b57cec5SDimitry Andric       CGF.getLangOpts().OpenCL) {
2653*0b57cec5SDimitry Andric     return false;
2654*0b57cec5SDimitry Andric   }
2655*0b57cec5SDimitry Andric 
2656*0b57cec5SDimitry Andric   // We can emit a spurious reference only if the linkage implies that we'll
2657*0b57cec5SDimitry Andric   // be emitting a non-interposable symbol that will be retained until link
2658*0b57cec5SDimitry Andric   // time.
2659*0b57cec5SDimitry Andric   switch (CGF.CGM.getLLVMLinkageVarDefinition(VD, IsConstant)) {
2660*0b57cec5SDimitry Andric   case llvm::GlobalValue::ExternalLinkage:
2661*0b57cec5SDimitry Andric   case llvm::GlobalValue::LinkOnceODRLinkage:
2662*0b57cec5SDimitry Andric   case llvm::GlobalValue::WeakODRLinkage:
2663*0b57cec5SDimitry Andric   case llvm::GlobalValue::InternalLinkage:
2664*0b57cec5SDimitry Andric   case llvm::GlobalValue::PrivateLinkage:
2665*0b57cec5SDimitry Andric     return true;
2666*0b57cec5SDimitry Andric   default:
2667*0b57cec5SDimitry Andric     return false;
2668*0b57cec5SDimitry Andric   }
2669*0b57cec5SDimitry Andric }
2670*0b57cec5SDimitry Andric 
2671*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
2672*0b57cec5SDimitry Andric   const NamedDecl *ND = E->getDecl();
2673*0b57cec5SDimitry Andric   QualType T = E->getType();
2674*0b57cec5SDimitry Andric 
2675*0b57cec5SDimitry Andric   assert(E->isNonOdrUse() != NOUR_Unevaluated &&
2676*0b57cec5SDimitry Andric          "should not emit an unevaluated operand");
2677*0b57cec5SDimitry Andric 
2678*0b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2679*0b57cec5SDimitry Andric     // Global Named registers access via intrinsics only
2680*0b57cec5SDimitry Andric     if (VD->getStorageClass() == SC_Register &&
2681*0b57cec5SDimitry Andric         VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
2682*0b57cec5SDimitry Andric       return EmitGlobalNamedRegister(VD, CGM);
2683*0b57cec5SDimitry Andric 
2684*0b57cec5SDimitry Andric     // If this DeclRefExpr does not constitute an odr-use of the variable,
2685*0b57cec5SDimitry Andric     // we're not permitted to emit a reference to it in general, and it might
2686*0b57cec5SDimitry Andric     // not be captured if capture would be necessary for a use. Emit the
2687*0b57cec5SDimitry Andric     // constant value directly instead.
2688*0b57cec5SDimitry Andric     if (E->isNonOdrUse() == NOUR_Constant &&
2689*0b57cec5SDimitry Andric         (VD->getType()->isReferenceType() ||
2690*0b57cec5SDimitry Andric          !canEmitSpuriousReferenceToVariable(*this, E, VD, true))) {
2691*0b57cec5SDimitry Andric       VD->getAnyInitializer(VD);
2692*0b57cec5SDimitry Andric       llvm::Constant *Val = ConstantEmitter(*this).emitAbstract(
2693*0b57cec5SDimitry Andric           E->getLocation(), *VD->evaluateValue(), VD->getType());
2694*0b57cec5SDimitry Andric       assert(Val && "failed to emit constant expression");
2695*0b57cec5SDimitry Andric 
2696*0b57cec5SDimitry Andric       Address Addr = Address::invalid();
2697*0b57cec5SDimitry Andric       if (!VD->getType()->isReferenceType()) {
2698*0b57cec5SDimitry Andric         // Spill the constant value to a global.
2699*0b57cec5SDimitry Andric         Addr = CGM.createUnnamedGlobalFrom(*VD, Val,
2700*0b57cec5SDimitry Andric                                            getContext().getDeclAlign(VD));
2701c14a5a88SDimitry Andric         llvm::Type *VarTy = getTypes().ConvertTypeForMem(VD->getType());
2702c14a5a88SDimitry Andric         auto *PTy = llvm::PointerType::get(
2703c14a5a88SDimitry Andric             VarTy, getContext().getTargetAddressSpace(VD->getType()));
2704c14a5a88SDimitry Andric         if (PTy != Addr.getType())
2705c14a5a88SDimitry Andric           Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy);
2706*0b57cec5SDimitry Andric       } else {
2707*0b57cec5SDimitry Andric         // Should we be using the alignment of the constant pointer we emitted?
2708*0b57cec5SDimitry Andric         CharUnits Alignment =
27095ffd83dbSDimitry Andric             CGM.getNaturalTypeAlignment(E->getType(),
2710*0b57cec5SDimitry Andric                                         /* BaseInfo= */ nullptr,
2711*0b57cec5SDimitry Andric                                         /* TBAAInfo= */ nullptr,
2712*0b57cec5SDimitry Andric                                         /* forPointeeType= */ true);
27130eae32dcSDimitry Andric         Addr = Address(Val, ConvertTypeForMem(E->getType()), Alignment);
2714*0b57cec5SDimitry Andric       }
2715*0b57cec5SDimitry Andric       return MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2716*0b57cec5SDimitry Andric     }
2717*0b57cec5SDimitry Andric 
2718*0b57cec5SDimitry Andric     // FIXME: Handle other kinds of non-odr-use DeclRefExprs.
2719*0b57cec5SDimitry Andric 
2720*0b57cec5SDimitry Andric     // Check for captured variables.
2721*0b57cec5SDimitry Andric     if (E->refersToEnclosingVariableOrCapture()) {
2722*0b57cec5SDimitry Andric       VD = VD->getCanonicalDecl();
2723*0b57cec5SDimitry Andric       if (auto *FD = LambdaCaptureFields.lookup(VD))
2724*0b57cec5SDimitry Andric         return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2725480093f4SDimitry Andric       if (CapturedStmtInfo) {
2726*0b57cec5SDimitry Andric         auto I = LocalDeclMap.find(VD);
2727*0b57cec5SDimitry Andric         if (I != LocalDeclMap.end()) {
2728480093f4SDimitry Andric           LValue CapLVal;
2729*0b57cec5SDimitry Andric           if (VD->getType()->isReferenceType())
2730480093f4SDimitry Andric             CapLVal = EmitLoadOfReferenceLValue(I->second, VD->getType(),
2731*0b57cec5SDimitry Andric                                                 AlignmentSource::Decl);
2732480093f4SDimitry Andric           else
2733480093f4SDimitry Andric             CapLVal = MakeAddrLValue(I->second, T);
2734480093f4SDimitry Andric           // Mark lvalue as nontemporal if the variable is marked as nontemporal
2735480093f4SDimitry Andric           // in simd context.
2736480093f4SDimitry Andric           if (getLangOpts().OpenMP &&
2737480093f4SDimitry Andric               CGM.getOpenMPRuntime().isNontemporalDecl(VD))
2738480093f4SDimitry Andric             CapLVal.setNontemporal(/*Value=*/true);
2739480093f4SDimitry Andric           return CapLVal;
2740*0b57cec5SDimitry Andric         }
2741*0b57cec5SDimitry Andric         LValue CapLVal =
2742*0b57cec5SDimitry Andric             EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2743*0b57cec5SDimitry Andric                                     CapturedStmtInfo->getContextValue());
2744480093f4SDimitry Andric         CapLVal = MakeAddrLValue(
2745480093f4SDimitry Andric             Address(CapLVal.getPointer(*this), getContext().getDeclAlign(VD)),
2746*0b57cec5SDimitry Andric             CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl),
2747*0b57cec5SDimitry Andric             CapLVal.getTBAAInfo());
2748480093f4SDimitry Andric         // Mark lvalue as nontemporal if the variable is marked as nontemporal
2749480093f4SDimitry Andric         // in simd context.
2750480093f4SDimitry Andric         if (getLangOpts().OpenMP &&
2751480093f4SDimitry Andric             CGM.getOpenMPRuntime().isNontemporalDecl(VD))
2752480093f4SDimitry Andric           CapLVal.setNontemporal(/*Value=*/true);
2753480093f4SDimitry Andric         return CapLVal;
2754*0b57cec5SDimitry Andric       }
2755*0b57cec5SDimitry Andric 
2756*0b57cec5SDimitry Andric       assert(isa<BlockDecl>(CurCodeDecl));
2757*0b57cec5SDimitry Andric       Address addr = GetAddrOfBlockDecl(VD);
2758*0b57cec5SDimitry Andric       return MakeAddrLValue(addr, T, AlignmentSource::Decl);
2759*0b57cec5SDimitry Andric     }
2760*0b57cec5SDimitry Andric   }
2761*0b57cec5SDimitry Andric 
2762*0b57cec5SDimitry Andric   // FIXME: We should be able to assert this for FunctionDecls as well!
2763*0b57cec5SDimitry Andric   // FIXME: We should be able to assert this for all DeclRefExprs, not just
2764*0b57cec5SDimitry Andric   // those with a valid source location.
2765*0b57cec5SDimitry Andric   assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() ||
2766*0b57cec5SDimitry Andric           !E->getLocation().isValid()) &&
2767*0b57cec5SDimitry Andric          "Should not use decl without marking it used!");
2768*0b57cec5SDimitry Andric 
2769*0b57cec5SDimitry Andric   if (ND->hasAttr<WeakRefAttr>()) {
2770*0b57cec5SDimitry Andric     const auto *VD = cast<ValueDecl>(ND);
2771*0b57cec5SDimitry Andric     ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2772*0b57cec5SDimitry Andric     return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
2773*0b57cec5SDimitry Andric   }
2774*0b57cec5SDimitry Andric 
2775*0b57cec5SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2776*0b57cec5SDimitry Andric     // Check if this is a global variable.
2777*0b57cec5SDimitry Andric     if (VD->hasLinkage() || VD->isStaticDataMember())
2778*0b57cec5SDimitry Andric       return EmitGlobalVarDeclLValue(*this, E, VD);
2779*0b57cec5SDimitry Andric 
2780*0b57cec5SDimitry Andric     Address addr = Address::invalid();
2781*0b57cec5SDimitry Andric 
2782*0b57cec5SDimitry Andric     // The variable should generally be present in the local decl map.
2783*0b57cec5SDimitry Andric     auto iter = LocalDeclMap.find(VD);
2784*0b57cec5SDimitry Andric     if (iter != LocalDeclMap.end()) {
2785*0b57cec5SDimitry Andric       addr = iter->second;
2786*0b57cec5SDimitry Andric 
2787*0b57cec5SDimitry Andric     // Otherwise, it might be static local we haven't emitted yet for
2788*0b57cec5SDimitry Andric     // some reason; most likely, because it's in an outer function.
2789*0b57cec5SDimitry Andric     } else if (VD->isStaticLocal()) {
27900eae32dcSDimitry Andric       llvm::Constant *var = CGM.getOrCreateStaticVarDecl(
27910eae32dcSDimitry Andric           *VD, CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false));
27920eae32dcSDimitry Andric       addr = Address(
27930eae32dcSDimitry Andric           var, ConvertTypeForMem(VD->getType()), getContext().getDeclAlign(VD));
2794*0b57cec5SDimitry Andric 
2795*0b57cec5SDimitry Andric     // No other cases for now.
2796*0b57cec5SDimitry Andric     } else {
2797*0b57cec5SDimitry Andric       llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2798*0b57cec5SDimitry Andric     }
2799*0b57cec5SDimitry Andric 
2800*0b57cec5SDimitry Andric 
2801*0b57cec5SDimitry Andric     // Check for OpenMP threadprivate variables.
2802*0b57cec5SDimitry Andric     if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
2803*0b57cec5SDimitry Andric         VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2804*0b57cec5SDimitry Andric       return EmitThreadPrivateVarDeclLValue(
2805*0b57cec5SDimitry Andric           *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2806*0b57cec5SDimitry Andric           E->getExprLoc());
2807*0b57cec5SDimitry Andric     }
2808*0b57cec5SDimitry Andric 
2809*0b57cec5SDimitry Andric     // Drill into block byref variables.
2810*0b57cec5SDimitry Andric     bool isBlockByref = VD->isEscapingByref();
2811*0b57cec5SDimitry Andric     if (isBlockByref) {
2812*0b57cec5SDimitry Andric       addr = emitBlockByrefAddress(addr, VD);
2813*0b57cec5SDimitry Andric     }
2814*0b57cec5SDimitry Andric 
2815*0b57cec5SDimitry Andric     // Drill into reference types.
2816*0b57cec5SDimitry Andric     LValue LV = VD->getType()->isReferenceType() ?
2817*0b57cec5SDimitry Andric         EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) :
2818*0b57cec5SDimitry Andric         MakeAddrLValue(addr, T, AlignmentSource::Decl);
2819*0b57cec5SDimitry Andric 
2820*0b57cec5SDimitry Andric     bool isLocalStorage = VD->hasLocalStorage();
2821*0b57cec5SDimitry Andric 
2822*0b57cec5SDimitry Andric     bool NonGCable = isLocalStorage &&
2823*0b57cec5SDimitry Andric                      !VD->getType()->isReferenceType() &&
2824*0b57cec5SDimitry Andric                      !isBlockByref;
2825*0b57cec5SDimitry Andric     if (NonGCable) {
2826*0b57cec5SDimitry Andric       LV.getQuals().removeObjCGCAttr();
2827*0b57cec5SDimitry Andric       LV.setNonGC(true);
2828*0b57cec5SDimitry Andric     }
2829*0b57cec5SDimitry Andric 
2830*0b57cec5SDimitry Andric     bool isImpreciseLifetime =
2831*0b57cec5SDimitry Andric       (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2832*0b57cec5SDimitry Andric     if (isImpreciseLifetime)
2833*0b57cec5SDimitry Andric       LV.setARCPreciseLifetime(ARCImpreciseLifetime);
2834*0b57cec5SDimitry Andric     setObjCGCLValueClass(getContext(), E, LV);
2835*0b57cec5SDimitry Andric     return LV;
2836*0b57cec5SDimitry Andric   }
2837*0b57cec5SDimitry Andric 
2838fe6060f1SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
2839fe6060f1SDimitry Andric     LValue LV = EmitFunctionDeclLValue(*this, E, FD);
2840fe6060f1SDimitry Andric 
2841fe6060f1SDimitry Andric     // Emit debuginfo for the function declaration if the target wants to.
2842fe6060f1SDimitry Andric     if (getContext().getTargetInfo().allowDebugInfoForExternalRef()) {
2843fe6060f1SDimitry Andric       if (CGDebugInfo *DI = CGM.getModuleDebugInfo()) {
2844fe6060f1SDimitry Andric         auto *Fn =
2845fe6060f1SDimitry Andric             cast<llvm::Function>(LV.getPointer(*this)->stripPointerCasts());
2846fe6060f1SDimitry Andric         if (!Fn->getSubprogram())
2847fe6060f1SDimitry Andric           DI->EmitFunctionDecl(FD, FD->getLocation(), T, Fn);
2848fe6060f1SDimitry Andric       }
2849fe6060f1SDimitry Andric     }
2850fe6060f1SDimitry Andric 
2851fe6060f1SDimitry Andric     return LV;
2852fe6060f1SDimitry Andric   }
2853*0b57cec5SDimitry Andric 
2854*0b57cec5SDimitry Andric   // FIXME: While we're emitting a binding from an enclosing scope, all other
2855*0b57cec5SDimitry Andric   // DeclRefExprs we see should be implicitly treated as if they also refer to
2856*0b57cec5SDimitry Andric   // an enclosing scope.
2857*0b57cec5SDimitry Andric   if (const auto *BD = dyn_cast<BindingDecl>(ND))
2858*0b57cec5SDimitry Andric     return EmitLValue(BD->getBinding());
2859*0b57cec5SDimitry Andric 
28605ffd83dbSDimitry Andric   // We can form DeclRefExprs naming GUID declarations when reconstituting
28615ffd83dbSDimitry Andric   // non-type template parameters into expressions.
28625ffd83dbSDimitry Andric   if (const auto *GD = dyn_cast<MSGuidDecl>(ND))
28635ffd83dbSDimitry Andric     return MakeAddrLValue(CGM.GetAddrOfMSGuidDecl(GD), T,
28645ffd83dbSDimitry Andric                           AlignmentSource::Decl);
28655ffd83dbSDimitry Andric 
2866e8d8bef9SDimitry Andric   if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND))
2867e8d8bef9SDimitry Andric     return MakeAddrLValue(CGM.GetAddrOfTemplateParamObject(TPO), T,
2868e8d8bef9SDimitry Andric                           AlignmentSource::Decl);
2869e8d8bef9SDimitry Andric 
2870*0b57cec5SDimitry Andric   llvm_unreachable("Unhandled DeclRefExpr");
2871*0b57cec5SDimitry Andric }
2872*0b57cec5SDimitry Andric 
2873*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2874*0b57cec5SDimitry Andric   // __extension__ doesn't affect lvalue-ness.
2875*0b57cec5SDimitry Andric   if (E->getOpcode() == UO_Extension)
2876*0b57cec5SDimitry Andric     return EmitLValue(E->getSubExpr());
2877*0b57cec5SDimitry Andric 
2878*0b57cec5SDimitry Andric   QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
2879*0b57cec5SDimitry Andric   switch (E->getOpcode()) {
2880*0b57cec5SDimitry Andric   default: llvm_unreachable("Unknown unary operator lvalue!");
2881*0b57cec5SDimitry Andric   case UO_Deref: {
2882*0b57cec5SDimitry Andric     QualType T = E->getSubExpr()->getType()->getPointeeType();
2883*0b57cec5SDimitry Andric     assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
2884*0b57cec5SDimitry Andric 
2885*0b57cec5SDimitry Andric     LValueBaseInfo BaseInfo;
2886*0b57cec5SDimitry Andric     TBAAAccessInfo TBAAInfo;
2887*0b57cec5SDimitry Andric     Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo,
2888*0b57cec5SDimitry Andric                                             &TBAAInfo);
2889*0b57cec5SDimitry Andric     LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
2890*0b57cec5SDimitry Andric     LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
2891*0b57cec5SDimitry Andric 
2892*0b57cec5SDimitry Andric     // We should not generate __weak write barrier on indirect reference
2893*0b57cec5SDimitry Andric     // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2894*0b57cec5SDimitry Andric     // But, we continue to generate __strong write barrier on indirect write
2895*0b57cec5SDimitry Andric     // into a pointer to object.
2896*0b57cec5SDimitry Andric     if (getLangOpts().ObjC &&
2897*0b57cec5SDimitry Andric         getLangOpts().getGC() != LangOptions::NonGC &&
2898*0b57cec5SDimitry Andric         LV.isObjCWeak())
2899*0b57cec5SDimitry Andric       LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2900*0b57cec5SDimitry Andric     return LV;
2901*0b57cec5SDimitry Andric   }
2902*0b57cec5SDimitry Andric   case UO_Real:
2903*0b57cec5SDimitry Andric   case UO_Imag: {
2904*0b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
2905*0b57cec5SDimitry Andric     assert(LV.isSimple() && "real/imag on non-ordinary l-value");
2906*0b57cec5SDimitry Andric 
2907*0b57cec5SDimitry Andric     // __real is valid on scalars.  This is a faster way of testing that.
2908*0b57cec5SDimitry Andric     // __imag can only produce an rvalue on scalars.
2909*0b57cec5SDimitry Andric     if (E->getOpcode() == UO_Real &&
2910480093f4SDimitry Andric         !LV.getAddress(*this).getElementType()->isStructTy()) {
2911*0b57cec5SDimitry Andric       assert(E->getSubExpr()->getType()->isArithmeticType());
2912*0b57cec5SDimitry Andric       return LV;
2913*0b57cec5SDimitry Andric     }
2914*0b57cec5SDimitry Andric 
2915*0b57cec5SDimitry Andric     QualType T = ExprTy->castAs<ComplexType>()->getElementType();
2916*0b57cec5SDimitry Andric 
2917*0b57cec5SDimitry Andric     Address Component =
2918*0b57cec5SDimitry Andric         (E->getOpcode() == UO_Real
2919480093f4SDimitry Andric              ? emitAddrOfRealComponent(LV.getAddress(*this), LV.getType())
2920480093f4SDimitry Andric              : emitAddrOfImagComponent(LV.getAddress(*this), LV.getType()));
2921*0b57cec5SDimitry Andric     LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
2922*0b57cec5SDimitry Andric                                    CGM.getTBAAInfoForSubobject(LV, T));
2923*0b57cec5SDimitry Andric     ElemLV.getQuals().addQualifiers(LV.getQuals());
2924*0b57cec5SDimitry Andric     return ElemLV;
2925*0b57cec5SDimitry Andric   }
2926*0b57cec5SDimitry Andric   case UO_PreInc:
2927*0b57cec5SDimitry Andric   case UO_PreDec: {
2928*0b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
2929*0b57cec5SDimitry Andric     bool isInc = E->getOpcode() == UO_PreInc;
2930*0b57cec5SDimitry Andric 
2931*0b57cec5SDimitry Andric     if (E->getType()->isAnyComplexType())
2932*0b57cec5SDimitry Andric       EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2933*0b57cec5SDimitry Andric     else
2934*0b57cec5SDimitry Andric       EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2935*0b57cec5SDimitry Andric     return LV;
2936*0b57cec5SDimitry Andric   }
2937*0b57cec5SDimitry Andric   }
2938*0b57cec5SDimitry Andric }
2939*0b57cec5SDimitry Andric 
2940*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
2941*0b57cec5SDimitry Andric   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
2942*0b57cec5SDimitry Andric                         E->getType(), AlignmentSource::Decl);
2943*0b57cec5SDimitry Andric }
2944*0b57cec5SDimitry Andric 
2945*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
2946*0b57cec5SDimitry Andric   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
2947*0b57cec5SDimitry Andric                         E->getType(), AlignmentSource::Decl);
2948*0b57cec5SDimitry Andric }
2949*0b57cec5SDimitry Andric 
2950*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
2951*0b57cec5SDimitry Andric   auto SL = E->getFunctionName();
2952*0b57cec5SDimitry Andric   assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2953*0b57cec5SDimitry Andric   StringRef FnName = CurFn->getName();
2954*0b57cec5SDimitry Andric   if (FnName.startswith("\01"))
2955*0b57cec5SDimitry Andric     FnName = FnName.substr(1);
2956*0b57cec5SDimitry Andric   StringRef NameItems[] = {
2957*0b57cec5SDimitry Andric       PredefinedExpr::getIdentKindName(E->getIdentKind()), FnName};
2958*0b57cec5SDimitry Andric   std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
2959*0b57cec5SDimitry Andric   if (auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl)) {
29605ffd83dbSDimitry Andric     std::string Name = std::string(SL->getString());
2961*0b57cec5SDimitry Andric     if (!Name.empty()) {
2962*0b57cec5SDimitry Andric       unsigned Discriminator =
2963*0b57cec5SDimitry Andric           CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2964*0b57cec5SDimitry Andric       if (Discriminator)
2965*0b57cec5SDimitry Andric         Name += "_" + Twine(Discriminator + 1).str();
2966*0b57cec5SDimitry Andric       auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
2967*0b57cec5SDimitry Andric       return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2968*0b57cec5SDimitry Andric     } else {
29695ffd83dbSDimitry Andric       auto C =
29705ffd83dbSDimitry Andric           CGM.GetAddrOfConstantCString(std::string(FnName), GVName.c_str());
2971*0b57cec5SDimitry Andric       return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2972*0b57cec5SDimitry Andric     }
2973*0b57cec5SDimitry Andric   }
2974*0b57cec5SDimitry Andric   auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
2975*0b57cec5SDimitry Andric   return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
2976*0b57cec5SDimitry Andric }
2977*0b57cec5SDimitry Andric 
2978*0b57cec5SDimitry Andric /// Emit a type description suitable for use by a runtime sanitizer library. The
2979*0b57cec5SDimitry Andric /// format of a type descriptor is
2980*0b57cec5SDimitry Andric ///
2981*0b57cec5SDimitry Andric /// \code
2982*0b57cec5SDimitry Andric ///   { i16 TypeKind, i16 TypeInfo }
2983*0b57cec5SDimitry Andric /// \endcode
2984*0b57cec5SDimitry Andric ///
2985*0b57cec5SDimitry Andric /// followed by an array of i8 containing the type name. TypeKind is 0 for an
2986*0b57cec5SDimitry Andric /// integer, 1 for a floating point value, and -1 for anything else.
2987*0b57cec5SDimitry Andric llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
2988*0b57cec5SDimitry Andric   // Only emit each type's descriptor once.
2989*0b57cec5SDimitry Andric   if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
2990*0b57cec5SDimitry Andric     return C;
2991*0b57cec5SDimitry Andric 
2992*0b57cec5SDimitry Andric   uint16_t TypeKind = -1;
2993*0b57cec5SDimitry Andric   uint16_t TypeInfo = 0;
2994*0b57cec5SDimitry Andric 
2995*0b57cec5SDimitry Andric   if (T->isIntegerType()) {
2996*0b57cec5SDimitry Andric     TypeKind = 0;
2997*0b57cec5SDimitry Andric     TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
2998*0b57cec5SDimitry Andric                (T->isSignedIntegerType() ? 1 : 0);
2999*0b57cec5SDimitry Andric   } else if (T->isFloatingType()) {
3000*0b57cec5SDimitry Andric     TypeKind = 1;
3001*0b57cec5SDimitry Andric     TypeInfo = getContext().getTypeSize(T);
3002*0b57cec5SDimitry Andric   }
3003*0b57cec5SDimitry Andric 
3004*0b57cec5SDimitry Andric   // Format the type name as if for a diagnostic, including quotes and
3005*0b57cec5SDimitry Andric   // optionally an 'aka'.
3006*0b57cec5SDimitry Andric   SmallString<32> Buffer;
3007*0b57cec5SDimitry Andric   CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
3008*0b57cec5SDimitry Andric                                     (intptr_t)T.getAsOpaquePtr(),
3009*0b57cec5SDimitry Andric                                     StringRef(), StringRef(), None, Buffer,
3010*0b57cec5SDimitry Andric                                     None);
3011*0b57cec5SDimitry Andric 
3012*0b57cec5SDimitry Andric   llvm::Constant *Components[] = {
3013*0b57cec5SDimitry Andric     Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
3014*0b57cec5SDimitry Andric     llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
3015*0b57cec5SDimitry Andric   };
3016*0b57cec5SDimitry Andric   llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
3017*0b57cec5SDimitry Andric 
3018*0b57cec5SDimitry Andric   auto *GV = new llvm::GlobalVariable(
3019*0b57cec5SDimitry Andric       CGM.getModule(), Descriptor->getType(),
3020*0b57cec5SDimitry Andric       /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
3021*0b57cec5SDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3022*0b57cec5SDimitry Andric   CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
3023*0b57cec5SDimitry Andric 
3024*0b57cec5SDimitry Andric   // Remember the descriptor for this type.
3025*0b57cec5SDimitry Andric   CGM.setTypeDescriptorInMap(T, GV);
3026*0b57cec5SDimitry Andric 
3027*0b57cec5SDimitry Andric   return GV;
3028*0b57cec5SDimitry Andric }
3029*0b57cec5SDimitry Andric 
3030*0b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
3031*0b57cec5SDimitry Andric   llvm::Type *TargetTy = IntPtrTy;
3032*0b57cec5SDimitry Andric 
3033*0b57cec5SDimitry Andric   if (V->getType() == TargetTy)
3034*0b57cec5SDimitry Andric     return V;
3035*0b57cec5SDimitry Andric 
3036*0b57cec5SDimitry Andric   // Floating-point types which fit into intptr_t are bitcast to integers
3037*0b57cec5SDimitry Andric   // and then passed directly (after zero-extension, if necessary).
3038*0b57cec5SDimitry Andric   if (V->getType()->isFloatingPointTy()) {
3039e8d8bef9SDimitry Andric     unsigned Bits = V->getType()->getPrimitiveSizeInBits().getFixedSize();
3040*0b57cec5SDimitry Andric     if (Bits <= TargetTy->getIntegerBitWidth())
3041*0b57cec5SDimitry Andric       V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
3042*0b57cec5SDimitry Andric                                                          Bits));
3043*0b57cec5SDimitry Andric   }
3044*0b57cec5SDimitry Andric 
3045*0b57cec5SDimitry Andric   // Integers which fit in intptr_t are zero-extended and passed directly.
3046*0b57cec5SDimitry Andric   if (V->getType()->isIntegerTy() &&
3047*0b57cec5SDimitry Andric       V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
3048*0b57cec5SDimitry Andric     return Builder.CreateZExt(V, TargetTy);
3049*0b57cec5SDimitry Andric 
3050*0b57cec5SDimitry Andric   // Pointers are passed directly, everything else is passed by address.
3051*0b57cec5SDimitry Andric   if (!V->getType()->isPointerTy()) {
3052*0b57cec5SDimitry Andric     Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
3053*0b57cec5SDimitry Andric     Builder.CreateStore(V, Ptr);
3054*0b57cec5SDimitry Andric     V = Ptr.getPointer();
3055*0b57cec5SDimitry Andric   }
3056*0b57cec5SDimitry Andric   return Builder.CreatePtrToInt(V, TargetTy);
3057*0b57cec5SDimitry Andric }
3058*0b57cec5SDimitry Andric 
3059*0b57cec5SDimitry Andric /// Emit a representation of a SourceLocation for passing to a handler
3060*0b57cec5SDimitry Andric /// in a sanitizer runtime library. The format for this data is:
3061*0b57cec5SDimitry Andric /// \code
3062*0b57cec5SDimitry Andric ///   struct SourceLocation {
3063*0b57cec5SDimitry Andric ///     const char *Filename;
3064*0b57cec5SDimitry Andric ///     int32_t Line, Column;
3065*0b57cec5SDimitry Andric ///   };
3066*0b57cec5SDimitry Andric /// \endcode
3067*0b57cec5SDimitry Andric /// For an invalid SourceLocation, the Filename pointer is null.
3068*0b57cec5SDimitry Andric llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
3069*0b57cec5SDimitry Andric   llvm::Constant *Filename;
3070*0b57cec5SDimitry Andric   int Line, Column;
3071*0b57cec5SDimitry Andric 
3072*0b57cec5SDimitry Andric   PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
3073*0b57cec5SDimitry Andric   if (PLoc.isValid()) {
3074*0b57cec5SDimitry Andric     StringRef FilenameString = PLoc.getFilename();
3075*0b57cec5SDimitry Andric 
3076*0b57cec5SDimitry Andric     int PathComponentsToStrip =
3077*0b57cec5SDimitry Andric         CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
3078*0b57cec5SDimitry Andric     if (PathComponentsToStrip < 0) {
3079*0b57cec5SDimitry Andric       assert(PathComponentsToStrip != INT_MIN);
3080*0b57cec5SDimitry Andric       int PathComponentsToKeep = -PathComponentsToStrip;
3081*0b57cec5SDimitry Andric       auto I = llvm::sys::path::rbegin(FilenameString);
3082*0b57cec5SDimitry Andric       auto E = llvm::sys::path::rend(FilenameString);
3083*0b57cec5SDimitry Andric       while (I != E && --PathComponentsToKeep)
3084*0b57cec5SDimitry Andric         ++I;
3085*0b57cec5SDimitry Andric 
3086*0b57cec5SDimitry Andric       FilenameString = FilenameString.substr(I - E);
3087*0b57cec5SDimitry Andric     } else if (PathComponentsToStrip > 0) {
3088*0b57cec5SDimitry Andric       auto I = llvm::sys::path::begin(FilenameString);
3089*0b57cec5SDimitry Andric       auto E = llvm::sys::path::end(FilenameString);
3090*0b57cec5SDimitry Andric       while (I != E && PathComponentsToStrip--)
3091*0b57cec5SDimitry Andric         ++I;
3092*0b57cec5SDimitry Andric 
3093*0b57cec5SDimitry Andric       if (I != E)
3094*0b57cec5SDimitry Andric         FilenameString =
3095*0b57cec5SDimitry Andric             FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
3096*0b57cec5SDimitry Andric       else
3097*0b57cec5SDimitry Andric         FilenameString = llvm::sys::path::filename(FilenameString);
3098*0b57cec5SDimitry Andric     }
3099*0b57cec5SDimitry Andric 
31005ffd83dbSDimitry Andric     auto FilenameGV =
31015ffd83dbSDimitry Andric         CGM.GetAddrOfConstantCString(std::string(FilenameString), ".src");
3102*0b57cec5SDimitry Andric     CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
3103*0b57cec5SDimitry Andric                           cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
3104*0b57cec5SDimitry Andric     Filename = FilenameGV.getPointer();
3105*0b57cec5SDimitry Andric     Line = PLoc.getLine();
3106*0b57cec5SDimitry Andric     Column = PLoc.getColumn();
3107*0b57cec5SDimitry Andric   } else {
3108*0b57cec5SDimitry Andric     Filename = llvm::Constant::getNullValue(Int8PtrTy);
3109*0b57cec5SDimitry Andric     Line = Column = 0;
3110*0b57cec5SDimitry Andric   }
3111*0b57cec5SDimitry Andric 
3112*0b57cec5SDimitry Andric   llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
3113*0b57cec5SDimitry Andric                             Builder.getInt32(Column)};
3114*0b57cec5SDimitry Andric 
3115*0b57cec5SDimitry Andric   return llvm::ConstantStruct::getAnon(Data);
3116*0b57cec5SDimitry Andric }
3117*0b57cec5SDimitry Andric 
3118*0b57cec5SDimitry Andric namespace {
3119*0b57cec5SDimitry Andric /// Specify under what conditions this check can be recovered
3120*0b57cec5SDimitry Andric enum class CheckRecoverableKind {
3121*0b57cec5SDimitry Andric   /// Always terminate program execution if this check fails.
3122*0b57cec5SDimitry Andric   Unrecoverable,
3123*0b57cec5SDimitry Andric   /// Check supports recovering, runtime has both fatal (noreturn) and
3124*0b57cec5SDimitry Andric   /// non-fatal handlers for this check.
3125*0b57cec5SDimitry Andric   Recoverable,
3126*0b57cec5SDimitry Andric   /// Runtime conditionally aborts, always need to support recovery.
3127*0b57cec5SDimitry Andric   AlwaysRecoverable
3128*0b57cec5SDimitry Andric };
3129*0b57cec5SDimitry Andric }
3130*0b57cec5SDimitry Andric 
3131*0b57cec5SDimitry Andric static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
3132*0b57cec5SDimitry Andric   assert(Kind.countPopulation() == 1);
3133*0b57cec5SDimitry Andric   if (Kind == SanitizerKind::Function || Kind == SanitizerKind::Vptr)
3134*0b57cec5SDimitry Andric     return CheckRecoverableKind::AlwaysRecoverable;
3135*0b57cec5SDimitry Andric   else if (Kind == SanitizerKind::Return || Kind == SanitizerKind::Unreachable)
3136*0b57cec5SDimitry Andric     return CheckRecoverableKind::Unrecoverable;
3137*0b57cec5SDimitry Andric   else
3138*0b57cec5SDimitry Andric     return CheckRecoverableKind::Recoverable;
3139*0b57cec5SDimitry Andric }
3140*0b57cec5SDimitry Andric 
3141*0b57cec5SDimitry Andric namespace {
3142*0b57cec5SDimitry Andric struct SanitizerHandlerInfo {
3143*0b57cec5SDimitry Andric   char const *const Name;
3144*0b57cec5SDimitry Andric   unsigned Version;
3145*0b57cec5SDimitry Andric };
3146*0b57cec5SDimitry Andric }
3147*0b57cec5SDimitry Andric 
3148*0b57cec5SDimitry Andric const SanitizerHandlerInfo SanitizerHandlers[] = {
3149*0b57cec5SDimitry Andric #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
3150*0b57cec5SDimitry Andric     LIST_SANITIZER_CHECKS
3151*0b57cec5SDimitry Andric #undef SANITIZER_CHECK
3152*0b57cec5SDimitry Andric };
3153*0b57cec5SDimitry Andric 
3154*0b57cec5SDimitry Andric static void emitCheckHandlerCall(CodeGenFunction &CGF,
3155*0b57cec5SDimitry Andric                                  llvm::FunctionType *FnType,
3156*0b57cec5SDimitry Andric                                  ArrayRef<llvm::Value *> FnArgs,
3157*0b57cec5SDimitry Andric                                  SanitizerHandler CheckHandler,
3158*0b57cec5SDimitry Andric                                  CheckRecoverableKind RecoverKind, bool IsFatal,
3159*0b57cec5SDimitry Andric                                  llvm::BasicBlock *ContBB) {
3160*0b57cec5SDimitry Andric   assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
3161*0b57cec5SDimitry Andric   Optional<ApplyDebugLocation> DL;
3162*0b57cec5SDimitry Andric   if (!CGF.Builder.getCurrentDebugLocation()) {
3163*0b57cec5SDimitry Andric     // Ensure that the call has at least an artificial debug location.
3164*0b57cec5SDimitry Andric     DL.emplace(CGF, SourceLocation());
3165*0b57cec5SDimitry Andric   }
3166*0b57cec5SDimitry Andric   bool NeedsAbortSuffix =
3167*0b57cec5SDimitry Andric       IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
3168*0b57cec5SDimitry Andric   bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
3169*0b57cec5SDimitry Andric   const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
3170*0b57cec5SDimitry Andric   const StringRef CheckName = CheckInfo.Name;
3171*0b57cec5SDimitry Andric   std::string FnName = "__ubsan_handle_" + CheckName.str();
3172*0b57cec5SDimitry Andric   if (CheckInfo.Version && !MinimalRuntime)
3173*0b57cec5SDimitry Andric     FnName += "_v" + llvm::utostr(CheckInfo.Version);
3174*0b57cec5SDimitry Andric   if (MinimalRuntime)
3175*0b57cec5SDimitry Andric     FnName += "_minimal";
3176*0b57cec5SDimitry Andric   if (NeedsAbortSuffix)
3177*0b57cec5SDimitry Andric     FnName += "_abort";
3178*0b57cec5SDimitry Andric   bool MayReturn =
3179*0b57cec5SDimitry Andric       !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
3180*0b57cec5SDimitry Andric 
3181*0b57cec5SDimitry Andric   llvm::AttrBuilder B;
3182*0b57cec5SDimitry Andric   if (!MayReturn) {
3183*0b57cec5SDimitry Andric     B.addAttribute(llvm::Attribute::NoReturn)
3184*0b57cec5SDimitry Andric         .addAttribute(llvm::Attribute::NoUnwind);
3185*0b57cec5SDimitry Andric   }
3186*0b57cec5SDimitry Andric   B.addAttribute(llvm::Attribute::UWTable);
3187*0b57cec5SDimitry Andric 
3188*0b57cec5SDimitry Andric   llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(
3189*0b57cec5SDimitry Andric       FnType, FnName,
3190*0b57cec5SDimitry Andric       llvm::AttributeList::get(CGF.getLLVMContext(),
3191*0b57cec5SDimitry Andric                                llvm::AttributeList::FunctionIndex, B),
3192*0b57cec5SDimitry Andric       /*Local=*/true);
3193*0b57cec5SDimitry Andric   llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
3194*0b57cec5SDimitry Andric   if (!MayReturn) {
3195*0b57cec5SDimitry Andric     HandlerCall->setDoesNotReturn();
3196*0b57cec5SDimitry Andric     CGF.Builder.CreateUnreachable();
3197*0b57cec5SDimitry Andric   } else {
3198*0b57cec5SDimitry Andric     CGF.Builder.CreateBr(ContBB);
3199*0b57cec5SDimitry Andric   }
3200*0b57cec5SDimitry Andric }
3201*0b57cec5SDimitry Andric 
3202*0b57cec5SDimitry Andric void CodeGenFunction::EmitCheck(
3203*0b57cec5SDimitry Andric     ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
3204*0b57cec5SDimitry Andric     SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
3205*0b57cec5SDimitry Andric     ArrayRef<llvm::Value *> DynamicArgs) {
3206*0b57cec5SDimitry Andric   assert(IsSanitizerScope);
3207*0b57cec5SDimitry Andric   assert(Checked.size() > 0);
3208*0b57cec5SDimitry Andric   assert(CheckHandler >= 0 &&
3209*0b57cec5SDimitry Andric          size_t(CheckHandler) < llvm::array_lengthof(SanitizerHandlers));
3210*0b57cec5SDimitry Andric   const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
3211*0b57cec5SDimitry Andric 
3212*0b57cec5SDimitry Andric   llvm::Value *FatalCond = nullptr;
3213*0b57cec5SDimitry Andric   llvm::Value *RecoverableCond = nullptr;
3214*0b57cec5SDimitry Andric   llvm::Value *TrapCond = nullptr;
3215*0b57cec5SDimitry Andric   for (int i = 0, n = Checked.size(); i < n; ++i) {
3216*0b57cec5SDimitry Andric     llvm::Value *Check = Checked[i].first;
3217*0b57cec5SDimitry Andric     // -fsanitize-trap= overrides -fsanitize-recover=.
3218*0b57cec5SDimitry Andric     llvm::Value *&Cond =
3219*0b57cec5SDimitry Andric         CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
3220*0b57cec5SDimitry Andric             ? TrapCond
3221*0b57cec5SDimitry Andric             : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
3222*0b57cec5SDimitry Andric                   ? RecoverableCond
3223*0b57cec5SDimitry Andric                   : FatalCond;
3224*0b57cec5SDimitry Andric     Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
3225*0b57cec5SDimitry Andric   }
3226*0b57cec5SDimitry Andric 
3227*0b57cec5SDimitry Andric   if (TrapCond)
3228e8d8bef9SDimitry Andric     EmitTrapCheck(TrapCond, CheckHandler);
3229*0b57cec5SDimitry Andric   if (!FatalCond && !RecoverableCond)
3230*0b57cec5SDimitry Andric     return;
3231*0b57cec5SDimitry Andric 
3232*0b57cec5SDimitry Andric   llvm::Value *JointCond;
3233*0b57cec5SDimitry Andric   if (FatalCond && RecoverableCond)
3234*0b57cec5SDimitry Andric     JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
3235*0b57cec5SDimitry Andric   else
3236*0b57cec5SDimitry Andric     JointCond = FatalCond ? FatalCond : RecoverableCond;
3237*0b57cec5SDimitry Andric   assert(JointCond);
3238*0b57cec5SDimitry Andric 
3239*0b57cec5SDimitry Andric   CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
3240*0b57cec5SDimitry Andric   assert(SanOpts.has(Checked[0].second));
3241*0b57cec5SDimitry Andric #ifndef NDEBUG
3242*0b57cec5SDimitry Andric   for (int i = 1, n = Checked.size(); i < n; ++i) {
3243*0b57cec5SDimitry Andric     assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
3244*0b57cec5SDimitry Andric            "All recoverable kinds in a single check must be same!");
3245*0b57cec5SDimitry Andric     assert(SanOpts.has(Checked[i].second));
3246*0b57cec5SDimitry Andric   }
3247*0b57cec5SDimitry Andric #endif
3248*0b57cec5SDimitry Andric 
3249*0b57cec5SDimitry Andric   llvm::BasicBlock *Cont = createBasicBlock("cont");
3250*0b57cec5SDimitry Andric   llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
3251*0b57cec5SDimitry Andric   llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
3252*0b57cec5SDimitry Andric   // Give hint that we very much don't expect to execute the handler
3253*0b57cec5SDimitry Andric   // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
3254*0b57cec5SDimitry Andric   llvm::MDBuilder MDHelper(getLLVMContext());
3255*0b57cec5SDimitry Andric   llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
3256*0b57cec5SDimitry Andric   Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
3257*0b57cec5SDimitry Andric   EmitBlock(Handlers);
3258*0b57cec5SDimitry Andric 
3259*0b57cec5SDimitry Andric   // Handler functions take an i8* pointing to the (handler-specific) static
3260*0b57cec5SDimitry Andric   // information block, followed by a sequence of intptr_t arguments
3261*0b57cec5SDimitry Andric   // representing operand values.
3262*0b57cec5SDimitry Andric   SmallVector<llvm::Value *, 4> Args;
3263*0b57cec5SDimitry Andric   SmallVector<llvm::Type *, 4> ArgTypes;
3264*0b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
3265*0b57cec5SDimitry Andric     Args.reserve(DynamicArgs.size() + 1);
3266*0b57cec5SDimitry Andric     ArgTypes.reserve(DynamicArgs.size() + 1);
3267*0b57cec5SDimitry Andric 
3268*0b57cec5SDimitry Andric     // Emit handler arguments and create handler function type.
3269*0b57cec5SDimitry Andric     if (!StaticArgs.empty()) {
3270*0b57cec5SDimitry Andric       llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
3271*0b57cec5SDimitry Andric       auto *InfoPtr =
3272*0b57cec5SDimitry Andric           new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
3273*0b57cec5SDimitry Andric                                    llvm::GlobalVariable::PrivateLinkage, Info);
3274*0b57cec5SDimitry Andric       InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3275*0b57cec5SDimitry Andric       CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
3276*0b57cec5SDimitry Andric       Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
3277*0b57cec5SDimitry Andric       ArgTypes.push_back(Int8PtrTy);
3278*0b57cec5SDimitry Andric     }
3279*0b57cec5SDimitry Andric 
3280*0b57cec5SDimitry Andric     for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
3281*0b57cec5SDimitry Andric       Args.push_back(EmitCheckValue(DynamicArgs[i]));
3282*0b57cec5SDimitry Andric       ArgTypes.push_back(IntPtrTy);
3283*0b57cec5SDimitry Andric     }
3284*0b57cec5SDimitry Andric   }
3285*0b57cec5SDimitry Andric 
3286*0b57cec5SDimitry Andric   llvm::FunctionType *FnType =
3287*0b57cec5SDimitry Andric     llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
3288*0b57cec5SDimitry Andric 
3289*0b57cec5SDimitry Andric   if (!FatalCond || !RecoverableCond) {
3290*0b57cec5SDimitry Andric     // Simple case: we need to generate a single handler call, either
3291*0b57cec5SDimitry Andric     // fatal, or non-fatal.
3292*0b57cec5SDimitry Andric     emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
3293*0b57cec5SDimitry Andric                          (FatalCond != nullptr), Cont);
3294*0b57cec5SDimitry Andric   } else {
3295*0b57cec5SDimitry Andric     // Emit two handler calls: first one for set of unrecoverable checks,
3296*0b57cec5SDimitry Andric     // another one for recoverable.
3297*0b57cec5SDimitry Andric     llvm::BasicBlock *NonFatalHandlerBB =
3298*0b57cec5SDimitry Andric         createBasicBlock("non_fatal." + CheckName);
3299*0b57cec5SDimitry Andric     llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
3300*0b57cec5SDimitry Andric     Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
3301*0b57cec5SDimitry Andric     EmitBlock(FatalHandlerBB);
3302*0b57cec5SDimitry Andric     emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
3303*0b57cec5SDimitry Andric                          NonFatalHandlerBB);
3304*0b57cec5SDimitry Andric     EmitBlock(NonFatalHandlerBB);
3305*0b57cec5SDimitry Andric     emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
3306*0b57cec5SDimitry Andric                          Cont);
3307*0b57cec5SDimitry Andric   }
3308*0b57cec5SDimitry Andric 
3309*0b57cec5SDimitry Andric   EmitBlock(Cont);
3310*0b57cec5SDimitry Andric }
3311*0b57cec5SDimitry Andric 
3312*0b57cec5SDimitry Andric void CodeGenFunction::EmitCfiSlowPathCheck(
3313*0b57cec5SDimitry Andric     SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
3314*0b57cec5SDimitry Andric     llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
3315*0b57cec5SDimitry Andric   llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
3316*0b57cec5SDimitry Andric 
3317*0b57cec5SDimitry Andric   llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
3318*0b57cec5SDimitry Andric   llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
3319*0b57cec5SDimitry Andric 
3320*0b57cec5SDimitry Andric   llvm::MDBuilder MDHelper(getLLVMContext());
3321*0b57cec5SDimitry Andric   llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
3322*0b57cec5SDimitry Andric   BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
3323*0b57cec5SDimitry Andric 
3324*0b57cec5SDimitry Andric   EmitBlock(CheckBB);
3325*0b57cec5SDimitry Andric 
3326*0b57cec5SDimitry Andric   bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
3327*0b57cec5SDimitry Andric 
3328*0b57cec5SDimitry Andric   llvm::CallInst *CheckCall;
3329*0b57cec5SDimitry Andric   llvm::FunctionCallee SlowPathFn;
3330*0b57cec5SDimitry Andric   if (WithDiag) {
3331*0b57cec5SDimitry Andric     llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
3332*0b57cec5SDimitry Andric     auto *InfoPtr =
3333*0b57cec5SDimitry Andric         new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
3334*0b57cec5SDimitry Andric                                  llvm::GlobalVariable::PrivateLinkage, Info);
3335*0b57cec5SDimitry Andric     InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3336*0b57cec5SDimitry Andric     CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
3337*0b57cec5SDimitry Andric 
3338*0b57cec5SDimitry Andric     SlowPathFn = CGM.getModule().getOrInsertFunction(
3339*0b57cec5SDimitry Andric         "__cfi_slowpath_diag",
3340*0b57cec5SDimitry Andric         llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
3341*0b57cec5SDimitry Andric                                 false));
3342*0b57cec5SDimitry Andric     CheckCall = Builder.CreateCall(
3343*0b57cec5SDimitry Andric         SlowPathFn, {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
3344*0b57cec5SDimitry Andric   } else {
3345*0b57cec5SDimitry Andric     SlowPathFn = CGM.getModule().getOrInsertFunction(
3346*0b57cec5SDimitry Andric         "__cfi_slowpath",
3347*0b57cec5SDimitry Andric         llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
3348*0b57cec5SDimitry Andric     CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
3349*0b57cec5SDimitry Andric   }
3350*0b57cec5SDimitry Andric 
3351*0b57cec5SDimitry Andric   CGM.setDSOLocal(
3352*0b57cec5SDimitry Andric       cast<llvm::GlobalValue>(SlowPathFn.getCallee()->stripPointerCasts()));
3353*0b57cec5SDimitry Andric   CheckCall->setDoesNotThrow();
3354*0b57cec5SDimitry Andric 
3355*0b57cec5SDimitry Andric   EmitBlock(Cont);
3356*0b57cec5SDimitry Andric }
3357*0b57cec5SDimitry Andric 
3358*0b57cec5SDimitry Andric // Emit a stub for __cfi_check function so that the linker knows about this
3359*0b57cec5SDimitry Andric // symbol in LTO mode.
3360*0b57cec5SDimitry Andric void CodeGenFunction::EmitCfiCheckStub() {
3361*0b57cec5SDimitry Andric   llvm::Module *M = &CGM.getModule();
3362*0b57cec5SDimitry Andric   auto &Ctx = M->getContext();
3363*0b57cec5SDimitry Andric   llvm::Function *F = llvm::Function::Create(
3364*0b57cec5SDimitry Andric       llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
3365*0b57cec5SDimitry Andric       llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
3366*0b57cec5SDimitry Andric   CGM.setDSOLocal(F);
3367*0b57cec5SDimitry Andric   llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
3368*0b57cec5SDimitry Andric   // FIXME: consider emitting an intrinsic call like
3369*0b57cec5SDimitry Andric   // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
3370*0b57cec5SDimitry Andric   // which can be lowered in CrossDSOCFI pass to the actual contents of
3371*0b57cec5SDimitry Andric   // __cfi_check. This would allow inlining of __cfi_check calls.
3372*0b57cec5SDimitry Andric   llvm::CallInst::Create(
3373*0b57cec5SDimitry Andric       llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
3374*0b57cec5SDimitry Andric   llvm::ReturnInst::Create(Ctx, nullptr, BB);
3375*0b57cec5SDimitry Andric }
3376*0b57cec5SDimitry Andric 
3377*0b57cec5SDimitry Andric // This function is basically a switch over the CFI failure kind, which is
3378*0b57cec5SDimitry Andric // extracted from CFICheckFailData (1st function argument). Each case is either
3379*0b57cec5SDimitry Andric // llvm.trap or a call to one of the two runtime handlers, based on
3380*0b57cec5SDimitry Andric // -fsanitize-trap and -fsanitize-recover settings.  Default case (invalid
3381*0b57cec5SDimitry Andric // failure kind) traps, but this should really never happen.  CFICheckFailData
3382*0b57cec5SDimitry Andric // can be nullptr if the calling module has -fsanitize-trap behavior for this
3383*0b57cec5SDimitry Andric // check kind; in this case __cfi_check_fail traps as well.
3384*0b57cec5SDimitry Andric void CodeGenFunction::EmitCfiCheckFail() {
3385*0b57cec5SDimitry Andric   SanitizerScope SanScope(this);
3386*0b57cec5SDimitry Andric   FunctionArgList Args;
3387*0b57cec5SDimitry Andric   ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
3388*0b57cec5SDimitry Andric                             ImplicitParamDecl::Other);
3389*0b57cec5SDimitry Andric   ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
3390*0b57cec5SDimitry Andric                             ImplicitParamDecl::Other);
3391*0b57cec5SDimitry Andric   Args.push_back(&ArgData);
3392*0b57cec5SDimitry Andric   Args.push_back(&ArgAddr);
3393*0b57cec5SDimitry Andric 
3394*0b57cec5SDimitry Andric   const CGFunctionInfo &FI =
3395*0b57cec5SDimitry Andric     CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
3396*0b57cec5SDimitry Andric 
3397*0b57cec5SDimitry Andric   llvm::Function *F = llvm::Function::Create(
3398*0b57cec5SDimitry Andric       llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
3399*0b57cec5SDimitry Andric       llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
3400480093f4SDimitry Andric 
3401fe6060f1SDimitry Andric   CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
3402480093f4SDimitry Andric   CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
3403*0b57cec5SDimitry Andric   F->setVisibility(llvm::GlobalValue::HiddenVisibility);
3404*0b57cec5SDimitry Andric 
3405*0b57cec5SDimitry Andric   StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
3406*0b57cec5SDimitry Andric                 SourceLocation());
3407*0b57cec5SDimitry Andric 
3408fe6060f1SDimitry Andric   // This function is not affected by NoSanitizeList. This function does
3409*0b57cec5SDimitry Andric   // not have a source location, but "src:*" would still apply. Revert any
3410*0b57cec5SDimitry Andric   // changes to SanOpts made in StartFunction.
3411*0b57cec5SDimitry Andric   SanOpts = CGM.getLangOpts().Sanitize;
3412*0b57cec5SDimitry Andric 
3413*0b57cec5SDimitry Andric   llvm::Value *Data =
3414*0b57cec5SDimitry Andric       EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
3415*0b57cec5SDimitry Andric                        CGM.getContext().VoidPtrTy, ArgData.getLocation());
3416*0b57cec5SDimitry Andric   llvm::Value *Addr =
3417*0b57cec5SDimitry Andric       EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
3418*0b57cec5SDimitry Andric                        CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
3419*0b57cec5SDimitry Andric 
3420*0b57cec5SDimitry Andric   // Data == nullptr means the calling module has trap behaviour for this check.
3421*0b57cec5SDimitry Andric   llvm::Value *DataIsNotNullPtr =
3422*0b57cec5SDimitry Andric       Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
3423e8d8bef9SDimitry Andric   EmitTrapCheck(DataIsNotNullPtr, SanitizerHandler::CFICheckFail);
3424*0b57cec5SDimitry Andric 
3425*0b57cec5SDimitry Andric   llvm::StructType *SourceLocationTy =
3426*0b57cec5SDimitry Andric       llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
3427*0b57cec5SDimitry Andric   llvm::StructType *CfiCheckFailDataTy =
3428*0b57cec5SDimitry Andric       llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
3429*0b57cec5SDimitry Andric 
3430*0b57cec5SDimitry Andric   llvm::Value *V = Builder.CreateConstGEP2_32(
3431*0b57cec5SDimitry Andric       CfiCheckFailDataTy,
3432*0b57cec5SDimitry Andric       Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
3433*0b57cec5SDimitry Andric       0);
3434*0b57cec5SDimitry Andric   Address CheckKindAddr(V, getIntAlign());
3435*0b57cec5SDimitry Andric   llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
3436*0b57cec5SDimitry Andric 
3437*0b57cec5SDimitry Andric   llvm::Value *AllVtables = llvm::MetadataAsValue::get(
3438*0b57cec5SDimitry Andric       CGM.getLLVMContext(),
3439*0b57cec5SDimitry Andric       llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
3440*0b57cec5SDimitry Andric   llvm::Value *ValidVtable = Builder.CreateZExt(
3441*0b57cec5SDimitry Andric       Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
3442*0b57cec5SDimitry Andric                          {Addr, AllVtables}),
3443*0b57cec5SDimitry Andric       IntPtrTy);
3444*0b57cec5SDimitry Andric 
3445*0b57cec5SDimitry Andric   const std::pair<int, SanitizerMask> CheckKinds[] = {
3446*0b57cec5SDimitry Andric       {CFITCK_VCall, SanitizerKind::CFIVCall},
3447*0b57cec5SDimitry Andric       {CFITCK_NVCall, SanitizerKind::CFINVCall},
3448*0b57cec5SDimitry Andric       {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
3449*0b57cec5SDimitry Andric       {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
3450*0b57cec5SDimitry Andric       {CFITCK_ICall, SanitizerKind::CFIICall}};
3451*0b57cec5SDimitry Andric 
3452*0b57cec5SDimitry Andric   SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
3453*0b57cec5SDimitry Andric   for (auto CheckKindMaskPair : CheckKinds) {
3454*0b57cec5SDimitry Andric     int Kind = CheckKindMaskPair.first;
3455*0b57cec5SDimitry Andric     SanitizerMask Mask = CheckKindMaskPair.second;
3456*0b57cec5SDimitry Andric     llvm::Value *Cond =
3457*0b57cec5SDimitry Andric         Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
3458*0b57cec5SDimitry Andric     if (CGM.getLangOpts().Sanitize.has(Mask))
3459*0b57cec5SDimitry Andric       EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
3460*0b57cec5SDimitry Andric                 {Data, Addr, ValidVtable});
3461*0b57cec5SDimitry Andric     else
3462e8d8bef9SDimitry Andric       EmitTrapCheck(Cond, SanitizerHandler::CFICheckFail);
3463*0b57cec5SDimitry Andric   }
3464*0b57cec5SDimitry Andric 
3465*0b57cec5SDimitry Andric   FinishFunction();
3466*0b57cec5SDimitry Andric   // The only reference to this function will be created during LTO link.
3467*0b57cec5SDimitry Andric   // Make sure it survives until then.
3468*0b57cec5SDimitry Andric   CGM.addUsedGlobal(F);
3469*0b57cec5SDimitry Andric }
3470*0b57cec5SDimitry Andric 
3471*0b57cec5SDimitry Andric void CodeGenFunction::EmitUnreachable(SourceLocation Loc) {
3472*0b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::Unreachable)) {
3473*0b57cec5SDimitry Andric     SanitizerScope SanScope(this);
3474*0b57cec5SDimitry Andric     EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()),
3475*0b57cec5SDimitry Andric                              SanitizerKind::Unreachable),
3476*0b57cec5SDimitry Andric               SanitizerHandler::BuiltinUnreachable,
3477*0b57cec5SDimitry Andric               EmitCheckSourceLocation(Loc), None);
3478*0b57cec5SDimitry Andric   }
3479*0b57cec5SDimitry Andric   Builder.CreateUnreachable();
3480*0b57cec5SDimitry Andric }
3481*0b57cec5SDimitry Andric 
3482e8d8bef9SDimitry Andric void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked,
3483e8d8bef9SDimitry Andric                                     SanitizerHandler CheckHandlerID) {
3484*0b57cec5SDimitry Andric   llvm::BasicBlock *Cont = createBasicBlock("cont");
3485*0b57cec5SDimitry Andric 
3486*0b57cec5SDimitry Andric   // If we're optimizing, collapse all calls to trap down to just one per
3487e8d8bef9SDimitry Andric   // check-type per function to save on code size.
3488e8d8bef9SDimitry Andric   if (TrapBBs.size() <= CheckHandlerID)
3489e8d8bef9SDimitry Andric     TrapBBs.resize(CheckHandlerID + 1);
3490e8d8bef9SDimitry Andric   llvm::BasicBlock *&TrapBB = TrapBBs[CheckHandlerID];
3491e8d8bef9SDimitry Andric 
3492*0b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
3493*0b57cec5SDimitry Andric     TrapBB = createBasicBlock("trap");
3494*0b57cec5SDimitry Andric     Builder.CreateCondBr(Checked, Cont, TrapBB);
3495*0b57cec5SDimitry Andric     EmitBlock(TrapBB);
3496e8d8bef9SDimitry Andric 
3497e8d8bef9SDimitry Andric     llvm::CallInst *TrapCall =
3498e8d8bef9SDimitry Andric         Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::ubsantrap),
3499e8d8bef9SDimitry Andric                            llvm::ConstantInt::get(CGM.Int8Ty, CheckHandlerID));
3500e8d8bef9SDimitry Andric 
3501e8d8bef9SDimitry Andric     if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3502e8d8bef9SDimitry Andric       auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3503e8d8bef9SDimitry Andric                                     CGM.getCodeGenOpts().TrapFuncName);
3504349cc55cSDimitry Andric       TrapCall->addFnAttr(A);
3505e8d8bef9SDimitry Andric     }
3506*0b57cec5SDimitry Andric     TrapCall->setDoesNotReturn();
3507*0b57cec5SDimitry Andric     TrapCall->setDoesNotThrow();
3508*0b57cec5SDimitry Andric     Builder.CreateUnreachable();
3509*0b57cec5SDimitry Andric   } else {
3510e8d8bef9SDimitry Andric     auto Call = TrapBB->begin();
3511e8d8bef9SDimitry Andric     assert(isa<llvm::CallInst>(Call) && "Expected call in trap BB");
3512e8d8bef9SDimitry Andric 
3513e8d8bef9SDimitry Andric     Call->applyMergedLocation(Call->getDebugLoc(),
3514e8d8bef9SDimitry Andric                               Builder.getCurrentDebugLocation());
3515*0b57cec5SDimitry Andric     Builder.CreateCondBr(Checked, Cont, TrapBB);
3516*0b57cec5SDimitry Andric   }
3517*0b57cec5SDimitry Andric 
3518*0b57cec5SDimitry Andric   EmitBlock(Cont);
3519*0b57cec5SDimitry Andric }
3520*0b57cec5SDimitry Andric 
3521*0b57cec5SDimitry Andric llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
3522e8d8bef9SDimitry Andric   llvm::CallInst *TrapCall =
3523e8d8bef9SDimitry Andric       Builder.CreateCall(CGM.getIntrinsic(IntrID));
3524*0b57cec5SDimitry Andric 
3525*0b57cec5SDimitry Andric   if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3526*0b57cec5SDimitry Andric     auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3527*0b57cec5SDimitry Andric                                   CGM.getCodeGenOpts().TrapFuncName);
3528349cc55cSDimitry Andric     TrapCall->addFnAttr(A);
3529*0b57cec5SDimitry Andric   }
3530*0b57cec5SDimitry Andric 
3531*0b57cec5SDimitry Andric   return TrapCall;
3532*0b57cec5SDimitry Andric }
3533*0b57cec5SDimitry Andric 
3534*0b57cec5SDimitry Andric Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
3535*0b57cec5SDimitry Andric                                                  LValueBaseInfo *BaseInfo,
3536*0b57cec5SDimitry Andric                                                  TBAAAccessInfo *TBAAInfo) {
3537*0b57cec5SDimitry Andric   assert(E->getType()->isArrayType() &&
3538*0b57cec5SDimitry Andric          "Array to pointer decay must have array source type!");
3539*0b57cec5SDimitry Andric 
3540*0b57cec5SDimitry Andric   // Expressions of array type can't be bitfields or vector elements.
3541*0b57cec5SDimitry Andric   LValue LV = EmitLValue(E);
3542480093f4SDimitry Andric   Address Addr = LV.getAddress(*this);
3543*0b57cec5SDimitry Andric 
3544*0b57cec5SDimitry Andric   // If the array type was an incomplete type, we need to make sure
3545*0b57cec5SDimitry Andric   // the decay ends up being the right type.
3546*0b57cec5SDimitry Andric   llvm::Type *NewTy = ConvertType(E->getType());
3547*0b57cec5SDimitry Andric   Addr = Builder.CreateElementBitCast(Addr, NewTy);
3548*0b57cec5SDimitry Andric 
3549*0b57cec5SDimitry Andric   // Note that VLA pointers are always decayed, so we don't need to do
3550*0b57cec5SDimitry Andric   // anything here.
3551*0b57cec5SDimitry Andric   if (!E->getType()->isVariableArrayType()) {
3552*0b57cec5SDimitry Andric     assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3553*0b57cec5SDimitry Andric            "Expected pointer to array");
3554*0b57cec5SDimitry Andric     Addr = Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
3555*0b57cec5SDimitry Andric   }
3556*0b57cec5SDimitry Andric 
3557*0b57cec5SDimitry Andric   // The result of this decay conversion points to an array element within the
3558*0b57cec5SDimitry Andric   // base lvalue. However, since TBAA currently does not support representing
3559*0b57cec5SDimitry Andric   // accesses to elements of member arrays, we conservatively represent accesses
3560*0b57cec5SDimitry Andric   // to the pointee object as if it had no any base lvalue specified.
3561*0b57cec5SDimitry Andric   // TODO: Support TBAA for member arrays.
3562*0b57cec5SDimitry Andric   QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
3563*0b57cec5SDimitry Andric   if (BaseInfo) *BaseInfo = LV.getBaseInfo();
3564*0b57cec5SDimitry Andric   if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
3565*0b57cec5SDimitry Andric 
3566*0b57cec5SDimitry Andric   return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
3567*0b57cec5SDimitry Andric }
3568*0b57cec5SDimitry Andric 
3569*0b57cec5SDimitry Andric /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
3570*0b57cec5SDimitry Andric /// array to pointer, return the array subexpression.
3571*0b57cec5SDimitry Andric static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
3572*0b57cec5SDimitry Andric   // If this isn't just an array->pointer decay, bail out.
3573*0b57cec5SDimitry Andric   const auto *CE = dyn_cast<CastExpr>(E);
3574*0b57cec5SDimitry Andric   if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
3575*0b57cec5SDimitry Andric     return nullptr;
3576*0b57cec5SDimitry Andric 
3577*0b57cec5SDimitry Andric   // If this is a decay from variable width array, bail out.
3578*0b57cec5SDimitry Andric   const Expr *SubExpr = CE->getSubExpr();
3579*0b57cec5SDimitry Andric   if (SubExpr->getType()->isVariableArrayType())
3580*0b57cec5SDimitry Andric     return nullptr;
3581*0b57cec5SDimitry Andric 
3582*0b57cec5SDimitry Andric   return SubExpr;
3583*0b57cec5SDimitry Andric }
3584*0b57cec5SDimitry Andric 
3585*0b57cec5SDimitry Andric static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3586fe6060f1SDimitry Andric                                           llvm::Type *elemType,
3587*0b57cec5SDimitry Andric                                           llvm::Value *ptr,
3588*0b57cec5SDimitry Andric                                           ArrayRef<llvm::Value*> indices,
3589*0b57cec5SDimitry Andric                                           bool inbounds,
3590*0b57cec5SDimitry Andric                                           bool signedIndices,
3591*0b57cec5SDimitry Andric                                           SourceLocation loc,
3592*0b57cec5SDimitry Andric                                     const llvm::Twine &name = "arrayidx") {
3593*0b57cec5SDimitry Andric   if (inbounds) {
35940eae32dcSDimitry Andric     return CGF.EmitCheckedInBoundsGEP(elemType, ptr, indices, signedIndices,
3595*0b57cec5SDimitry Andric                                       CodeGenFunction::NotSubtraction, loc,
3596*0b57cec5SDimitry Andric                                       name);
3597*0b57cec5SDimitry Andric   } else {
3598fe6060f1SDimitry Andric     return CGF.Builder.CreateGEP(elemType, ptr, indices, name);
3599*0b57cec5SDimitry Andric   }
3600*0b57cec5SDimitry Andric }
3601*0b57cec5SDimitry Andric 
3602*0b57cec5SDimitry Andric static CharUnits getArrayElementAlign(CharUnits arrayAlign,
3603*0b57cec5SDimitry Andric                                       llvm::Value *idx,
3604*0b57cec5SDimitry Andric                                       CharUnits eltSize) {
3605*0b57cec5SDimitry Andric   // If we have a constant index, we can use the exact offset of the
3606*0b57cec5SDimitry Andric   // element we're accessing.
3607*0b57cec5SDimitry Andric   if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3608*0b57cec5SDimitry Andric     CharUnits offset = constantIdx->getZExtValue() * eltSize;
3609*0b57cec5SDimitry Andric     return arrayAlign.alignmentAtOffset(offset);
3610*0b57cec5SDimitry Andric 
3611*0b57cec5SDimitry Andric   // Otherwise, use the worst-case alignment for any element.
3612*0b57cec5SDimitry Andric   } else {
3613*0b57cec5SDimitry Andric     return arrayAlign.alignmentOfArrayElement(eltSize);
3614*0b57cec5SDimitry Andric   }
3615*0b57cec5SDimitry Andric }
3616*0b57cec5SDimitry Andric 
3617*0b57cec5SDimitry Andric static QualType getFixedSizeElementType(const ASTContext &ctx,
3618*0b57cec5SDimitry Andric                                         const VariableArrayType *vla) {
3619*0b57cec5SDimitry Andric   QualType eltType;
3620*0b57cec5SDimitry Andric   do {
3621*0b57cec5SDimitry Andric     eltType = vla->getElementType();
3622*0b57cec5SDimitry Andric   } while ((vla = ctx.getAsVariableArrayType(eltType)));
3623*0b57cec5SDimitry Andric   return eltType;
3624*0b57cec5SDimitry Andric }
3625*0b57cec5SDimitry Andric 
3626480093f4SDimitry Andric /// Given an array base, check whether its member access belongs to a record
3627480093f4SDimitry Andric /// with preserve_access_index attribute or not.
3628480093f4SDimitry Andric static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase) {
3629480093f4SDimitry Andric   if (!ArrayBase || !CGF.getDebugInfo())
3630480093f4SDimitry Andric     return false;
3631480093f4SDimitry Andric 
3632480093f4SDimitry Andric   // Only support base as either a MemberExpr or DeclRefExpr.
3633480093f4SDimitry Andric   // DeclRefExpr to cover cases like:
3634480093f4SDimitry Andric   //    struct s { int a; int b[10]; };
3635480093f4SDimitry Andric   //    struct s *p;
3636480093f4SDimitry Andric   //    p[1].a
3637480093f4SDimitry Andric   // p[1] will generate a DeclRefExpr and p[1].a is a MemberExpr.
3638480093f4SDimitry Andric   // p->b[5] is a MemberExpr example.
3639480093f4SDimitry Andric   const Expr *E = ArrayBase->IgnoreImpCasts();
3640480093f4SDimitry Andric   if (const auto *ME = dyn_cast<MemberExpr>(E))
3641480093f4SDimitry Andric     return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
3642480093f4SDimitry Andric 
3643480093f4SDimitry Andric   if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3644480093f4SDimitry Andric     const auto *VarDef = dyn_cast<VarDecl>(DRE->getDecl());
3645480093f4SDimitry Andric     if (!VarDef)
3646480093f4SDimitry Andric       return false;
3647480093f4SDimitry Andric 
3648480093f4SDimitry Andric     const auto *PtrT = VarDef->getType()->getAs<PointerType>();
3649480093f4SDimitry Andric     if (!PtrT)
3650480093f4SDimitry Andric       return false;
3651480093f4SDimitry Andric 
3652480093f4SDimitry Andric     const auto *PointeeT = PtrT->getPointeeType()
3653480093f4SDimitry Andric                              ->getUnqualifiedDesugaredType();
3654480093f4SDimitry Andric     if (const auto *RecT = dyn_cast<RecordType>(PointeeT))
3655480093f4SDimitry Andric       return RecT->getDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
3656480093f4SDimitry Andric     return false;
3657480093f4SDimitry Andric   }
3658480093f4SDimitry Andric 
3659480093f4SDimitry Andric   return false;
3660480093f4SDimitry Andric }
3661480093f4SDimitry Andric 
3662*0b57cec5SDimitry Andric static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
3663*0b57cec5SDimitry Andric                                      ArrayRef<llvm::Value *> indices,
3664*0b57cec5SDimitry Andric                                      QualType eltType, bool inbounds,
3665*0b57cec5SDimitry Andric                                      bool signedIndices, SourceLocation loc,
3666a7dea167SDimitry Andric                                      QualType *arrayType = nullptr,
3667480093f4SDimitry Andric                                      const Expr *Base = nullptr,
3668*0b57cec5SDimitry Andric                                      const llvm::Twine &name = "arrayidx") {
3669*0b57cec5SDimitry Andric   // All the indices except that last must be zero.
3670*0b57cec5SDimitry Andric #ifndef NDEBUG
3671*0b57cec5SDimitry Andric   for (auto idx : indices.drop_back())
3672*0b57cec5SDimitry Andric     assert(isa<llvm::ConstantInt>(idx) &&
3673*0b57cec5SDimitry Andric            cast<llvm::ConstantInt>(idx)->isZero());
3674*0b57cec5SDimitry Andric #endif
3675*0b57cec5SDimitry Andric 
3676*0b57cec5SDimitry Andric   // Determine the element size of the statically-sized base.  This is
3677*0b57cec5SDimitry Andric   // the thing that the indices are expressed in terms of.
3678*0b57cec5SDimitry Andric   if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3679*0b57cec5SDimitry Andric     eltType = getFixedSizeElementType(CGF.getContext(), vla);
3680*0b57cec5SDimitry Andric   }
3681*0b57cec5SDimitry Andric 
3682*0b57cec5SDimitry Andric   // We can use that to compute the best alignment of the element.
3683*0b57cec5SDimitry Andric   CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3684*0b57cec5SDimitry Andric   CharUnits eltAlign =
3685*0b57cec5SDimitry Andric     getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3686*0b57cec5SDimitry Andric 
3687*0b57cec5SDimitry Andric   llvm::Value *eltPtr;
3688*0b57cec5SDimitry Andric   auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back());
3689480093f4SDimitry Andric   if (!LastIndex ||
3690480093f4SDimitry Andric       (!CGF.IsInPreservedAIRegion && !IsPreserveAIArrayBase(CGF, Base))) {
3691*0b57cec5SDimitry Andric     eltPtr = emitArraySubscriptGEP(
3692fe6060f1SDimitry Andric         CGF, addr.getElementType(), addr.getPointer(), indices, inbounds,
3693fe6060f1SDimitry Andric         signedIndices, loc, name);
3694*0b57cec5SDimitry Andric   } else {
3695*0b57cec5SDimitry Andric     // Remember the original array subscript for bpf target
3696*0b57cec5SDimitry Andric     unsigned idx = LastIndex->getZExtValue();
3697a7dea167SDimitry Andric     llvm::DIType *DbgInfo = nullptr;
3698a7dea167SDimitry Andric     if (arrayType)
3699a7dea167SDimitry Andric       DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(*arrayType, loc);
3700480093f4SDimitry Andric     eltPtr = CGF.Builder.CreatePreserveArrayAccessIndex(addr.getElementType(),
3701480093f4SDimitry Andric                                                         addr.getPointer(),
3702*0b57cec5SDimitry Andric                                                         indices.size() - 1,
3703a7dea167SDimitry Andric                                                         idx, DbgInfo);
3704*0b57cec5SDimitry Andric   }
3705*0b57cec5SDimitry Andric 
37060eae32dcSDimitry Andric   return Address(eltPtr, CGF.ConvertTypeForMem(eltType), eltAlign);
3707*0b57cec5SDimitry Andric }
3708*0b57cec5SDimitry Andric 
3709*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3710*0b57cec5SDimitry Andric                                                bool Accessed) {
3711*0b57cec5SDimitry Andric   // The index must always be an integer, which is not an aggregate.  Emit it
3712*0b57cec5SDimitry Andric   // in lexical order (this complexity is, sadly, required by C++17).
3713*0b57cec5SDimitry Andric   llvm::Value *IdxPre =
3714*0b57cec5SDimitry Andric       (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
3715*0b57cec5SDimitry Andric   bool SignedIndices = false;
3716*0b57cec5SDimitry Andric   auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
3717*0b57cec5SDimitry Andric     auto *Idx = IdxPre;
3718*0b57cec5SDimitry Andric     if (E->getLHS() != E->getIdx()) {
3719*0b57cec5SDimitry Andric       assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3720*0b57cec5SDimitry Andric       Idx = EmitScalarExpr(E->getIdx());
3721*0b57cec5SDimitry Andric     }
3722*0b57cec5SDimitry Andric 
3723*0b57cec5SDimitry Andric     QualType IdxTy = E->getIdx()->getType();
3724*0b57cec5SDimitry Andric     bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
3725*0b57cec5SDimitry Andric     SignedIndices |= IdxSigned;
3726*0b57cec5SDimitry Andric 
3727*0b57cec5SDimitry Andric     if (SanOpts.has(SanitizerKind::ArrayBounds))
3728*0b57cec5SDimitry Andric       EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3729*0b57cec5SDimitry Andric 
3730*0b57cec5SDimitry Andric     // Extend or truncate the index type to 32 or 64-bits.
3731*0b57cec5SDimitry Andric     if (Promote && Idx->getType() != IntPtrTy)
3732*0b57cec5SDimitry Andric       Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3733*0b57cec5SDimitry Andric 
3734*0b57cec5SDimitry Andric     return Idx;
3735*0b57cec5SDimitry Andric   };
3736*0b57cec5SDimitry Andric   IdxPre = nullptr;
3737*0b57cec5SDimitry Andric 
3738*0b57cec5SDimitry Andric   // If the base is a vector type, then we are forming a vector element lvalue
3739*0b57cec5SDimitry Andric   // with this subscript.
3740*0b57cec5SDimitry Andric   if (E->getBase()->getType()->isVectorType() &&
3741*0b57cec5SDimitry Andric       !isa<ExtVectorElementExpr>(E->getBase())) {
3742*0b57cec5SDimitry Andric     // Emit the vector as an lvalue to get its address.
3743*0b57cec5SDimitry Andric     LValue LHS = EmitLValue(E->getBase());
3744*0b57cec5SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/false);
3745*0b57cec5SDimitry Andric     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
3746480093f4SDimitry Andric     return LValue::MakeVectorElt(LHS.getAddress(*this), Idx,
3747480093f4SDimitry Andric                                  E->getBase()->getType(), LHS.getBaseInfo(),
3748480093f4SDimitry Andric                                  TBAAAccessInfo());
3749*0b57cec5SDimitry Andric   }
3750*0b57cec5SDimitry Andric 
3751*0b57cec5SDimitry Andric   // All the other cases basically behave like simple offsetting.
3752*0b57cec5SDimitry Andric 
3753*0b57cec5SDimitry Andric   // Handle the extvector case we ignored above.
3754*0b57cec5SDimitry Andric   if (isa<ExtVectorElementExpr>(E->getBase())) {
3755*0b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getBase());
3756*0b57cec5SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3757*0b57cec5SDimitry Andric     Address Addr = EmitExtVectorElementLValue(LV);
3758*0b57cec5SDimitry Andric 
3759*0b57cec5SDimitry Andric     QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
3760*0b57cec5SDimitry Andric     Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
3761*0b57cec5SDimitry Andric                                  SignedIndices, E->getExprLoc());
3762*0b57cec5SDimitry Andric     return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
3763*0b57cec5SDimitry Andric                           CGM.getTBAAInfoForSubobject(LV, EltType));
3764*0b57cec5SDimitry Andric   }
3765*0b57cec5SDimitry Andric 
3766*0b57cec5SDimitry Andric   LValueBaseInfo EltBaseInfo;
3767*0b57cec5SDimitry Andric   TBAAAccessInfo EltTBAAInfo;
3768*0b57cec5SDimitry Andric   Address Addr = Address::invalid();
3769*0b57cec5SDimitry Andric   if (const VariableArrayType *vla =
3770*0b57cec5SDimitry Andric            getContext().getAsVariableArrayType(E->getType())) {
3771*0b57cec5SDimitry Andric     // The base must be a pointer, which is not an aggregate.  Emit
3772*0b57cec5SDimitry Andric     // it.  It needs to be emitted first in case it's what captures
3773*0b57cec5SDimitry Andric     // the VLA bounds.
3774*0b57cec5SDimitry Andric     Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3775*0b57cec5SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3776*0b57cec5SDimitry Andric 
3777*0b57cec5SDimitry Andric     // The element count here is the total number of non-VLA elements.
3778*0b57cec5SDimitry Andric     llvm::Value *numElements = getVLASize(vla).NumElts;
3779*0b57cec5SDimitry Andric 
3780*0b57cec5SDimitry Andric     // Effectively, the multiply by the VLA size is part of the GEP.
3781*0b57cec5SDimitry Andric     // GEP indexes are signed, and scaling an index isn't permitted to
3782*0b57cec5SDimitry Andric     // signed-overflow, so we use the same semantics for our explicit
3783*0b57cec5SDimitry Andric     // multiply.  We suppress this if overflow is not undefined behavior.
3784*0b57cec5SDimitry Andric     if (getLangOpts().isSignedOverflowDefined()) {
3785*0b57cec5SDimitry Andric       Idx = Builder.CreateMul(Idx, numElements);
3786*0b57cec5SDimitry Andric     } else {
3787*0b57cec5SDimitry Andric       Idx = Builder.CreateNSWMul(Idx, numElements);
3788*0b57cec5SDimitry Andric     }
3789*0b57cec5SDimitry Andric 
3790*0b57cec5SDimitry Andric     Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3791*0b57cec5SDimitry Andric                                  !getLangOpts().isSignedOverflowDefined(),
3792*0b57cec5SDimitry Andric                                  SignedIndices, E->getExprLoc());
3793*0b57cec5SDimitry Andric 
3794*0b57cec5SDimitry Andric   } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3795*0b57cec5SDimitry Andric     // Indexing over an interface, as in "NSString *P; P[4];"
3796*0b57cec5SDimitry Andric 
3797*0b57cec5SDimitry Andric     // Emit the base pointer.
3798*0b57cec5SDimitry Andric     Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3799*0b57cec5SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3800*0b57cec5SDimitry Andric 
3801*0b57cec5SDimitry Andric     CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3802*0b57cec5SDimitry Andric     llvm::Value *InterfaceSizeVal =
3803*0b57cec5SDimitry Andric         llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3804*0b57cec5SDimitry Andric 
3805*0b57cec5SDimitry Andric     llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
3806*0b57cec5SDimitry Andric 
3807*0b57cec5SDimitry Andric     // We don't necessarily build correct LLVM struct types for ObjC
3808*0b57cec5SDimitry Andric     // interfaces, so we can't rely on GEP to do this scaling
3809*0b57cec5SDimitry Andric     // correctly, so we need to cast to i8*.  FIXME: is this actually
3810*0b57cec5SDimitry Andric     // true?  A lot of other things in the fragile ABI would break...
3811*0b57cec5SDimitry Andric     llvm::Type *OrigBaseTy = Addr.getType();
3812*0b57cec5SDimitry Andric     Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3813*0b57cec5SDimitry Andric 
3814*0b57cec5SDimitry Andric     // Do the GEP.
3815*0b57cec5SDimitry Andric     CharUnits EltAlign =
3816*0b57cec5SDimitry Andric       getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
3817*0b57cec5SDimitry Andric     llvm::Value *EltPtr =
3818fe6060f1SDimitry Andric         emitArraySubscriptGEP(*this, Addr.getElementType(), Addr.getPointer(),
3819fe6060f1SDimitry Andric                               ScaledIdx, false, SignedIndices, E->getExprLoc());
3820*0b57cec5SDimitry Andric     Addr = Address(EltPtr, EltAlign);
3821*0b57cec5SDimitry Andric 
3822*0b57cec5SDimitry Andric     // Cast back.
3823*0b57cec5SDimitry Andric     Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
3824*0b57cec5SDimitry Andric   } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3825*0b57cec5SDimitry Andric     // If this is A[i] where A is an array, the frontend will have decayed the
3826*0b57cec5SDimitry Andric     // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
3827*0b57cec5SDimitry Andric     // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3828*0b57cec5SDimitry Andric     // "gep x, i" here.  Emit one "gep A, 0, i".
3829*0b57cec5SDimitry Andric     assert(Array->getType()->isArrayType() &&
3830*0b57cec5SDimitry Andric            "Array to pointer decay must have array source type!");
3831*0b57cec5SDimitry Andric     LValue ArrayLV;
3832*0b57cec5SDimitry Andric     // For simple multidimensional array indexing, set the 'accessed' flag for
3833*0b57cec5SDimitry Andric     // better bounds-checking of the base expression.
3834*0b57cec5SDimitry Andric     if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3835*0b57cec5SDimitry Andric       ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3836*0b57cec5SDimitry Andric     else
3837*0b57cec5SDimitry Andric       ArrayLV = EmitLValue(Array);
3838*0b57cec5SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3839*0b57cec5SDimitry Andric 
3840*0b57cec5SDimitry Andric     // Propagate the alignment from the array itself to the result.
3841a7dea167SDimitry Andric     QualType arrayType = Array->getType();
3842*0b57cec5SDimitry Andric     Addr = emitArraySubscriptGEP(
3843480093f4SDimitry Andric         *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
3844*0b57cec5SDimitry Andric         E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3845480093f4SDimitry Andric         E->getExprLoc(), &arrayType, E->getBase());
3846*0b57cec5SDimitry Andric     EltBaseInfo = ArrayLV.getBaseInfo();
3847*0b57cec5SDimitry Andric     EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
3848*0b57cec5SDimitry Andric   } else {
3849*0b57cec5SDimitry Andric     // The base must be a pointer; emit it with an estimate of its alignment.
3850*0b57cec5SDimitry Andric     Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3851*0b57cec5SDimitry Andric     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3852a7dea167SDimitry Andric     QualType ptrType = E->getBase()->getType();
3853*0b57cec5SDimitry Andric     Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3854*0b57cec5SDimitry Andric                                  !getLangOpts().isSignedOverflowDefined(),
3855480093f4SDimitry Andric                                  SignedIndices, E->getExprLoc(), &ptrType,
3856480093f4SDimitry Andric                                  E->getBase());
3857*0b57cec5SDimitry Andric   }
3858*0b57cec5SDimitry Andric 
3859*0b57cec5SDimitry Andric   LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
3860*0b57cec5SDimitry Andric 
3861*0b57cec5SDimitry Andric   if (getLangOpts().ObjC &&
3862*0b57cec5SDimitry Andric       getLangOpts().getGC() != LangOptions::NonGC) {
3863*0b57cec5SDimitry Andric     LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
3864*0b57cec5SDimitry Andric     setObjCGCLValueClass(getContext(), E, LV);
3865*0b57cec5SDimitry Andric   }
3866*0b57cec5SDimitry Andric   return LV;
3867*0b57cec5SDimitry Andric }
3868*0b57cec5SDimitry Andric 
38695ffd83dbSDimitry Andric LValue CodeGenFunction::EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E) {
38705ffd83dbSDimitry Andric   assert(
38715ffd83dbSDimitry Andric       !E->isIncomplete() &&
38725ffd83dbSDimitry Andric       "incomplete matrix subscript expressions should be rejected during Sema");
38735ffd83dbSDimitry Andric   LValue Base = EmitLValue(E->getBase());
38745ffd83dbSDimitry Andric   llvm::Value *RowIdx = EmitScalarExpr(E->getRowIdx());
38755ffd83dbSDimitry Andric   llvm::Value *ColIdx = EmitScalarExpr(E->getColumnIdx());
38765ffd83dbSDimitry Andric   llvm::Value *NumRows = Builder.getIntN(
38775ffd83dbSDimitry Andric       RowIdx->getType()->getScalarSizeInBits(),
3878e8d8bef9SDimitry Andric       E->getBase()->getType()->castAs<ConstantMatrixType>()->getNumRows());
38795ffd83dbSDimitry Andric   llvm::Value *FinalIdx =
38805ffd83dbSDimitry Andric       Builder.CreateAdd(Builder.CreateMul(ColIdx, NumRows), RowIdx);
38815ffd83dbSDimitry Andric   return LValue::MakeMatrixElt(
38825ffd83dbSDimitry Andric       MaybeConvertMatrixAddress(Base.getAddress(*this), *this), FinalIdx,
38835ffd83dbSDimitry Andric       E->getBase()->getType(), Base.getBaseInfo(), TBAAAccessInfo());
38845ffd83dbSDimitry Andric }
38855ffd83dbSDimitry Andric 
3886*0b57cec5SDimitry Andric static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
3887*0b57cec5SDimitry Andric                                        LValueBaseInfo &BaseInfo,
3888*0b57cec5SDimitry Andric                                        TBAAAccessInfo &TBAAInfo,
3889*0b57cec5SDimitry Andric                                        QualType BaseTy, QualType ElTy,
3890*0b57cec5SDimitry Andric                                        bool IsLowerBound) {
3891*0b57cec5SDimitry Andric   LValue BaseLVal;
3892*0b57cec5SDimitry Andric   if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3893*0b57cec5SDimitry Andric     BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3894*0b57cec5SDimitry Andric     if (BaseTy->isArrayType()) {
3895480093f4SDimitry Andric       Address Addr = BaseLVal.getAddress(CGF);
3896*0b57cec5SDimitry Andric       BaseInfo = BaseLVal.getBaseInfo();
3897*0b57cec5SDimitry Andric 
3898*0b57cec5SDimitry Andric       // If the array type was an incomplete type, we need to make sure
3899*0b57cec5SDimitry Andric       // the decay ends up being the right type.
3900*0b57cec5SDimitry Andric       llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3901*0b57cec5SDimitry Andric       Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3902*0b57cec5SDimitry Andric 
3903*0b57cec5SDimitry Andric       // Note that VLA pointers are always decayed, so we don't need to do
3904*0b57cec5SDimitry Andric       // anything here.
3905*0b57cec5SDimitry Andric       if (!BaseTy->isVariableArrayType()) {
3906*0b57cec5SDimitry Andric         assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3907*0b57cec5SDimitry Andric                "Expected pointer to array");
3908*0b57cec5SDimitry Andric         Addr = CGF.Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
3909*0b57cec5SDimitry Andric       }
3910*0b57cec5SDimitry Andric 
3911*0b57cec5SDimitry Andric       return CGF.Builder.CreateElementBitCast(Addr,
3912*0b57cec5SDimitry Andric                                               CGF.ConvertTypeForMem(ElTy));
3913*0b57cec5SDimitry Andric     }
3914*0b57cec5SDimitry Andric     LValueBaseInfo TypeBaseInfo;
3915*0b57cec5SDimitry Andric     TBAAAccessInfo TypeTBAAInfo;
39165ffd83dbSDimitry Andric     CharUnits Align =
39175ffd83dbSDimitry Andric         CGF.CGM.getNaturalTypeAlignment(ElTy, &TypeBaseInfo, &TypeTBAAInfo);
3918*0b57cec5SDimitry Andric     BaseInfo.mergeForCast(TypeBaseInfo);
3919*0b57cec5SDimitry Andric     TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
3920480093f4SDimitry Andric     return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress(CGF)), Align);
3921*0b57cec5SDimitry Andric   }
3922*0b57cec5SDimitry Andric   return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
3923*0b57cec5SDimitry Andric }
3924*0b57cec5SDimitry Andric 
3925*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3926*0b57cec5SDimitry Andric                                                 bool IsLowerBound) {
3927*0b57cec5SDimitry Andric   QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(E->getBase());
3928*0b57cec5SDimitry Andric   QualType ResultExprTy;
3929*0b57cec5SDimitry Andric   if (auto *AT = getContext().getAsArrayType(BaseTy))
3930*0b57cec5SDimitry Andric     ResultExprTy = AT->getElementType();
3931*0b57cec5SDimitry Andric   else
3932*0b57cec5SDimitry Andric     ResultExprTy = BaseTy->getPointeeType();
3933*0b57cec5SDimitry Andric   llvm::Value *Idx = nullptr;
39345ffd83dbSDimitry Andric   if (IsLowerBound || E->getColonLocFirst().isInvalid()) {
3935*0b57cec5SDimitry Andric     // Requesting lower bound or upper bound, but without provided length and
3936*0b57cec5SDimitry Andric     // without ':' symbol for the default length -> length = 1.
3937*0b57cec5SDimitry Andric     // Idx = LowerBound ?: 0;
3938*0b57cec5SDimitry Andric     if (auto *LowerBound = E->getLowerBound()) {
3939*0b57cec5SDimitry Andric       Idx = Builder.CreateIntCast(
3940*0b57cec5SDimitry Andric           EmitScalarExpr(LowerBound), IntPtrTy,
3941*0b57cec5SDimitry Andric           LowerBound->getType()->hasSignedIntegerRepresentation());
3942*0b57cec5SDimitry Andric     } else
3943*0b57cec5SDimitry Andric       Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3944*0b57cec5SDimitry Andric   } else {
3945*0b57cec5SDimitry Andric     // Try to emit length or lower bound as constant. If this is possible, 1
3946*0b57cec5SDimitry Andric     // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3947*0b57cec5SDimitry Andric     // IR (LB + Len) - 1.
3948*0b57cec5SDimitry Andric     auto &C = CGM.getContext();
3949*0b57cec5SDimitry Andric     auto *Length = E->getLength();
3950*0b57cec5SDimitry Andric     llvm::APSInt ConstLength;
3951*0b57cec5SDimitry Andric     if (Length) {
3952*0b57cec5SDimitry Andric       // Idx = LowerBound + Length - 1;
3953e8d8bef9SDimitry Andric       if (Optional<llvm::APSInt> CL = Length->getIntegerConstantExpr(C)) {
3954e8d8bef9SDimitry Andric         ConstLength = CL->zextOrTrunc(PointerWidthInBits);
3955*0b57cec5SDimitry Andric         Length = nullptr;
3956*0b57cec5SDimitry Andric       }
3957*0b57cec5SDimitry Andric       auto *LowerBound = E->getLowerBound();
3958*0b57cec5SDimitry Andric       llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3959e8d8bef9SDimitry Andric       if (LowerBound) {
3960e8d8bef9SDimitry Andric         if (Optional<llvm::APSInt> LB = LowerBound->getIntegerConstantExpr(C)) {
3961e8d8bef9SDimitry Andric           ConstLowerBound = LB->zextOrTrunc(PointerWidthInBits);
3962*0b57cec5SDimitry Andric           LowerBound = nullptr;
3963*0b57cec5SDimitry Andric         }
3964e8d8bef9SDimitry Andric       }
3965*0b57cec5SDimitry Andric       if (!Length)
3966*0b57cec5SDimitry Andric         --ConstLength;
3967*0b57cec5SDimitry Andric       else if (!LowerBound)
3968*0b57cec5SDimitry Andric         --ConstLowerBound;
3969*0b57cec5SDimitry Andric 
3970*0b57cec5SDimitry Andric       if (Length || LowerBound) {
3971*0b57cec5SDimitry Andric         auto *LowerBoundVal =
3972*0b57cec5SDimitry Andric             LowerBound
3973*0b57cec5SDimitry Andric                 ? Builder.CreateIntCast(
3974*0b57cec5SDimitry Andric                       EmitScalarExpr(LowerBound), IntPtrTy,
3975*0b57cec5SDimitry Andric                       LowerBound->getType()->hasSignedIntegerRepresentation())
3976*0b57cec5SDimitry Andric                 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3977*0b57cec5SDimitry Andric         auto *LengthVal =
3978*0b57cec5SDimitry Andric             Length
3979*0b57cec5SDimitry Andric                 ? Builder.CreateIntCast(
3980*0b57cec5SDimitry Andric                       EmitScalarExpr(Length), IntPtrTy,
3981*0b57cec5SDimitry Andric                       Length->getType()->hasSignedIntegerRepresentation())
3982*0b57cec5SDimitry Andric                 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3983*0b57cec5SDimitry Andric         Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3984*0b57cec5SDimitry Andric                                 /*HasNUW=*/false,
3985*0b57cec5SDimitry Andric                                 !getLangOpts().isSignedOverflowDefined());
3986*0b57cec5SDimitry Andric         if (Length && LowerBound) {
3987*0b57cec5SDimitry Andric           Idx = Builder.CreateSub(
3988*0b57cec5SDimitry Andric               Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3989*0b57cec5SDimitry Andric               /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3990*0b57cec5SDimitry Andric         }
3991*0b57cec5SDimitry Andric       } else
3992*0b57cec5SDimitry Andric         Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3993*0b57cec5SDimitry Andric     } else {
3994*0b57cec5SDimitry Andric       // Idx = ArraySize - 1;
3995*0b57cec5SDimitry Andric       QualType ArrayTy = BaseTy->isPointerType()
3996*0b57cec5SDimitry Andric                              ? E->getBase()->IgnoreParenImpCasts()->getType()
3997*0b57cec5SDimitry Andric                              : BaseTy;
3998*0b57cec5SDimitry Andric       if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
3999*0b57cec5SDimitry Andric         Length = VAT->getSizeExpr();
4000e8d8bef9SDimitry Andric         if (Optional<llvm::APSInt> L = Length->getIntegerConstantExpr(C)) {
4001e8d8bef9SDimitry Andric           ConstLength = *L;
4002*0b57cec5SDimitry Andric           Length = nullptr;
4003e8d8bef9SDimitry Andric         }
4004*0b57cec5SDimitry Andric       } else {
4005*0b57cec5SDimitry Andric         auto *CAT = C.getAsConstantArrayType(ArrayTy);
4006*0b57cec5SDimitry Andric         ConstLength = CAT->getSize();
4007*0b57cec5SDimitry Andric       }
4008*0b57cec5SDimitry Andric       if (Length) {
4009*0b57cec5SDimitry Andric         auto *LengthVal = Builder.CreateIntCast(
4010*0b57cec5SDimitry Andric             EmitScalarExpr(Length), IntPtrTy,
4011*0b57cec5SDimitry Andric             Length->getType()->hasSignedIntegerRepresentation());
4012*0b57cec5SDimitry Andric         Idx = Builder.CreateSub(
4013*0b57cec5SDimitry Andric             LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
4014*0b57cec5SDimitry Andric             /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
4015*0b57cec5SDimitry Andric       } else {
4016*0b57cec5SDimitry Andric         ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
4017*0b57cec5SDimitry Andric         --ConstLength;
4018*0b57cec5SDimitry Andric         Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
4019*0b57cec5SDimitry Andric       }
4020*0b57cec5SDimitry Andric     }
4021*0b57cec5SDimitry Andric   }
4022*0b57cec5SDimitry Andric   assert(Idx);
4023*0b57cec5SDimitry Andric 
4024*0b57cec5SDimitry Andric   Address EltPtr = Address::invalid();
4025*0b57cec5SDimitry Andric   LValueBaseInfo BaseInfo;
4026*0b57cec5SDimitry Andric   TBAAAccessInfo TBAAInfo;
4027*0b57cec5SDimitry Andric   if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
4028*0b57cec5SDimitry Andric     // The base must be a pointer, which is not an aggregate.  Emit
4029*0b57cec5SDimitry Andric     // it.  It needs to be emitted first in case it's what captures
4030*0b57cec5SDimitry Andric     // the VLA bounds.
4031*0b57cec5SDimitry Andric     Address Base =
4032*0b57cec5SDimitry Andric         emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
4033*0b57cec5SDimitry Andric                                 BaseTy, VLA->getElementType(), IsLowerBound);
4034*0b57cec5SDimitry Andric     // The element count here is the total number of non-VLA elements.
4035*0b57cec5SDimitry Andric     llvm::Value *NumElements = getVLASize(VLA).NumElts;
4036*0b57cec5SDimitry Andric 
4037*0b57cec5SDimitry Andric     // Effectively, the multiply by the VLA size is part of the GEP.
4038*0b57cec5SDimitry Andric     // GEP indexes are signed, and scaling an index isn't permitted to
4039*0b57cec5SDimitry Andric     // signed-overflow, so we use the same semantics for our explicit
4040*0b57cec5SDimitry Andric     // multiply.  We suppress this if overflow is not undefined behavior.
4041*0b57cec5SDimitry Andric     if (getLangOpts().isSignedOverflowDefined())
4042*0b57cec5SDimitry Andric       Idx = Builder.CreateMul(Idx, NumElements);
4043*0b57cec5SDimitry Andric     else
4044*0b57cec5SDimitry Andric       Idx = Builder.CreateNSWMul(Idx, NumElements);
4045*0b57cec5SDimitry Andric     EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
4046*0b57cec5SDimitry Andric                                    !getLangOpts().isSignedOverflowDefined(),
4047*0b57cec5SDimitry Andric                                    /*signedIndices=*/false, E->getExprLoc());
4048*0b57cec5SDimitry Andric   } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
4049*0b57cec5SDimitry Andric     // If this is A[i] where A is an array, the frontend will have decayed the
4050*0b57cec5SDimitry Andric     // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
4051*0b57cec5SDimitry Andric     // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
4052*0b57cec5SDimitry Andric     // "gep x, i" here.  Emit one "gep A, 0, i".
4053*0b57cec5SDimitry Andric     assert(Array->getType()->isArrayType() &&
4054*0b57cec5SDimitry Andric            "Array to pointer decay must have array source type!");
4055*0b57cec5SDimitry Andric     LValue ArrayLV;
4056*0b57cec5SDimitry Andric     // For simple multidimensional array indexing, set the 'accessed' flag for
4057*0b57cec5SDimitry Andric     // better bounds-checking of the base expression.
4058*0b57cec5SDimitry Andric     if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
4059*0b57cec5SDimitry Andric       ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
4060*0b57cec5SDimitry Andric     else
4061*0b57cec5SDimitry Andric       ArrayLV = EmitLValue(Array);
4062*0b57cec5SDimitry Andric 
4063*0b57cec5SDimitry Andric     // Propagate the alignment from the array itself to the result.
4064*0b57cec5SDimitry Andric     EltPtr = emitArraySubscriptGEP(
4065480093f4SDimitry Andric         *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
4066*0b57cec5SDimitry Andric         ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
4067*0b57cec5SDimitry Andric         /*signedIndices=*/false, E->getExprLoc());
4068*0b57cec5SDimitry Andric     BaseInfo = ArrayLV.getBaseInfo();
4069*0b57cec5SDimitry Andric     TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
4070*0b57cec5SDimitry Andric   } else {
4071*0b57cec5SDimitry Andric     Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
4072*0b57cec5SDimitry Andric                                            TBAAInfo, BaseTy, ResultExprTy,
4073*0b57cec5SDimitry Andric                                            IsLowerBound);
4074*0b57cec5SDimitry Andric     EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
4075*0b57cec5SDimitry Andric                                    !getLangOpts().isSignedOverflowDefined(),
4076*0b57cec5SDimitry Andric                                    /*signedIndices=*/false, E->getExprLoc());
4077*0b57cec5SDimitry Andric   }
4078*0b57cec5SDimitry Andric 
4079*0b57cec5SDimitry Andric   return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
4080*0b57cec5SDimitry Andric }
4081*0b57cec5SDimitry Andric 
4082*0b57cec5SDimitry Andric LValue CodeGenFunction::
4083*0b57cec5SDimitry Andric EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
4084*0b57cec5SDimitry Andric   // Emit the base vector as an l-value.
4085*0b57cec5SDimitry Andric   LValue Base;
4086*0b57cec5SDimitry Andric 
4087*0b57cec5SDimitry Andric   // ExtVectorElementExpr's base can either be a vector or pointer to vector.
4088*0b57cec5SDimitry Andric   if (E->isArrow()) {
4089*0b57cec5SDimitry Andric     // If it is a pointer to a vector, emit the address and form an lvalue with
4090*0b57cec5SDimitry Andric     // it.
4091*0b57cec5SDimitry Andric     LValueBaseInfo BaseInfo;
4092*0b57cec5SDimitry Andric     TBAAAccessInfo TBAAInfo;
4093*0b57cec5SDimitry Andric     Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
4094480093f4SDimitry Andric     const auto *PT = E->getBase()->getType()->castAs<PointerType>();
4095*0b57cec5SDimitry Andric     Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
4096*0b57cec5SDimitry Andric     Base.getQuals().removeObjCGCAttr();
4097*0b57cec5SDimitry Andric   } else if (E->getBase()->isGLValue()) {
4098*0b57cec5SDimitry Andric     // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
4099*0b57cec5SDimitry Andric     // emit the base as an lvalue.
4100*0b57cec5SDimitry Andric     assert(E->getBase()->getType()->isVectorType());
4101*0b57cec5SDimitry Andric     Base = EmitLValue(E->getBase());
4102*0b57cec5SDimitry Andric   } else {
4103*0b57cec5SDimitry Andric     // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
4104*0b57cec5SDimitry Andric     assert(E->getBase()->getType()->isVectorType() &&
4105*0b57cec5SDimitry Andric            "Result must be a vector");
4106*0b57cec5SDimitry Andric     llvm::Value *Vec = EmitScalarExpr(E->getBase());
4107*0b57cec5SDimitry Andric 
4108*0b57cec5SDimitry Andric     // Store the vector to memory (because LValue wants an address).
4109*0b57cec5SDimitry Andric     Address VecMem = CreateMemTemp(E->getBase()->getType());
4110*0b57cec5SDimitry Andric     Builder.CreateStore(Vec, VecMem);
4111*0b57cec5SDimitry Andric     Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
4112*0b57cec5SDimitry Andric                           AlignmentSource::Decl);
4113*0b57cec5SDimitry Andric   }
4114*0b57cec5SDimitry Andric 
4115*0b57cec5SDimitry Andric   QualType type =
4116*0b57cec5SDimitry Andric     E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
4117*0b57cec5SDimitry Andric 
4118*0b57cec5SDimitry Andric   // Encode the element access list into a vector of unsigned indices.
4119*0b57cec5SDimitry Andric   SmallVector<uint32_t, 4> Indices;
4120*0b57cec5SDimitry Andric   E->getEncodedElementAccess(Indices);
4121*0b57cec5SDimitry Andric 
4122*0b57cec5SDimitry Andric   if (Base.isSimple()) {
4123*0b57cec5SDimitry Andric     llvm::Constant *CV =
4124*0b57cec5SDimitry Andric         llvm::ConstantDataVector::get(getLLVMContext(), Indices);
4125480093f4SDimitry Andric     return LValue::MakeExtVectorElt(Base.getAddress(*this), CV, type,
4126*0b57cec5SDimitry Andric                                     Base.getBaseInfo(), TBAAAccessInfo());
4127*0b57cec5SDimitry Andric   }
4128*0b57cec5SDimitry Andric   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
4129*0b57cec5SDimitry Andric 
4130*0b57cec5SDimitry Andric   llvm::Constant *BaseElts = Base.getExtVectorElts();
4131*0b57cec5SDimitry Andric   SmallVector<llvm::Constant *, 4> CElts;
4132*0b57cec5SDimitry Andric 
4133*0b57cec5SDimitry Andric   for (unsigned i = 0, e = Indices.size(); i != e; ++i)
4134*0b57cec5SDimitry Andric     CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
4135*0b57cec5SDimitry Andric   llvm::Constant *CV = llvm::ConstantVector::get(CElts);
4136*0b57cec5SDimitry Andric   return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
4137*0b57cec5SDimitry Andric                                   Base.getBaseInfo(), TBAAAccessInfo());
4138*0b57cec5SDimitry Andric }
4139*0b57cec5SDimitry Andric 
4140*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
4141*0b57cec5SDimitry Andric   if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
4142*0b57cec5SDimitry Andric     EmitIgnoredExpr(E->getBase());
4143*0b57cec5SDimitry Andric     return EmitDeclRefLValue(DRE);
4144*0b57cec5SDimitry Andric   }
4145*0b57cec5SDimitry Andric 
4146*0b57cec5SDimitry Andric   Expr *BaseExpr = E->getBase();
4147*0b57cec5SDimitry Andric   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
4148*0b57cec5SDimitry Andric   LValue BaseLV;
4149*0b57cec5SDimitry Andric   if (E->isArrow()) {
4150*0b57cec5SDimitry Andric     LValueBaseInfo BaseInfo;
4151*0b57cec5SDimitry Andric     TBAAAccessInfo TBAAInfo;
4152*0b57cec5SDimitry Andric     Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
4153*0b57cec5SDimitry Andric     QualType PtrTy = BaseExpr->getType()->getPointeeType();
4154*0b57cec5SDimitry Andric     SanitizerSet SkippedChecks;
4155*0b57cec5SDimitry Andric     bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
4156*0b57cec5SDimitry Andric     if (IsBaseCXXThis)
4157*0b57cec5SDimitry Andric       SkippedChecks.set(SanitizerKind::Alignment, true);
4158*0b57cec5SDimitry Andric     if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
4159*0b57cec5SDimitry Andric       SkippedChecks.set(SanitizerKind::Null, true);
4160*0b57cec5SDimitry Andric     EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
4161*0b57cec5SDimitry Andric                   /*Alignment=*/CharUnits::Zero(), SkippedChecks);
4162*0b57cec5SDimitry Andric     BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
4163*0b57cec5SDimitry Andric   } else
4164*0b57cec5SDimitry Andric     BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
4165*0b57cec5SDimitry Andric 
4166*0b57cec5SDimitry Andric   NamedDecl *ND = E->getMemberDecl();
4167*0b57cec5SDimitry Andric   if (auto *Field = dyn_cast<FieldDecl>(ND)) {
4168*0b57cec5SDimitry Andric     LValue LV = EmitLValueForField(BaseLV, Field);
4169*0b57cec5SDimitry Andric     setObjCGCLValueClass(getContext(), E, LV);
4170480093f4SDimitry Andric     if (getLangOpts().OpenMP) {
4171480093f4SDimitry Andric       // If the member was explicitly marked as nontemporal, mark it as
4172480093f4SDimitry Andric       // nontemporal. If the base lvalue is marked as nontemporal, mark access
4173480093f4SDimitry Andric       // to children as nontemporal too.
4174480093f4SDimitry Andric       if ((IsWrappedCXXThis(BaseExpr) &&
4175480093f4SDimitry Andric            CGM.getOpenMPRuntime().isNontemporalDecl(Field)) ||
4176480093f4SDimitry Andric           BaseLV.isNontemporal())
4177480093f4SDimitry Andric         LV.setNontemporal(/*Value=*/true);
4178480093f4SDimitry Andric     }
4179*0b57cec5SDimitry Andric     return LV;
4180*0b57cec5SDimitry Andric   }
4181*0b57cec5SDimitry Andric 
4182*0b57cec5SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
4183*0b57cec5SDimitry Andric     return EmitFunctionDeclLValue(*this, E, FD);
4184*0b57cec5SDimitry Andric 
4185*0b57cec5SDimitry Andric   llvm_unreachable("Unhandled member declaration!");
4186*0b57cec5SDimitry Andric }
4187*0b57cec5SDimitry Andric 
4188*0b57cec5SDimitry Andric /// Given that we are currently emitting a lambda, emit an l-value for
4189*0b57cec5SDimitry Andric /// one of its members.
4190*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
4191fe6060f1SDimitry Andric   if (CurCodeDecl) {
4192*0b57cec5SDimitry Andric     assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
4193*0b57cec5SDimitry Andric     assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
4194fe6060f1SDimitry Andric   }
4195*0b57cec5SDimitry Andric   QualType LambdaTagType =
4196*0b57cec5SDimitry Andric     getContext().getTagDeclType(Field->getParent());
4197*0b57cec5SDimitry Andric   LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
4198*0b57cec5SDimitry Andric   return EmitLValueForField(LambdaLV, Field);
4199*0b57cec5SDimitry Andric }
4200*0b57cec5SDimitry Andric 
4201*0b57cec5SDimitry Andric /// Get the field index in the debug info. The debug info structure/union
4202*0b57cec5SDimitry Andric /// will ignore the unnamed bitfields.
4203*0b57cec5SDimitry Andric unsigned CodeGenFunction::getDebugInfoFIndex(const RecordDecl *Rec,
4204*0b57cec5SDimitry Andric                                              unsigned FieldIndex) {
4205*0b57cec5SDimitry Andric   unsigned I = 0, Skipped = 0;
4206*0b57cec5SDimitry Andric 
4207*0b57cec5SDimitry Andric   for (auto F : Rec->getDefinition()->fields()) {
4208*0b57cec5SDimitry Andric     if (I == FieldIndex)
4209*0b57cec5SDimitry Andric       break;
4210*0b57cec5SDimitry Andric     if (F->isUnnamedBitfield())
4211*0b57cec5SDimitry Andric       Skipped++;
4212*0b57cec5SDimitry Andric     I++;
4213*0b57cec5SDimitry Andric   }
4214*0b57cec5SDimitry Andric 
4215*0b57cec5SDimitry Andric   return FieldIndex - Skipped;
4216*0b57cec5SDimitry Andric }
4217*0b57cec5SDimitry Andric 
4218*0b57cec5SDimitry Andric /// Get the address of a zero-sized field within a record. The resulting
4219*0b57cec5SDimitry Andric /// address doesn't necessarily have the right type.
4220*0b57cec5SDimitry Andric static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base,
4221*0b57cec5SDimitry Andric                                        const FieldDecl *Field) {
4222*0b57cec5SDimitry Andric   CharUnits Offset = CGF.getContext().toCharUnitsFromBits(
4223*0b57cec5SDimitry Andric       CGF.getContext().getFieldOffset(Field));
4224*0b57cec5SDimitry Andric   if (Offset.isZero())
4225*0b57cec5SDimitry Andric     return Base;
4226*0b57cec5SDimitry Andric   Base = CGF.Builder.CreateElementBitCast(Base, CGF.Int8Ty);
4227*0b57cec5SDimitry Andric   return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
4228*0b57cec5SDimitry Andric }
4229*0b57cec5SDimitry Andric 
4230*0b57cec5SDimitry Andric /// Drill down to the storage of a field without walking into
4231*0b57cec5SDimitry Andric /// reference types.
4232*0b57cec5SDimitry Andric ///
4233*0b57cec5SDimitry Andric /// The resulting address doesn't necessarily have the right type.
4234*0b57cec5SDimitry Andric static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
4235*0b57cec5SDimitry Andric                                       const FieldDecl *field) {
4236*0b57cec5SDimitry Andric   if (field->isZeroSize(CGF.getContext()))
4237*0b57cec5SDimitry Andric     return emitAddrOfZeroSizeField(CGF, base, field);
4238*0b57cec5SDimitry Andric 
4239*0b57cec5SDimitry Andric   const RecordDecl *rec = field->getParent();
4240*0b57cec5SDimitry Andric 
4241*0b57cec5SDimitry Andric   unsigned idx =
4242*0b57cec5SDimitry Andric     CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
4243*0b57cec5SDimitry Andric 
4244*0b57cec5SDimitry Andric   return CGF.Builder.CreateStructGEP(base, idx, field->getName());
4245*0b57cec5SDimitry Andric }
4246*0b57cec5SDimitry Andric 
42475ffd83dbSDimitry Andric static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base,
42485ffd83dbSDimitry Andric                                         Address addr, const FieldDecl *field) {
4249*0b57cec5SDimitry Andric   const RecordDecl *rec = field->getParent();
42505ffd83dbSDimitry Andric   llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(
42515ffd83dbSDimitry Andric       base.getType(), rec->getLocation());
4252*0b57cec5SDimitry Andric 
4253*0b57cec5SDimitry Andric   unsigned idx =
4254*0b57cec5SDimitry Andric       CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
4255*0b57cec5SDimitry Andric 
4256*0b57cec5SDimitry Andric   return CGF.Builder.CreatePreserveStructAccessIndex(
42575ffd83dbSDimitry Andric       addr, idx, CGF.getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo);
4258*0b57cec5SDimitry Andric }
4259*0b57cec5SDimitry Andric 
4260*0b57cec5SDimitry Andric static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
4261*0b57cec5SDimitry Andric   const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
4262*0b57cec5SDimitry Andric   if (!RD)
4263*0b57cec5SDimitry Andric     return false;
4264*0b57cec5SDimitry Andric 
4265*0b57cec5SDimitry Andric   if (RD->isDynamicClass())
4266*0b57cec5SDimitry Andric     return true;
4267*0b57cec5SDimitry Andric 
4268*0b57cec5SDimitry Andric   for (const auto &Base : RD->bases())
4269*0b57cec5SDimitry Andric     if (hasAnyVptr(Base.getType(), Context))
4270*0b57cec5SDimitry Andric       return true;
4271*0b57cec5SDimitry Andric 
4272*0b57cec5SDimitry Andric   for (const FieldDecl *Field : RD->fields())
4273*0b57cec5SDimitry Andric     if (hasAnyVptr(Field->getType(), Context))
4274*0b57cec5SDimitry Andric       return true;
4275*0b57cec5SDimitry Andric 
4276*0b57cec5SDimitry Andric   return false;
4277*0b57cec5SDimitry Andric }
4278*0b57cec5SDimitry Andric 
4279*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitLValueForField(LValue base,
4280*0b57cec5SDimitry Andric                                            const FieldDecl *field) {
4281*0b57cec5SDimitry Andric   LValueBaseInfo BaseInfo = base.getBaseInfo();
4282*0b57cec5SDimitry Andric 
4283*0b57cec5SDimitry Andric   if (field->isBitField()) {
4284*0b57cec5SDimitry Andric     const CGRecordLayout &RL =
4285*0b57cec5SDimitry Andric         CGM.getTypes().getCGRecordLayout(field->getParent());
4286*0b57cec5SDimitry Andric     const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
4287e8d8bef9SDimitry Andric     const bool UseVolatile = isAAPCS(CGM.getTarget()) &&
4288e8d8bef9SDimitry Andric                              CGM.getCodeGenOpts().AAPCSBitfieldWidth &&
4289e8d8bef9SDimitry Andric                              Info.VolatileStorageSize != 0 &&
4290e8d8bef9SDimitry Andric                              field->getType()
4291e8d8bef9SDimitry Andric                                  .withCVRQualifiers(base.getVRQualifiers())
4292e8d8bef9SDimitry Andric                                  .isVolatileQualified();
4293480093f4SDimitry Andric     Address Addr = base.getAddress(*this);
4294*0b57cec5SDimitry Andric     unsigned Idx = RL.getLLVMFieldNo(field);
4295480093f4SDimitry Andric     const RecordDecl *rec = field->getParent();
4296e8d8bef9SDimitry Andric     if (!UseVolatile) {
4297480093f4SDimitry Andric       if (!IsInPreservedAIRegion &&
4298480093f4SDimitry Andric           (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
4299*0b57cec5SDimitry Andric         if (Idx != 0)
4300*0b57cec5SDimitry Andric           // For structs, we GEP to the field that the record layout suggests.
4301*0b57cec5SDimitry Andric           Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
4302a7dea167SDimitry Andric       } else {
4303a7dea167SDimitry Andric         llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType(
4304a7dea167SDimitry Andric             getContext().getRecordType(rec), rec->getLocation());
4305e8d8bef9SDimitry Andric         Addr = Builder.CreatePreserveStructAccessIndex(
4306e8d8bef9SDimitry Andric             Addr, Idx, getDebugInfoFIndex(rec, field->getFieldIndex()),
4307a7dea167SDimitry Andric             DbgInfo);
4308a7dea167SDimitry Andric       }
4309e8d8bef9SDimitry Andric     }
4310e8d8bef9SDimitry Andric     const unsigned SS =
4311e8d8bef9SDimitry Andric         UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
4312*0b57cec5SDimitry Andric     // Get the access type.
4313e8d8bef9SDimitry Andric     llvm::Type *FieldIntTy = llvm::Type::getIntNTy(getLLVMContext(), SS);
4314*0b57cec5SDimitry Andric     if (Addr.getElementType() != FieldIntTy)
4315*0b57cec5SDimitry Andric       Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
4316e8d8bef9SDimitry Andric     if (UseVolatile) {
4317e8d8bef9SDimitry Andric       const unsigned VolatileOffset = Info.VolatileStorageOffset.getQuantity();
4318e8d8bef9SDimitry Andric       if (VolatileOffset)
4319e8d8bef9SDimitry Andric         Addr = Builder.CreateConstInBoundsGEP(Addr, VolatileOffset);
4320e8d8bef9SDimitry Andric     }
4321*0b57cec5SDimitry Andric 
4322*0b57cec5SDimitry Andric     QualType fieldType =
4323*0b57cec5SDimitry Andric         field->getType().withCVRQualifiers(base.getVRQualifiers());
4324*0b57cec5SDimitry Andric     // TODO: Support TBAA for bit fields.
4325*0b57cec5SDimitry Andric     LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
4326*0b57cec5SDimitry Andric     return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
4327*0b57cec5SDimitry Andric                                 TBAAAccessInfo());
4328*0b57cec5SDimitry Andric   }
4329*0b57cec5SDimitry Andric 
4330*0b57cec5SDimitry Andric   // Fields of may-alias structures are may-alias themselves.
4331*0b57cec5SDimitry Andric   // FIXME: this should get propagated down through anonymous structs
4332*0b57cec5SDimitry Andric   // and unions.
4333*0b57cec5SDimitry Andric   QualType FieldType = field->getType();
4334*0b57cec5SDimitry Andric   const RecordDecl *rec = field->getParent();
4335*0b57cec5SDimitry Andric   AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
4336*0b57cec5SDimitry Andric   LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
4337*0b57cec5SDimitry Andric   TBAAAccessInfo FieldTBAAInfo;
4338*0b57cec5SDimitry Andric   if (base.getTBAAInfo().isMayAlias() ||
4339*0b57cec5SDimitry Andric           rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
4340*0b57cec5SDimitry Andric     FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
4341*0b57cec5SDimitry Andric   } else if (rec->isUnion()) {
4342*0b57cec5SDimitry Andric     // TODO: Support TBAA for unions.
4343*0b57cec5SDimitry Andric     FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
4344*0b57cec5SDimitry Andric   } else {
4345*0b57cec5SDimitry Andric     // If no base type been assigned for the base access, then try to generate
4346*0b57cec5SDimitry Andric     // one for this base lvalue.
4347*0b57cec5SDimitry Andric     FieldTBAAInfo = base.getTBAAInfo();
4348*0b57cec5SDimitry Andric     if (!FieldTBAAInfo.BaseType) {
4349*0b57cec5SDimitry Andric         FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
4350*0b57cec5SDimitry Andric         assert(!FieldTBAAInfo.Offset &&
4351*0b57cec5SDimitry Andric                "Nonzero offset for an access with no base type!");
4352*0b57cec5SDimitry Andric     }
4353*0b57cec5SDimitry Andric 
4354*0b57cec5SDimitry Andric     // Adjust offset to be relative to the base type.
4355*0b57cec5SDimitry Andric     const ASTRecordLayout &Layout =
4356*0b57cec5SDimitry Andric         getContext().getASTRecordLayout(field->getParent());
4357*0b57cec5SDimitry Andric     unsigned CharWidth = getContext().getCharWidth();
4358*0b57cec5SDimitry Andric     if (FieldTBAAInfo.BaseType)
4359*0b57cec5SDimitry Andric       FieldTBAAInfo.Offset +=
4360*0b57cec5SDimitry Andric           Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
4361*0b57cec5SDimitry Andric 
4362*0b57cec5SDimitry Andric     // Update the final access type and size.
4363*0b57cec5SDimitry Andric     FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
4364*0b57cec5SDimitry Andric     FieldTBAAInfo.Size =
4365*0b57cec5SDimitry Andric         getContext().getTypeSizeInChars(FieldType).getQuantity();
4366*0b57cec5SDimitry Andric   }
4367*0b57cec5SDimitry Andric 
4368480093f4SDimitry Andric   Address addr = base.getAddress(*this);
4369*0b57cec5SDimitry Andric   if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) {
4370*0b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().StrictVTablePointers &&
4371*0b57cec5SDimitry Andric         ClassDef->isDynamicClass()) {
4372*0b57cec5SDimitry Andric       // Getting to any field of dynamic object requires stripping dynamic
4373*0b57cec5SDimitry Andric       // information provided by invariant.group.  This is because accessing
4374*0b57cec5SDimitry Andric       // fields may leak the real address of dynamic object, which could result
4375*0b57cec5SDimitry Andric       // in miscompilation when leaked pointer would be compared.
4376*0b57cec5SDimitry Andric       auto *stripped = Builder.CreateStripInvariantGroup(addr.getPointer());
4377*0b57cec5SDimitry Andric       addr = Address(stripped, addr.getAlignment());
4378*0b57cec5SDimitry Andric     }
4379*0b57cec5SDimitry Andric   }
4380*0b57cec5SDimitry Andric 
4381*0b57cec5SDimitry Andric   unsigned RecordCVR = base.getVRQualifiers();
4382*0b57cec5SDimitry Andric   if (rec->isUnion()) {
4383*0b57cec5SDimitry Andric     // For unions, there is no pointer adjustment.
4384*0b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().StrictVTablePointers &&
4385*0b57cec5SDimitry Andric         hasAnyVptr(FieldType, getContext()))
4386*0b57cec5SDimitry Andric       // Because unions can easily skip invariant.barriers, we need to add
4387*0b57cec5SDimitry Andric       // a barrier every time CXXRecord field with vptr is referenced.
43880eae32dcSDimitry Andric       addr = Builder.CreateLaunderInvariantGroup(addr);
4389*0b57cec5SDimitry Andric 
4390480093f4SDimitry Andric     if (IsInPreservedAIRegion ||
4391480093f4SDimitry Andric         (getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
4392*0b57cec5SDimitry Andric       // Remember the original union field index
43935ffd83dbSDimitry Andric       llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(base.getType(),
43945ffd83dbSDimitry Andric           rec->getLocation());
4395*0b57cec5SDimitry Andric       addr = Address(
4396*0b57cec5SDimitry Andric           Builder.CreatePreserveUnionAccessIndex(
4397*0b57cec5SDimitry Andric               addr.getPointer(), getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo),
4398*0b57cec5SDimitry Andric           addr.getAlignment());
4399*0b57cec5SDimitry Andric     }
4400*0b57cec5SDimitry Andric 
4401a7dea167SDimitry Andric     if (FieldType->isReferenceType())
4402a7dea167SDimitry Andric       addr = Builder.CreateElementBitCast(
4403a7dea167SDimitry Andric           addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
4404a7dea167SDimitry Andric   } else {
4405480093f4SDimitry Andric     if (!IsInPreservedAIRegion &&
4406480093f4SDimitry Andric         (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>()))
4407*0b57cec5SDimitry Andric       // For structs, we GEP to the field that the record layout suggests.
4408*0b57cec5SDimitry Andric       addr = emitAddrOfFieldStorage(*this, addr, field);
4409*0b57cec5SDimitry Andric     else
4410*0b57cec5SDimitry Andric       // Remember the original struct field index
44115ffd83dbSDimitry Andric       addr = emitPreserveStructAccess(*this, base, addr, field);
4412a7dea167SDimitry Andric   }
4413*0b57cec5SDimitry Andric 
4414*0b57cec5SDimitry Andric   // If this is a reference field, load the reference right now.
4415*0b57cec5SDimitry Andric   if (FieldType->isReferenceType()) {
4416a7dea167SDimitry Andric     LValue RefLVal =
4417a7dea167SDimitry Andric         MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
4418*0b57cec5SDimitry Andric     if (RecordCVR & Qualifiers::Volatile)
4419*0b57cec5SDimitry Andric       RefLVal.getQuals().addVolatile();
4420*0b57cec5SDimitry Andric     addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
4421*0b57cec5SDimitry Andric 
4422*0b57cec5SDimitry Andric     // Qualifiers on the struct don't apply to the referencee.
4423*0b57cec5SDimitry Andric     RecordCVR = 0;
4424*0b57cec5SDimitry Andric     FieldType = FieldType->getPointeeType();
4425*0b57cec5SDimitry Andric   }
4426*0b57cec5SDimitry Andric 
4427*0b57cec5SDimitry Andric   // Make sure that the address is pointing to the right type.  This is critical
4428*0b57cec5SDimitry Andric   // for both unions and structs.  A union needs a bitcast, a struct element
4429*0b57cec5SDimitry Andric   // will need a bitcast if the LLVM type laid out doesn't match the desired
4430*0b57cec5SDimitry Andric   // type.
4431*0b57cec5SDimitry Andric   addr = Builder.CreateElementBitCast(
4432*0b57cec5SDimitry Andric       addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
4433*0b57cec5SDimitry Andric 
4434*0b57cec5SDimitry Andric   if (field->hasAttr<AnnotateAttr>())
4435*0b57cec5SDimitry Andric     addr = EmitFieldAnnotations(field, addr);
4436*0b57cec5SDimitry Andric 
4437*0b57cec5SDimitry Andric   LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
4438*0b57cec5SDimitry Andric   LV.getQuals().addCVRQualifiers(RecordCVR);
4439*0b57cec5SDimitry Andric 
4440*0b57cec5SDimitry Andric   // __weak attribute on a field is ignored.
4441*0b57cec5SDimitry Andric   if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
4442*0b57cec5SDimitry Andric     LV.getQuals().removeObjCGCAttr();
4443*0b57cec5SDimitry Andric 
4444*0b57cec5SDimitry Andric   return LV;
4445*0b57cec5SDimitry Andric }
4446*0b57cec5SDimitry Andric 
4447*0b57cec5SDimitry Andric LValue
4448*0b57cec5SDimitry Andric CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
4449*0b57cec5SDimitry Andric                                                   const FieldDecl *Field) {
4450*0b57cec5SDimitry Andric   QualType FieldType = Field->getType();
4451*0b57cec5SDimitry Andric 
4452*0b57cec5SDimitry Andric   if (!FieldType->isReferenceType())
4453*0b57cec5SDimitry Andric     return EmitLValueForField(Base, Field);
4454*0b57cec5SDimitry Andric 
4455480093f4SDimitry Andric   Address V = emitAddrOfFieldStorage(*this, Base.getAddress(*this), Field);
4456*0b57cec5SDimitry Andric 
4457*0b57cec5SDimitry Andric   // Make sure that the address is pointing to the right type.
4458*0b57cec5SDimitry Andric   llvm::Type *llvmType = ConvertTypeForMem(FieldType);
4459*0b57cec5SDimitry Andric   V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
4460*0b57cec5SDimitry Andric 
4461*0b57cec5SDimitry Andric   // TODO: Generate TBAA information that describes this access as a structure
4462*0b57cec5SDimitry Andric   // member access and not just an access to an object of the field's type. This
4463*0b57cec5SDimitry Andric   // should be similar to what we do in EmitLValueForField().
4464*0b57cec5SDimitry Andric   LValueBaseInfo BaseInfo = Base.getBaseInfo();
4465*0b57cec5SDimitry Andric   AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
4466*0b57cec5SDimitry Andric   LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
4467*0b57cec5SDimitry Andric   return MakeAddrLValue(V, FieldType, FieldBaseInfo,
4468*0b57cec5SDimitry Andric                         CGM.getTBAAInfoForSubobject(Base, FieldType));
4469*0b57cec5SDimitry Andric }
4470*0b57cec5SDimitry Andric 
4471*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
4472*0b57cec5SDimitry Andric   if (E->isFileScope()) {
4473*0b57cec5SDimitry Andric     ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
4474*0b57cec5SDimitry Andric     return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
4475*0b57cec5SDimitry Andric   }
4476*0b57cec5SDimitry Andric   if (E->getType()->isVariablyModifiedType())
4477*0b57cec5SDimitry Andric     // make sure to emit the VLA size.
4478*0b57cec5SDimitry Andric     EmitVariablyModifiedType(E->getType());
4479*0b57cec5SDimitry Andric 
4480*0b57cec5SDimitry Andric   Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
4481*0b57cec5SDimitry Andric   const Expr *InitExpr = E->getInitializer();
4482*0b57cec5SDimitry Andric   LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
4483*0b57cec5SDimitry Andric 
4484*0b57cec5SDimitry Andric   EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
4485*0b57cec5SDimitry Andric                    /*Init*/ true);
4486*0b57cec5SDimitry Andric 
44875ffd83dbSDimitry Andric   // Block-scope compound literals are destroyed at the end of the enclosing
44885ffd83dbSDimitry Andric   // scope in C.
44895ffd83dbSDimitry Andric   if (!getLangOpts().CPlusPlus)
44905ffd83dbSDimitry Andric     if (QualType::DestructionKind DtorKind = E->getType().isDestructedType())
44915ffd83dbSDimitry Andric       pushLifetimeExtendedDestroy(getCleanupKind(DtorKind), DeclPtr,
44925ffd83dbSDimitry Andric                                   E->getType(), getDestroyer(DtorKind),
44935ffd83dbSDimitry Andric                                   DtorKind & EHCleanup);
44945ffd83dbSDimitry Andric 
4495*0b57cec5SDimitry Andric   return Result;
4496*0b57cec5SDimitry Andric }
4497*0b57cec5SDimitry Andric 
4498*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
4499*0b57cec5SDimitry Andric   if (!E->isGLValue())
4500*0b57cec5SDimitry Andric     // Initializing an aggregate temporary in C++11: T{...}.
4501*0b57cec5SDimitry Andric     return EmitAggExprToLValue(E);
4502*0b57cec5SDimitry Andric 
4503*0b57cec5SDimitry Andric   // An lvalue initializer list must be initializing a reference.
4504*0b57cec5SDimitry Andric   assert(E->isTransparent() && "non-transparent glvalue init list");
4505*0b57cec5SDimitry Andric   return EmitLValue(E->getInit(0));
4506*0b57cec5SDimitry Andric }
4507*0b57cec5SDimitry Andric 
4508*0b57cec5SDimitry Andric /// Emit the operand of a glvalue conditional operator. This is either a glvalue
4509*0b57cec5SDimitry Andric /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
4510*0b57cec5SDimitry Andric /// LValue is returned and the current block has been terminated.
4511*0b57cec5SDimitry Andric static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
4512*0b57cec5SDimitry Andric                                                     const Expr *Operand) {
4513*0b57cec5SDimitry Andric   if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
4514*0b57cec5SDimitry Andric     CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
4515*0b57cec5SDimitry Andric     return None;
4516*0b57cec5SDimitry Andric   }
4517*0b57cec5SDimitry Andric 
4518*0b57cec5SDimitry Andric   return CGF.EmitLValue(Operand);
4519*0b57cec5SDimitry Andric }
4520*0b57cec5SDimitry Andric 
4521*0b57cec5SDimitry Andric LValue CodeGenFunction::
4522*0b57cec5SDimitry Andric EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
4523*0b57cec5SDimitry Andric   if (!expr->isGLValue()) {
4524*0b57cec5SDimitry Andric     // ?: here should be an aggregate.
4525*0b57cec5SDimitry Andric     assert(hasAggregateEvaluationKind(expr->getType()) &&
4526*0b57cec5SDimitry Andric            "Unexpected conditional operator!");
4527*0b57cec5SDimitry Andric     return EmitAggExprToLValue(expr);
4528*0b57cec5SDimitry Andric   }
4529*0b57cec5SDimitry Andric 
4530*0b57cec5SDimitry Andric   OpaqueValueMapping binding(*this, expr);
4531*0b57cec5SDimitry Andric 
4532*0b57cec5SDimitry Andric   const Expr *condExpr = expr->getCond();
4533*0b57cec5SDimitry Andric   bool CondExprBool;
4534*0b57cec5SDimitry Andric   if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
4535*0b57cec5SDimitry Andric     const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
4536*0b57cec5SDimitry Andric     if (!CondExprBool) std::swap(live, dead);
4537*0b57cec5SDimitry Andric 
4538*0b57cec5SDimitry Andric     if (!ContainsLabel(dead)) {
4539*0b57cec5SDimitry Andric       // If the true case is live, we need to track its region.
4540*0b57cec5SDimitry Andric       if (CondExprBool)
4541*0b57cec5SDimitry Andric         incrementProfileCounter(expr);
45425ffd83dbSDimitry Andric       // If a throw expression we emit it and return an undefined lvalue
45435ffd83dbSDimitry Andric       // because it can't be used.
45445ffd83dbSDimitry Andric       if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(live->IgnoreParens())) {
45455ffd83dbSDimitry Andric         EmitCXXThrowExpr(ThrowExpr);
45460eae32dcSDimitry Andric         llvm::Type *ElemTy = ConvertType(dead->getType());
45470eae32dcSDimitry Andric         llvm::Type *Ty = llvm::PointerType::getUnqual(ElemTy);
45485ffd83dbSDimitry Andric         return MakeAddrLValue(
45490eae32dcSDimitry Andric             Address(llvm::UndefValue::get(Ty), ElemTy, CharUnits::One()),
45505ffd83dbSDimitry Andric             dead->getType());
45515ffd83dbSDimitry Andric       }
4552*0b57cec5SDimitry Andric       return EmitLValue(live);
4553*0b57cec5SDimitry Andric     }
4554*0b57cec5SDimitry Andric   }
4555*0b57cec5SDimitry Andric 
4556*0b57cec5SDimitry Andric   llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
4557*0b57cec5SDimitry Andric   llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
4558*0b57cec5SDimitry Andric   llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
4559*0b57cec5SDimitry Andric 
4560*0b57cec5SDimitry Andric   ConditionalEvaluation eval(*this);
4561*0b57cec5SDimitry Andric   EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
4562*0b57cec5SDimitry Andric 
4563*0b57cec5SDimitry Andric   // Any temporaries created here are conditional.
4564*0b57cec5SDimitry Andric   EmitBlock(lhsBlock);
4565*0b57cec5SDimitry Andric   incrementProfileCounter(expr);
4566*0b57cec5SDimitry Andric   eval.begin(*this);
4567*0b57cec5SDimitry Andric   Optional<LValue> lhs =
4568*0b57cec5SDimitry Andric       EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
4569*0b57cec5SDimitry Andric   eval.end(*this);
4570*0b57cec5SDimitry Andric 
4571*0b57cec5SDimitry Andric   if (lhs && !lhs->isSimple())
4572*0b57cec5SDimitry Andric     return EmitUnsupportedLValue(expr, "conditional operator");
4573*0b57cec5SDimitry Andric 
4574*0b57cec5SDimitry Andric   lhsBlock = Builder.GetInsertBlock();
4575*0b57cec5SDimitry Andric   if (lhs)
4576*0b57cec5SDimitry Andric     Builder.CreateBr(contBlock);
4577*0b57cec5SDimitry Andric 
4578*0b57cec5SDimitry Andric   // Any temporaries created here are conditional.
4579*0b57cec5SDimitry Andric   EmitBlock(rhsBlock);
4580*0b57cec5SDimitry Andric   eval.begin(*this);
4581*0b57cec5SDimitry Andric   Optional<LValue> rhs =
4582*0b57cec5SDimitry Andric       EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
4583*0b57cec5SDimitry Andric   eval.end(*this);
4584*0b57cec5SDimitry Andric   if (rhs && !rhs->isSimple())
4585*0b57cec5SDimitry Andric     return EmitUnsupportedLValue(expr, "conditional operator");
4586*0b57cec5SDimitry Andric   rhsBlock = Builder.GetInsertBlock();
4587*0b57cec5SDimitry Andric 
4588*0b57cec5SDimitry Andric   EmitBlock(contBlock);
4589*0b57cec5SDimitry Andric 
4590*0b57cec5SDimitry Andric   if (lhs && rhs) {
45910eae32dcSDimitry Andric     Address lhsAddr = lhs->getAddress(*this);
45920eae32dcSDimitry Andric     Address rhsAddr = rhs->getAddress(*this);
45930eae32dcSDimitry Andric     llvm::PHINode *phi = Builder.CreatePHI(lhsAddr.getType(), 2, "cond-lvalue");
45940eae32dcSDimitry Andric     phi->addIncoming(lhsAddr.getPointer(), lhsBlock);
45950eae32dcSDimitry Andric     phi->addIncoming(rhsAddr.getPointer(), rhsBlock);
45960eae32dcSDimitry Andric     Address result(phi, lhsAddr.getElementType(),
45970eae32dcSDimitry Andric                    std::min(lhsAddr.getAlignment(), rhsAddr.getAlignment()));
4598*0b57cec5SDimitry Andric     AlignmentSource alignSource =
4599*0b57cec5SDimitry Andric       std::max(lhs->getBaseInfo().getAlignmentSource(),
4600*0b57cec5SDimitry Andric                rhs->getBaseInfo().getAlignmentSource());
4601*0b57cec5SDimitry Andric     TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
4602*0b57cec5SDimitry Andric         lhs->getTBAAInfo(), rhs->getTBAAInfo());
4603*0b57cec5SDimitry Andric     return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
4604*0b57cec5SDimitry Andric                           TBAAInfo);
4605*0b57cec5SDimitry Andric   } else {
4606*0b57cec5SDimitry Andric     assert((lhs || rhs) &&
4607*0b57cec5SDimitry Andric            "both operands of glvalue conditional are throw-expressions?");
4608*0b57cec5SDimitry Andric     return lhs ? *lhs : *rhs;
4609*0b57cec5SDimitry Andric   }
4610*0b57cec5SDimitry Andric }
4611*0b57cec5SDimitry Andric 
4612*0b57cec5SDimitry Andric /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
4613*0b57cec5SDimitry Andric /// type. If the cast is to a reference, we can have the usual lvalue result,
4614*0b57cec5SDimitry Andric /// otherwise if a cast is needed by the code generator in an lvalue context,
4615*0b57cec5SDimitry Andric /// then it must mean that we need the address of an aggregate in order to
4616*0b57cec5SDimitry Andric /// access one of its members.  This can happen for all the reasons that casts
4617*0b57cec5SDimitry Andric /// are permitted with aggregate result, including noop aggregate casts, and
4618*0b57cec5SDimitry Andric /// cast from scalar to union.
4619*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
4620*0b57cec5SDimitry Andric   switch (E->getCastKind()) {
4621*0b57cec5SDimitry Andric   case CK_ToVoid:
4622*0b57cec5SDimitry Andric   case CK_BitCast:
4623*0b57cec5SDimitry Andric   case CK_LValueToRValueBitCast:
4624*0b57cec5SDimitry Andric   case CK_ArrayToPointerDecay:
4625*0b57cec5SDimitry Andric   case CK_FunctionToPointerDecay:
4626*0b57cec5SDimitry Andric   case CK_NullToMemberPointer:
4627*0b57cec5SDimitry Andric   case CK_NullToPointer:
4628*0b57cec5SDimitry Andric   case CK_IntegralToPointer:
4629*0b57cec5SDimitry Andric   case CK_PointerToIntegral:
4630*0b57cec5SDimitry Andric   case CK_PointerToBoolean:
4631*0b57cec5SDimitry Andric   case CK_VectorSplat:
4632*0b57cec5SDimitry Andric   case CK_IntegralCast:
4633*0b57cec5SDimitry Andric   case CK_BooleanToSignedIntegral:
4634*0b57cec5SDimitry Andric   case CK_IntegralToBoolean:
4635*0b57cec5SDimitry Andric   case CK_IntegralToFloating:
4636*0b57cec5SDimitry Andric   case CK_FloatingToIntegral:
4637*0b57cec5SDimitry Andric   case CK_FloatingToBoolean:
4638*0b57cec5SDimitry Andric   case CK_FloatingCast:
4639*0b57cec5SDimitry Andric   case CK_FloatingRealToComplex:
4640*0b57cec5SDimitry Andric   case CK_FloatingComplexToReal:
4641*0b57cec5SDimitry Andric   case CK_FloatingComplexToBoolean:
4642*0b57cec5SDimitry Andric   case CK_FloatingComplexCast:
4643*0b57cec5SDimitry Andric   case CK_FloatingComplexToIntegralComplex:
4644*0b57cec5SDimitry Andric   case CK_IntegralRealToComplex:
4645*0b57cec5SDimitry Andric   case CK_IntegralComplexToReal:
4646*0b57cec5SDimitry Andric   case CK_IntegralComplexToBoolean:
4647*0b57cec5SDimitry Andric   case CK_IntegralComplexCast:
4648*0b57cec5SDimitry Andric   case CK_IntegralComplexToFloatingComplex:
4649*0b57cec5SDimitry Andric   case CK_DerivedToBaseMemberPointer:
4650*0b57cec5SDimitry Andric   case CK_BaseToDerivedMemberPointer:
4651*0b57cec5SDimitry Andric   case CK_MemberPointerToBoolean:
4652*0b57cec5SDimitry Andric   case CK_ReinterpretMemberPointer:
4653*0b57cec5SDimitry Andric   case CK_AnyPointerToBlockPointerCast:
4654*0b57cec5SDimitry Andric   case CK_ARCProduceObject:
4655*0b57cec5SDimitry Andric   case CK_ARCConsumeObject:
4656*0b57cec5SDimitry Andric   case CK_ARCReclaimReturnedObject:
4657*0b57cec5SDimitry Andric   case CK_ARCExtendBlockObject:
4658*0b57cec5SDimitry Andric   case CK_CopyAndAutoreleaseBlockObject:
4659*0b57cec5SDimitry Andric   case CK_IntToOCLSampler:
4660e8d8bef9SDimitry Andric   case CK_FloatingToFixedPoint:
4661e8d8bef9SDimitry Andric   case CK_FixedPointToFloating:
4662*0b57cec5SDimitry Andric   case CK_FixedPointCast:
4663*0b57cec5SDimitry Andric   case CK_FixedPointToBoolean:
4664*0b57cec5SDimitry Andric   case CK_FixedPointToIntegral:
4665*0b57cec5SDimitry Andric   case CK_IntegralToFixedPoint:
4666fe6060f1SDimitry Andric   case CK_MatrixCast:
4667*0b57cec5SDimitry Andric     return EmitUnsupportedLValue(E, "unexpected cast lvalue");
4668*0b57cec5SDimitry Andric 
4669*0b57cec5SDimitry Andric   case CK_Dependent:
4670*0b57cec5SDimitry Andric     llvm_unreachable("dependent cast kind in IR gen!");
4671*0b57cec5SDimitry Andric 
4672*0b57cec5SDimitry Andric   case CK_BuiltinFnToFnPtr:
4673*0b57cec5SDimitry Andric     llvm_unreachable("builtin functions are handled elsewhere");
4674*0b57cec5SDimitry Andric 
4675*0b57cec5SDimitry Andric   // These are never l-values; just use the aggregate emission code.
4676*0b57cec5SDimitry Andric   case CK_NonAtomicToAtomic:
4677*0b57cec5SDimitry Andric   case CK_AtomicToNonAtomic:
4678*0b57cec5SDimitry Andric     return EmitAggExprToLValue(E);
4679*0b57cec5SDimitry Andric 
4680*0b57cec5SDimitry Andric   case CK_Dynamic: {
4681*0b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
4682480093f4SDimitry Andric     Address V = LV.getAddress(*this);
4683*0b57cec5SDimitry Andric     const auto *DCE = cast<CXXDynamicCastExpr>(E);
4684*0b57cec5SDimitry Andric     return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
4685*0b57cec5SDimitry Andric   }
4686*0b57cec5SDimitry Andric 
4687*0b57cec5SDimitry Andric   case CK_ConstructorConversion:
4688*0b57cec5SDimitry Andric   case CK_UserDefinedConversion:
4689*0b57cec5SDimitry Andric   case CK_CPointerToObjCPointerCast:
4690*0b57cec5SDimitry Andric   case CK_BlockPointerToObjCPointerCast:
4691*0b57cec5SDimitry Andric   case CK_LValueToRValue:
4692*0b57cec5SDimitry Andric     return EmitLValue(E->getSubExpr());
4693*0b57cec5SDimitry Andric 
4694349cc55cSDimitry Andric   case CK_NoOp: {
4695349cc55cSDimitry Andric     // CK_NoOp can model a qualification conversion, which can remove an array
4696349cc55cSDimitry Andric     // bound and change the IR type.
4697349cc55cSDimitry Andric     // FIXME: Once pointee types are removed from IR, remove this.
4698349cc55cSDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
4699349cc55cSDimitry Andric     if (LV.isSimple()) {
4700349cc55cSDimitry Andric       Address V = LV.getAddress(*this);
4701349cc55cSDimitry Andric       if (V.isValid()) {
4702349cc55cSDimitry Andric         llvm::Type *T =
4703349cc55cSDimitry Andric             ConvertTypeForMem(E->getType())
4704349cc55cSDimitry Andric                 ->getPointerTo(
4705349cc55cSDimitry Andric                     cast<llvm::PointerType>(V.getType())->getAddressSpace());
4706349cc55cSDimitry Andric         if (V.getType() != T)
4707349cc55cSDimitry Andric           LV.setAddress(Builder.CreateBitCast(V, T));
4708349cc55cSDimitry Andric       }
4709349cc55cSDimitry Andric     }
4710349cc55cSDimitry Andric     return LV;
4711349cc55cSDimitry Andric   }
4712349cc55cSDimitry Andric 
4713*0b57cec5SDimitry Andric   case CK_UncheckedDerivedToBase:
4714*0b57cec5SDimitry Andric   case CK_DerivedToBase: {
4715480093f4SDimitry Andric     const auto *DerivedClassTy =
4716480093f4SDimitry Andric         E->getSubExpr()->getType()->castAs<RecordType>();
4717*0b57cec5SDimitry Andric     auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
4718*0b57cec5SDimitry Andric 
4719*0b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
4720480093f4SDimitry Andric     Address This = LV.getAddress(*this);
4721*0b57cec5SDimitry Andric 
4722*0b57cec5SDimitry Andric     // Perform the derived-to-base conversion
4723*0b57cec5SDimitry Andric     Address Base = GetAddressOfBaseClass(
4724*0b57cec5SDimitry Andric         This, DerivedClassDecl, E->path_begin(), E->path_end(),
4725*0b57cec5SDimitry Andric         /*NullCheckValue=*/false, E->getExprLoc());
4726*0b57cec5SDimitry Andric 
4727*0b57cec5SDimitry Andric     // TODO: Support accesses to members of base classes in TBAA. For now, we
4728*0b57cec5SDimitry Andric     // conservatively pretend that the complete object is of the base class
4729*0b57cec5SDimitry Andric     // type.
4730*0b57cec5SDimitry Andric     return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
4731*0b57cec5SDimitry Andric                           CGM.getTBAAInfoForSubobject(LV, E->getType()));
4732*0b57cec5SDimitry Andric   }
4733*0b57cec5SDimitry Andric   case CK_ToUnion:
4734*0b57cec5SDimitry Andric     return EmitAggExprToLValue(E);
4735*0b57cec5SDimitry Andric   case CK_BaseToDerived: {
4736480093f4SDimitry Andric     const auto *DerivedClassTy = E->getType()->castAs<RecordType>();
4737*0b57cec5SDimitry Andric     auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
4738*0b57cec5SDimitry Andric 
4739*0b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
4740*0b57cec5SDimitry Andric 
4741*0b57cec5SDimitry Andric     // Perform the base-to-derived conversion
4742480093f4SDimitry Andric     Address Derived = GetAddressOfDerivedClass(
4743480093f4SDimitry Andric         LV.getAddress(*this), DerivedClassDecl, E->path_begin(), E->path_end(),
4744*0b57cec5SDimitry Andric         /*NullCheckValue=*/false);
4745*0b57cec5SDimitry Andric 
4746*0b57cec5SDimitry Andric     // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
4747*0b57cec5SDimitry Andric     // performed and the object is not of the derived type.
4748*0b57cec5SDimitry Andric     if (sanitizePerformTypeCheck())
4749*0b57cec5SDimitry Andric       EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
4750*0b57cec5SDimitry Andric                     Derived.getPointer(), E->getType());
4751*0b57cec5SDimitry Andric 
4752*0b57cec5SDimitry Andric     if (SanOpts.has(SanitizerKind::CFIDerivedCast))
4753*0b57cec5SDimitry Andric       EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
4754*0b57cec5SDimitry Andric                                 /*MayBeNull=*/false, CFITCK_DerivedCast,
4755*0b57cec5SDimitry Andric                                 E->getBeginLoc());
4756*0b57cec5SDimitry Andric 
4757*0b57cec5SDimitry Andric     return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
4758*0b57cec5SDimitry Andric                           CGM.getTBAAInfoForSubobject(LV, E->getType()));
4759*0b57cec5SDimitry Andric   }
4760*0b57cec5SDimitry Andric   case CK_LValueBitCast: {
4761*0b57cec5SDimitry Andric     // This must be a reinterpret_cast (or c-style equivalent).
4762*0b57cec5SDimitry Andric     const auto *CE = cast<ExplicitCastExpr>(E);
4763*0b57cec5SDimitry Andric 
4764*0b57cec5SDimitry Andric     CGM.EmitExplicitCastExprType(CE, this);
4765*0b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
4766480093f4SDimitry Andric     Address V = Builder.CreateBitCast(LV.getAddress(*this),
4767*0b57cec5SDimitry Andric                                       ConvertType(CE->getTypeAsWritten()));
4768*0b57cec5SDimitry Andric 
4769*0b57cec5SDimitry Andric     if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
4770*0b57cec5SDimitry Andric       EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
4771*0b57cec5SDimitry Andric                                 /*MayBeNull=*/false, CFITCK_UnrelatedCast,
4772*0b57cec5SDimitry Andric                                 E->getBeginLoc());
4773*0b57cec5SDimitry Andric 
4774*0b57cec5SDimitry Andric     return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
4775*0b57cec5SDimitry Andric                           CGM.getTBAAInfoForSubobject(LV, E->getType()));
4776*0b57cec5SDimitry Andric   }
4777*0b57cec5SDimitry Andric   case CK_AddressSpaceConversion: {
4778*0b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
4779*0b57cec5SDimitry Andric     QualType DestTy = getContext().getPointerType(E->getType());
4780*0b57cec5SDimitry Andric     llvm::Value *V = getTargetHooks().performAddrSpaceCast(
4781480093f4SDimitry Andric         *this, LV.getPointer(*this),
4782480093f4SDimitry Andric         E->getSubExpr()->getType().getAddressSpace(),
4783*0b57cec5SDimitry Andric         E->getType().getAddressSpace(), ConvertType(DestTy));
4784480093f4SDimitry Andric     return MakeAddrLValue(Address(V, LV.getAddress(*this).getAlignment()),
4785*0b57cec5SDimitry Andric                           E->getType(), LV.getBaseInfo(), LV.getTBAAInfo());
4786*0b57cec5SDimitry Andric   }
4787*0b57cec5SDimitry Andric   case CK_ObjCObjectLValueCast: {
4788*0b57cec5SDimitry Andric     LValue LV = EmitLValue(E->getSubExpr());
4789480093f4SDimitry Andric     Address V = Builder.CreateElementBitCast(LV.getAddress(*this),
4790*0b57cec5SDimitry Andric                                              ConvertType(E->getType()));
4791*0b57cec5SDimitry Andric     return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
4792*0b57cec5SDimitry Andric                           CGM.getTBAAInfoForSubobject(LV, E->getType()));
4793*0b57cec5SDimitry Andric   }
4794*0b57cec5SDimitry Andric   case CK_ZeroToOCLOpaqueType:
4795*0b57cec5SDimitry Andric     llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
4796*0b57cec5SDimitry Andric   }
4797*0b57cec5SDimitry Andric 
4798*0b57cec5SDimitry Andric   llvm_unreachable("Unhandled lvalue cast kind?");
4799*0b57cec5SDimitry Andric }
4800*0b57cec5SDimitry Andric 
4801*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
4802*0b57cec5SDimitry Andric   assert(OpaqueValueMappingData::shouldBindAsLValue(e));
4803*0b57cec5SDimitry Andric   return getOrCreateOpaqueLValueMapping(e);
4804*0b57cec5SDimitry Andric }
4805*0b57cec5SDimitry Andric 
4806*0b57cec5SDimitry Andric LValue
4807*0b57cec5SDimitry Andric CodeGenFunction::getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e) {
4808*0b57cec5SDimitry Andric   assert(OpaqueValueMapping::shouldBindAsLValue(e));
4809*0b57cec5SDimitry Andric 
4810*0b57cec5SDimitry Andric   llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
4811*0b57cec5SDimitry Andric       it = OpaqueLValues.find(e);
4812*0b57cec5SDimitry Andric 
4813*0b57cec5SDimitry Andric   if (it != OpaqueLValues.end())
4814*0b57cec5SDimitry Andric     return it->second;
4815*0b57cec5SDimitry Andric 
4816*0b57cec5SDimitry Andric   assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
4817*0b57cec5SDimitry Andric   return EmitLValue(e->getSourceExpr());
4818*0b57cec5SDimitry Andric }
4819*0b57cec5SDimitry Andric 
4820*0b57cec5SDimitry Andric RValue
4821*0b57cec5SDimitry Andric CodeGenFunction::getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e) {
4822*0b57cec5SDimitry Andric   assert(!OpaqueValueMapping::shouldBindAsLValue(e));
4823*0b57cec5SDimitry Andric 
4824*0b57cec5SDimitry Andric   llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
4825*0b57cec5SDimitry Andric       it = OpaqueRValues.find(e);
4826*0b57cec5SDimitry Andric 
4827*0b57cec5SDimitry Andric   if (it != OpaqueRValues.end())
4828*0b57cec5SDimitry Andric     return it->second;
4829*0b57cec5SDimitry Andric 
4830*0b57cec5SDimitry Andric   assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
4831*0b57cec5SDimitry Andric   return EmitAnyExpr(e->getSourceExpr());
4832*0b57cec5SDimitry Andric }
4833*0b57cec5SDimitry Andric 
4834*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitRValueForField(LValue LV,
4835*0b57cec5SDimitry Andric                                            const FieldDecl *FD,
4836*0b57cec5SDimitry Andric                                            SourceLocation Loc) {
4837*0b57cec5SDimitry Andric   QualType FT = FD->getType();
4838*0b57cec5SDimitry Andric   LValue FieldLV = EmitLValueForField(LV, FD);
4839*0b57cec5SDimitry Andric   switch (getEvaluationKind(FT)) {
4840*0b57cec5SDimitry Andric   case TEK_Complex:
4841*0b57cec5SDimitry Andric     return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
4842*0b57cec5SDimitry Andric   case TEK_Aggregate:
4843480093f4SDimitry Andric     return FieldLV.asAggregateRValue(*this);
4844*0b57cec5SDimitry Andric   case TEK_Scalar:
4845*0b57cec5SDimitry Andric     // This routine is used to load fields one-by-one to perform a copy, so
4846*0b57cec5SDimitry Andric     // don't load reference fields.
4847*0b57cec5SDimitry Andric     if (FD->getType()->isReferenceType())
4848480093f4SDimitry Andric       return RValue::get(FieldLV.getPointer(*this));
4849480093f4SDimitry Andric     // Call EmitLoadOfScalar except when the lvalue is a bitfield to emit a
4850480093f4SDimitry Andric     // primitive load.
4851480093f4SDimitry Andric     if (FieldLV.isBitField())
4852*0b57cec5SDimitry Andric       return EmitLoadOfLValue(FieldLV, Loc);
4853480093f4SDimitry Andric     return RValue::get(EmitLoadOfScalar(FieldLV, Loc));
4854*0b57cec5SDimitry Andric   }
4855*0b57cec5SDimitry Andric   llvm_unreachable("bad evaluation kind");
4856*0b57cec5SDimitry Andric }
4857*0b57cec5SDimitry Andric 
4858*0b57cec5SDimitry Andric //===--------------------------------------------------------------------===//
4859*0b57cec5SDimitry Andric //                             Expression Emission
4860*0b57cec5SDimitry Andric //===--------------------------------------------------------------------===//
4861*0b57cec5SDimitry Andric 
4862*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
4863*0b57cec5SDimitry Andric                                      ReturnValueSlot ReturnValue) {
4864*0b57cec5SDimitry Andric   // Builtins never have block type.
4865*0b57cec5SDimitry Andric   if (E->getCallee()->getType()->isBlockPointerType())
4866*0b57cec5SDimitry Andric     return EmitBlockCallExpr(E, ReturnValue);
4867*0b57cec5SDimitry Andric 
4868*0b57cec5SDimitry Andric   if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
4869*0b57cec5SDimitry Andric     return EmitCXXMemberCallExpr(CE, ReturnValue);
4870*0b57cec5SDimitry Andric 
4871*0b57cec5SDimitry Andric   if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
4872*0b57cec5SDimitry Andric     return EmitCUDAKernelCallExpr(CE, ReturnValue);
4873*0b57cec5SDimitry Andric 
4874*0b57cec5SDimitry Andric   if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
4875*0b57cec5SDimitry Andric     if (const CXXMethodDecl *MD =
4876*0b57cec5SDimitry Andric           dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
4877*0b57cec5SDimitry Andric       return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
4878*0b57cec5SDimitry Andric 
4879*0b57cec5SDimitry Andric   CGCallee callee = EmitCallee(E->getCallee());
4880*0b57cec5SDimitry Andric 
4881*0b57cec5SDimitry Andric   if (callee.isBuiltin()) {
4882*0b57cec5SDimitry Andric     return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
4883*0b57cec5SDimitry Andric                            E, ReturnValue);
4884*0b57cec5SDimitry Andric   }
4885*0b57cec5SDimitry Andric 
4886*0b57cec5SDimitry Andric   if (callee.isPseudoDestructor()) {
4887*0b57cec5SDimitry Andric     return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
4888*0b57cec5SDimitry Andric   }
4889*0b57cec5SDimitry Andric 
4890*0b57cec5SDimitry Andric   return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
4891*0b57cec5SDimitry Andric }
4892*0b57cec5SDimitry Andric 
4893*0b57cec5SDimitry Andric /// Emit a CallExpr without considering whether it might be a subclass.
4894*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
4895*0b57cec5SDimitry Andric                                            ReturnValueSlot ReturnValue) {
4896*0b57cec5SDimitry Andric   CGCallee Callee = EmitCallee(E->getCallee());
4897*0b57cec5SDimitry Andric   return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
4898*0b57cec5SDimitry Andric }
4899*0b57cec5SDimitry Andric 
49005ffd83dbSDimitry Andric static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD) {
49015ffd83dbSDimitry Andric   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
4902480093f4SDimitry Andric 
4903*0b57cec5SDimitry Andric   if (auto builtinID = FD->getBuiltinID()) {
4904349cc55cSDimitry Andric     std::string FDInlineName = (FD->getName() + ".inline").str();
4905349cc55cSDimitry Andric     // When directing calling an inline builtin, call it through it's mangled
4906349cc55cSDimitry Andric     // name to make it clear it's not the actual builtin.
4907349cc55cSDimitry Andric     if (FD->isInlineBuiltinDeclaration() &&
4908349cc55cSDimitry Andric         CGF.CurFn->getName() != FDInlineName) {
4909349cc55cSDimitry Andric       llvm::Constant *CalleePtr = EmitFunctionDeclPointer(CGF.CGM, GD);
4910349cc55cSDimitry Andric       llvm::Function *Fn = llvm::cast<llvm::Function>(CalleePtr);
4911349cc55cSDimitry Andric       llvm::Module *M = Fn->getParent();
4912349cc55cSDimitry Andric       llvm::Function *Clone = M->getFunction(FDInlineName);
4913349cc55cSDimitry Andric       if (!Clone) {
4914349cc55cSDimitry Andric         Clone = llvm::Function::Create(Fn->getFunctionType(),
4915349cc55cSDimitry Andric                                        llvm::GlobalValue::InternalLinkage,
4916349cc55cSDimitry Andric                                        Fn->getAddressSpace(), FDInlineName, M);
4917349cc55cSDimitry Andric         Clone->addFnAttr(llvm::Attribute::AlwaysInline);
4918349cc55cSDimitry Andric       }
4919349cc55cSDimitry Andric       return CGCallee::forDirect(Clone, GD);
4920349cc55cSDimitry Andric     }
4921349cc55cSDimitry Andric 
4922349cc55cSDimitry Andric     // Replaceable builtins provide their own implementation of a builtin. If we
4923349cc55cSDimitry Andric     // are in an inline builtin implementation, avoid trivial infinite
4924480093f4SDimitry Andric     // recursion.
4925349cc55cSDimitry Andric     else
4926*0b57cec5SDimitry Andric       return CGCallee::forBuiltin(builtinID, FD);
4927*0b57cec5SDimitry Andric   }
4928*0b57cec5SDimitry Andric 
4929fe6060f1SDimitry Andric   llvm::Constant *CalleePtr = EmitFunctionDeclPointer(CGF.CGM, GD);
4930fe6060f1SDimitry Andric   if (CGF.CGM.getLangOpts().CUDA && !CGF.CGM.getLangOpts().CUDAIsDevice &&
4931fe6060f1SDimitry Andric       FD->hasAttr<CUDAGlobalAttr>())
4932fe6060f1SDimitry Andric     CalleePtr = CGF.CGM.getCUDARuntime().getKernelStub(
4933fe6060f1SDimitry Andric         cast<llvm::GlobalValue>(CalleePtr->stripPointerCasts()));
4934349cc55cSDimitry Andric 
4935fe6060f1SDimitry Andric   return CGCallee::forDirect(CalleePtr, GD);
4936*0b57cec5SDimitry Andric }
4937*0b57cec5SDimitry Andric 
4938*0b57cec5SDimitry Andric CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
4939*0b57cec5SDimitry Andric   E = E->IgnoreParens();
4940*0b57cec5SDimitry Andric 
4941*0b57cec5SDimitry Andric   // Look through function-to-pointer decay.
4942*0b57cec5SDimitry Andric   if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
4943*0b57cec5SDimitry Andric     if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
4944*0b57cec5SDimitry Andric         ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
4945*0b57cec5SDimitry Andric       return EmitCallee(ICE->getSubExpr());
4946*0b57cec5SDimitry Andric     }
4947*0b57cec5SDimitry Andric 
4948*0b57cec5SDimitry Andric   // Resolve direct calls.
4949*0b57cec5SDimitry Andric   } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
4950*0b57cec5SDimitry Andric     if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
4951*0b57cec5SDimitry Andric       return EmitDirectCallee(*this, FD);
4952*0b57cec5SDimitry Andric     }
4953*0b57cec5SDimitry Andric   } else if (auto ME = dyn_cast<MemberExpr>(E)) {
4954*0b57cec5SDimitry Andric     if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
4955*0b57cec5SDimitry Andric       EmitIgnoredExpr(ME->getBase());
4956*0b57cec5SDimitry Andric       return EmitDirectCallee(*this, FD);
4957*0b57cec5SDimitry Andric     }
4958*0b57cec5SDimitry Andric 
4959*0b57cec5SDimitry Andric   // Look through template substitutions.
4960*0b57cec5SDimitry Andric   } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4961*0b57cec5SDimitry Andric     return EmitCallee(NTTP->getReplacement());
4962*0b57cec5SDimitry Andric 
4963*0b57cec5SDimitry Andric   // Treat pseudo-destructor calls differently.
4964*0b57cec5SDimitry Andric   } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4965*0b57cec5SDimitry Andric     return CGCallee::forPseudoDestructor(PDE);
4966*0b57cec5SDimitry Andric   }
4967*0b57cec5SDimitry Andric 
4968*0b57cec5SDimitry Andric   // Otherwise, we have an indirect reference.
4969*0b57cec5SDimitry Andric   llvm::Value *calleePtr;
4970*0b57cec5SDimitry Andric   QualType functionType;
4971*0b57cec5SDimitry Andric   if (auto ptrType = E->getType()->getAs<PointerType>()) {
4972*0b57cec5SDimitry Andric     calleePtr = EmitScalarExpr(E);
4973*0b57cec5SDimitry Andric     functionType = ptrType->getPointeeType();
4974*0b57cec5SDimitry Andric   } else {
4975*0b57cec5SDimitry Andric     functionType = E->getType();
4976480093f4SDimitry Andric     calleePtr = EmitLValue(E).getPointer(*this);
4977*0b57cec5SDimitry Andric   }
4978*0b57cec5SDimitry Andric   assert(functionType->isFunctionType());
4979*0b57cec5SDimitry Andric 
4980*0b57cec5SDimitry Andric   GlobalDecl GD;
4981*0b57cec5SDimitry Andric   if (const auto *VD =
4982*0b57cec5SDimitry Andric           dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee()))
4983*0b57cec5SDimitry Andric     GD = GlobalDecl(VD);
4984*0b57cec5SDimitry Andric 
4985*0b57cec5SDimitry Andric   CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD);
4986*0b57cec5SDimitry Andric   CGCallee callee(calleeInfo, calleePtr);
4987*0b57cec5SDimitry Andric   return callee;
4988*0b57cec5SDimitry Andric }
4989*0b57cec5SDimitry Andric 
4990*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
4991*0b57cec5SDimitry Andric   // Comma expressions just emit their LHS then their RHS as an l-value.
4992*0b57cec5SDimitry Andric   if (E->getOpcode() == BO_Comma) {
4993*0b57cec5SDimitry Andric     EmitIgnoredExpr(E->getLHS());
4994*0b57cec5SDimitry Andric     EnsureInsertPoint();
4995*0b57cec5SDimitry Andric     return EmitLValue(E->getRHS());
4996*0b57cec5SDimitry Andric   }
4997*0b57cec5SDimitry Andric 
4998*0b57cec5SDimitry Andric   if (E->getOpcode() == BO_PtrMemD ||
4999*0b57cec5SDimitry Andric       E->getOpcode() == BO_PtrMemI)
5000*0b57cec5SDimitry Andric     return EmitPointerToDataMemberBinaryExpr(E);
5001*0b57cec5SDimitry Andric 
5002*0b57cec5SDimitry Andric   assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
5003*0b57cec5SDimitry Andric 
5004*0b57cec5SDimitry Andric   // Note that in all of these cases, __block variables need the RHS
5005*0b57cec5SDimitry Andric   // evaluated first just in case the variable gets moved by the RHS.
5006*0b57cec5SDimitry Andric 
5007*0b57cec5SDimitry Andric   switch (getEvaluationKind(E->getType())) {
5008*0b57cec5SDimitry Andric   case TEK_Scalar: {
5009*0b57cec5SDimitry Andric     switch (E->getLHS()->getType().getObjCLifetime()) {
5010*0b57cec5SDimitry Andric     case Qualifiers::OCL_Strong:
5011*0b57cec5SDimitry Andric       return EmitARCStoreStrong(E, /*ignored*/ false).first;
5012*0b57cec5SDimitry Andric 
5013*0b57cec5SDimitry Andric     case Qualifiers::OCL_Autoreleasing:
5014*0b57cec5SDimitry Andric       return EmitARCStoreAutoreleasing(E).first;
5015*0b57cec5SDimitry Andric 
5016*0b57cec5SDimitry Andric     // No reason to do any of these differently.
5017*0b57cec5SDimitry Andric     case Qualifiers::OCL_None:
5018*0b57cec5SDimitry Andric     case Qualifiers::OCL_ExplicitNone:
5019*0b57cec5SDimitry Andric     case Qualifiers::OCL_Weak:
5020*0b57cec5SDimitry Andric       break;
5021*0b57cec5SDimitry Andric     }
5022*0b57cec5SDimitry Andric 
5023*0b57cec5SDimitry Andric     RValue RV = EmitAnyExpr(E->getRHS());
5024*0b57cec5SDimitry Andric     LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
5025*0b57cec5SDimitry Andric     if (RV.isScalar())
5026*0b57cec5SDimitry Andric       EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
5027*0b57cec5SDimitry Andric     EmitStoreThroughLValue(RV, LV);
5028480093f4SDimitry Andric     if (getLangOpts().OpenMP)
5029480093f4SDimitry Andric       CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
5030480093f4SDimitry Andric                                                                 E->getLHS());
5031*0b57cec5SDimitry Andric     return LV;
5032*0b57cec5SDimitry Andric   }
5033*0b57cec5SDimitry Andric 
5034*0b57cec5SDimitry Andric   case TEK_Complex:
5035*0b57cec5SDimitry Andric     return EmitComplexAssignmentLValue(E);
5036*0b57cec5SDimitry Andric 
5037*0b57cec5SDimitry Andric   case TEK_Aggregate:
5038*0b57cec5SDimitry Andric     return EmitAggExprToLValue(E);
5039*0b57cec5SDimitry Andric   }
5040*0b57cec5SDimitry Andric   llvm_unreachable("bad evaluation kind");
5041*0b57cec5SDimitry Andric }
5042*0b57cec5SDimitry Andric 
5043*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
5044*0b57cec5SDimitry Andric   RValue RV = EmitCallExpr(E);
5045*0b57cec5SDimitry Andric 
5046*0b57cec5SDimitry Andric   if (!RV.isScalar())
5047*0b57cec5SDimitry Andric     return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
5048*0b57cec5SDimitry Andric                           AlignmentSource::Decl);
5049*0b57cec5SDimitry Andric 
5050*0b57cec5SDimitry Andric   assert(E->getCallReturnType(getContext())->isReferenceType() &&
5051*0b57cec5SDimitry Andric          "Can't have a scalar return unless the return type is a "
5052*0b57cec5SDimitry Andric          "reference type!");
5053*0b57cec5SDimitry Andric 
5054*0b57cec5SDimitry Andric   return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
5055*0b57cec5SDimitry Andric }
5056*0b57cec5SDimitry Andric 
5057*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
5058*0b57cec5SDimitry Andric   // FIXME: This shouldn't require another copy.
5059*0b57cec5SDimitry Andric   return EmitAggExprToLValue(E);
5060*0b57cec5SDimitry Andric }
5061*0b57cec5SDimitry Andric 
5062*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
5063*0b57cec5SDimitry Andric   assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
5064*0b57cec5SDimitry Andric          && "binding l-value to type which needs a temporary");
5065*0b57cec5SDimitry Andric   AggValueSlot Slot = CreateAggTemp(E->getType());
5066*0b57cec5SDimitry Andric   EmitCXXConstructExpr(E, Slot);
5067*0b57cec5SDimitry Andric   return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
5068*0b57cec5SDimitry Andric }
5069*0b57cec5SDimitry Andric 
5070*0b57cec5SDimitry Andric LValue
5071*0b57cec5SDimitry Andric CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
5072*0b57cec5SDimitry Andric   return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
5073*0b57cec5SDimitry Andric }
5074*0b57cec5SDimitry Andric 
5075*0b57cec5SDimitry Andric Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
50765ffd83dbSDimitry Andric   return Builder.CreateElementBitCast(CGM.GetAddrOfMSGuidDecl(E->getGuidDecl()),
5077*0b57cec5SDimitry Andric                                       ConvertType(E->getType()));
5078*0b57cec5SDimitry Andric }
5079*0b57cec5SDimitry Andric 
5080*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
5081*0b57cec5SDimitry Andric   return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
5082*0b57cec5SDimitry Andric                         AlignmentSource::Decl);
5083*0b57cec5SDimitry Andric }
5084*0b57cec5SDimitry Andric 
5085*0b57cec5SDimitry Andric LValue
5086*0b57cec5SDimitry Andric CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
5087*0b57cec5SDimitry Andric   AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
5088*0b57cec5SDimitry Andric   Slot.setExternallyDestructed();
5089*0b57cec5SDimitry Andric   EmitAggExpr(E->getSubExpr(), Slot);
5090*0b57cec5SDimitry Andric   EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
5091*0b57cec5SDimitry Andric   return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
5092*0b57cec5SDimitry Andric }
5093*0b57cec5SDimitry Andric 
5094*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
5095*0b57cec5SDimitry Andric   RValue RV = EmitObjCMessageExpr(E);
5096*0b57cec5SDimitry Andric 
5097*0b57cec5SDimitry Andric   if (!RV.isScalar())
5098*0b57cec5SDimitry Andric     return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
5099*0b57cec5SDimitry Andric                           AlignmentSource::Decl);
5100*0b57cec5SDimitry Andric 
5101*0b57cec5SDimitry Andric   assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
5102*0b57cec5SDimitry Andric          "Can't have a scalar return unless the return type is a "
5103*0b57cec5SDimitry Andric          "reference type!");
5104*0b57cec5SDimitry Andric 
5105*0b57cec5SDimitry Andric   return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
5106*0b57cec5SDimitry Andric }
5107*0b57cec5SDimitry Andric 
5108*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
5109*0b57cec5SDimitry Andric   Address V =
5110*0b57cec5SDimitry Andric     CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
5111*0b57cec5SDimitry Andric   return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
5112*0b57cec5SDimitry Andric }
5113*0b57cec5SDimitry Andric 
5114*0b57cec5SDimitry Andric llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
5115*0b57cec5SDimitry Andric                                              const ObjCIvarDecl *Ivar) {
5116*0b57cec5SDimitry Andric   return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
5117*0b57cec5SDimitry Andric }
5118*0b57cec5SDimitry Andric 
5119*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
5120*0b57cec5SDimitry Andric                                           llvm::Value *BaseValue,
5121*0b57cec5SDimitry Andric                                           const ObjCIvarDecl *Ivar,
5122*0b57cec5SDimitry Andric                                           unsigned CVRQualifiers) {
5123*0b57cec5SDimitry Andric   return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
5124*0b57cec5SDimitry Andric                                                    Ivar, CVRQualifiers);
5125*0b57cec5SDimitry Andric }
5126*0b57cec5SDimitry Andric 
5127*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
5128*0b57cec5SDimitry Andric   // FIXME: A lot of the code below could be shared with EmitMemberExpr.
5129*0b57cec5SDimitry Andric   llvm::Value *BaseValue = nullptr;
5130*0b57cec5SDimitry Andric   const Expr *BaseExpr = E->getBase();
5131*0b57cec5SDimitry Andric   Qualifiers BaseQuals;
5132*0b57cec5SDimitry Andric   QualType ObjectTy;
5133*0b57cec5SDimitry Andric   if (E->isArrow()) {
5134*0b57cec5SDimitry Andric     BaseValue = EmitScalarExpr(BaseExpr);
5135*0b57cec5SDimitry Andric     ObjectTy = BaseExpr->getType()->getPointeeType();
5136*0b57cec5SDimitry Andric     BaseQuals = ObjectTy.getQualifiers();
5137*0b57cec5SDimitry Andric   } else {
5138*0b57cec5SDimitry Andric     LValue BaseLV = EmitLValue(BaseExpr);
5139480093f4SDimitry Andric     BaseValue = BaseLV.getPointer(*this);
5140*0b57cec5SDimitry Andric     ObjectTy = BaseExpr->getType();
5141*0b57cec5SDimitry Andric     BaseQuals = ObjectTy.getQualifiers();
5142*0b57cec5SDimitry Andric   }
5143*0b57cec5SDimitry Andric 
5144*0b57cec5SDimitry Andric   LValue LV =
5145*0b57cec5SDimitry Andric     EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
5146*0b57cec5SDimitry Andric                       BaseQuals.getCVRQualifiers());
5147*0b57cec5SDimitry Andric   setObjCGCLValueClass(getContext(), E, LV);
5148*0b57cec5SDimitry Andric   return LV;
5149*0b57cec5SDimitry Andric }
5150*0b57cec5SDimitry Andric 
5151*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
5152*0b57cec5SDimitry Andric   // Can only get l-value for message expression returning aggregate type
5153*0b57cec5SDimitry Andric   RValue RV = EmitAnyExprToTemp(E);
5154*0b57cec5SDimitry Andric   return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
5155*0b57cec5SDimitry Andric                         AlignmentSource::Decl);
5156*0b57cec5SDimitry Andric }
5157*0b57cec5SDimitry Andric 
5158*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
5159*0b57cec5SDimitry Andric                                  const CallExpr *E, ReturnValueSlot ReturnValue,
5160*0b57cec5SDimitry Andric                                  llvm::Value *Chain) {
5161*0b57cec5SDimitry Andric   // Get the actual function type. The callee type will always be a pointer to
5162*0b57cec5SDimitry Andric   // function type or a block pointer type.
5163*0b57cec5SDimitry Andric   assert(CalleeType->isFunctionPointerType() &&
5164*0b57cec5SDimitry Andric          "Call must have function pointer type!");
5165*0b57cec5SDimitry Andric 
5166*0b57cec5SDimitry Andric   const Decl *TargetDecl =
5167*0b57cec5SDimitry Andric       OrigCallee.getAbstractInfo().getCalleeDecl().getDecl();
5168*0b57cec5SDimitry Andric 
5169*0b57cec5SDimitry Andric   CalleeType = getContext().getCanonicalType(CalleeType);
5170*0b57cec5SDimitry Andric 
5171*0b57cec5SDimitry Andric   auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType();
5172*0b57cec5SDimitry Andric 
5173*0b57cec5SDimitry Andric   CGCallee Callee = OrigCallee;
5174*0b57cec5SDimitry Andric 
5175*0b57cec5SDimitry Andric   if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
5176*0b57cec5SDimitry Andric       (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
5177*0b57cec5SDimitry Andric     if (llvm::Constant *PrefixSig =
5178*0b57cec5SDimitry Andric             CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
5179*0b57cec5SDimitry Andric       SanitizerScope SanScope(this);
5180*0b57cec5SDimitry Andric       // Remove any (C++17) exception specifications, to allow calling e.g. a
5181*0b57cec5SDimitry Andric       // noexcept function through a non-noexcept pointer.
5182*0b57cec5SDimitry Andric       auto ProtoTy =
5183*0b57cec5SDimitry Andric         getContext().getFunctionTypeWithExceptionSpec(PointeeType, EST_None);
5184*0b57cec5SDimitry Andric       llvm::Constant *FTRTTIConst =
5185*0b57cec5SDimitry Andric           CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
5186fe6060f1SDimitry Andric       llvm::Type *PrefixSigType = PrefixSig->getType();
5187*0b57cec5SDimitry Andric       llvm::StructType *PrefixStructTy = llvm::StructType::get(
5188fe6060f1SDimitry Andric           CGM.getLLVMContext(), {PrefixSigType, Int32Ty}, /*isPacked=*/true);
5189*0b57cec5SDimitry Andric 
5190*0b57cec5SDimitry Andric       llvm::Value *CalleePtr = Callee.getFunctionPointer();
5191*0b57cec5SDimitry Andric 
5192*0b57cec5SDimitry Andric       llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
5193*0b57cec5SDimitry Andric           CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
5194*0b57cec5SDimitry Andric       llvm::Value *CalleeSigPtr =
5195*0b57cec5SDimitry Andric           Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
5196*0b57cec5SDimitry Andric       llvm::Value *CalleeSig =
5197fe6060f1SDimitry Andric           Builder.CreateAlignedLoad(PrefixSigType, CalleeSigPtr, getIntAlign());
5198*0b57cec5SDimitry Andric       llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
5199*0b57cec5SDimitry Andric 
5200*0b57cec5SDimitry Andric       llvm::BasicBlock *Cont = createBasicBlock("cont");
5201*0b57cec5SDimitry Andric       llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
5202*0b57cec5SDimitry Andric       Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
5203*0b57cec5SDimitry Andric 
5204*0b57cec5SDimitry Andric       EmitBlock(TypeCheck);
5205*0b57cec5SDimitry Andric       llvm::Value *CalleeRTTIPtr =
5206*0b57cec5SDimitry Andric           Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
5207*0b57cec5SDimitry Andric       llvm::Value *CalleeRTTIEncoded =
5208fe6060f1SDimitry Andric           Builder.CreateAlignedLoad(Int32Ty, CalleeRTTIPtr, getPointerAlign());
5209*0b57cec5SDimitry Andric       llvm::Value *CalleeRTTI =
5210*0b57cec5SDimitry Andric           DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded);
5211*0b57cec5SDimitry Andric       llvm::Value *CalleeRTTIMatch =
5212*0b57cec5SDimitry Andric           Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
5213*0b57cec5SDimitry Andric       llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()),
5214*0b57cec5SDimitry Andric                                       EmitCheckTypeDescriptor(CalleeType)};
5215*0b57cec5SDimitry Andric       EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
5216*0b57cec5SDimitry Andric                 SanitizerHandler::FunctionTypeMismatch, StaticData,
5217*0b57cec5SDimitry Andric                 {CalleePtr, CalleeRTTI, FTRTTIConst});
5218*0b57cec5SDimitry Andric 
5219*0b57cec5SDimitry Andric       Builder.CreateBr(Cont);
5220*0b57cec5SDimitry Andric       EmitBlock(Cont);
5221*0b57cec5SDimitry Andric     }
5222*0b57cec5SDimitry Andric   }
5223*0b57cec5SDimitry Andric 
5224*0b57cec5SDimitry Andric   const auto *FnType = cast<FunctionType>(PointeeType);
5225*0b57cec5SDimitry Andric 
5226*0b57cec5SDimitry Andric   // If we are checking indirect calls and this call is indirect, check that the
5227*0b57cec5SDimitry Andric   // function pointer is a member of the bit set for the function type.
5228*0b57cec5SDimitry Andric   if (SanOpts.has(SanitizerKind::CFIICall) &&
5229*0b57cec5SDimitry Andric       (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
5230*0b57cec5SDimitry Andric     SanitizerScope SanScope(this);
5231*0b57cec5SDimitry Andric     EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
5232*0b57cec5SDimitry Andric 
5233*0b57cec5SDimitry Andric     llvm::Metadata *MD;
5234*0b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
5235*0b57cec5SDimitry Andric       MD = CGM.CreateMetadataIdentifierGeneralized(QualType(FnType, 0));
5236*0b57cec5SDimitry Andric     else
5237*0b57cec5SDimitry Andric       MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
5238*0b57cec5SDimitry Andric 
5239*0b57cec5SDimitry Andric     llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
5240*0b57cec5SDimitry Andric 
5241*0b57cec5SDimitry Andric     llvm::Value *CalleePtr = Callee.getFunctionPointer();
5242*0b57cec5SDimitry Andric     llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
5243*0b57cec5SDimitry Andric     llvm::Value *TypeTest = Builder.CreateCall(
5244*0b57cec5SDimitry Andric         CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
5245*0b57cec5SDimitry Andric 
5246*0b57cec5SDimitry Andric     auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
5247*0b57cec5SDimitry Andric     llvm::Constant *StaticData[] = {
5248*0b57cec5SDimitry Andric         llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
5249*0b57cec5SDimitry Andric         EmitCheckSourceLocation(E->getBeginLoc()),
5250*0b57cec5SDimitry Andric         EmitCheckTypeDescriptor(QualType(FnType, 0)),
5251*0b57cec5SDimitry Andric     };
5252*0b57cec5SDimitry Andric     if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
5253*0b57cec5SDimitry Andric       EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
5254*0b57cec5SDimitry Andric                            CastedCallee, StaticData);
5255*0b57cec5SDimitry Andric     } else {
5256*0b57cec5SDimitry Andric       EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
5257*0b57cec5SDimitry Andric                 SanitizerHandler::CFICheckFail, StaticData,
5258*0b57cec5SDimitry Andric                 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
5259*0b57cec5SDimitry Andric     }
5260*0b57cec5SDimitry Andric   }
5261*0b57cec5SDimitry Andric 
5262*0b57cec5SDimitry Andric   CallArgList Args;
5263*0b57cec5SDimitry Andric   if (Chain)
5264*0b57cec5SDimitry Andric     Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
5265*0b57cec5SDimitry Andric              CGM.getContext().VoidPtrTy);
5266*0b57cec5SDimitry Andric 
5267*0b57cec5SDimitry Andric   // C++17 requires that we evaluate arguments to a call using assignment syntax
5268*0b57cec5SDimitry Andric   // right-to-left, and that we evaluate arguments to certain other operators
5269*0b57cec5SDimitry Andric   // left-to-right. Note that we allow this to override the order dictated by
5270*0b57cec5SDimitry Andric   // the calling convention on the MS ABI, which means that parameter
5271*0b57cec5SDimitry Andric   // destruction order is not necessarily reverse construction order.
5272*0b57cec5SDimitry Andric   // FIXME: Revisit this based on C++ committee response to unimplementability.
5273*0b57cec5SDimitry Andric   EvaluationOrder Order = EvaluationOrder::Default;
5274*0b57cec5SDimitry Andric   if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
5275*0b57cec5SDimitry Andric     if (OCE->isAssignmentOp())
5276*0b57cec5SDimitry Andric       Order = EvaluationOrder::ForceRightToLeft;
5277*0b57cec5SDimitry Andric     else {
5278*0b57cec5SDimitry Andric       switch (OCE->getOperator()) {
5279*0b57cec5SDimitry Andric       case OO_LessLess:
5280*0b57cec5SDimitry Andric       case OO_GreaterGreater:
5281*0b57cec5SDimitry Andric       case OO_AmpAmp:
5282*0b57cec5SDimitry Andric       case OO_PipePipe:
5283*0b57cec5SDimitry Andric       case OO_Comma:
5284*0b57cec5SDimitry Andric       case OO_ArrowStar:
5285*0b57cec5SDimitry Andric         Order = EvaluationOrder::ForceLeftToRight;
5286*0b57cec5SDimitry Andric         break;
5287*0b57cec5SDimitry Andric       default:
5288*0b57cec5SDimitry Andric         break;
5289*0b57cec5SDimitry Andric       }
5290*0b57cec5SDimitry Andric     }
5291*0b57cec5SDimitry Andric   }
5292*0b57cec5SDimitry Andric 
5293*0b57cec5SDimitry Andric   EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
5294*0b57cec5SDimitry Andric                E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
5295*0b57cec5SDimitry Andric 
5296*0b57cec5SDimitry Andric   const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
5297*0b57cec5SDimitry Andric       Args, FnType, /*ChainCall=*/Chain);
5298*0b57cec5SDimitry Andric 
5299*0b57cec5SDimitry Andric   // C99 6.5.2.2p6:
5300*0b57cec5SDimitry Andric   //   If the expression that denotes the called function has a type
5301*0b57cec5SDimitry Andric   //   that does not include a prototype, [the default argument
5302*0b57cec5SDimitry Andric   //   promotions are performed]. If the number of arguments does not
5303*0b57cec5SDimitry Andric   //   equal the number of parameters, the behavior is undefined. If
5304*0b57cec5SDimitry Andric   //   the function is defined with a type that includes a prototype,
5305*0b57cec5SDimitry Andric   //   and either the prototype ends with an ellipsis (, ...) or the
5306*0b57cec5SDimitry Andric   //   types of the arguments after promotion are not compatible with
5307*0b57cec5SDimitry Andric   //   the types of the parameters, the behavior is undefined. If the
5308*0b57cec5SDimitry Andric   //   function is defined with a type that does not include a
5309*0b57cec5SDimitry Andric   //   prototype, and the types of the arguments after promotion are
5310*0b57cec5SDimitry Andric   //   not compatible with those of the parameters after promotion,
5311*0b57cec5SDimitry Andric   //   the behavior is undefined [except in some trivial cases].
5312*0b57cec5SDimitry Andric   // That is, in the general case, we should assume that a call
5313*0b57cec5SDimitry Andric   // through an unprototyped function type works like a *non-variadic*
5314*0b57cec5SDimitry Andric   // call.  The way we make this work is to cast to the exact type
5315*0b57cec5SDimitry Andric   // of the promoted arguments.
5316*0b57cec5SDimitry Andric   //
5317*0b57cec5SDimitry Andric   // Chain calls use this same code path to add the invisible chain parameter
5318*0b57cec5SDimitry Andric   // to the function type.
5319*0b57cec5SDimitry Andric   if (isa<FunctionNoProtoType>(FnType) || Chain) {
5320*0b57cec5SDimitry Andric     llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
53215ffd83dbSDimitry Andric     int AS = Callee.getFunctionPointer()->getType()->getPointerAddressSpace();
53225ffd83dbSDimitry Andric     CalleeTy = CalleeTy->getPointerTo(AS);
5323*0b57cec5SDimitry Andric 
5324*0b57cec5SDimitry Andric     llvm::Value *CalleePtr = Callee.getFunctionPointer();
5325*0b57cec5SDimitry Andric     CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
5326*0b57cec5SDimitry Andric     Callee.setFunctionPointer(CalleePtr);
5327*0b57cec5SDimitry Andric   }
5328*0b57cec5SDimitry Andric 
5329fe6060f1SDimitry Andric   // HIP function pointer contains kernel handle when it is used in triple
5330fe6060f1SDimitry Andric   // chevron. The kernel stub needs to be loaded from kernel handle and used
5331fe6060f1SDimitry Andric   // as callee.
5332fe6060f1SDimitry Andric   if (CGM.getLangOpts().HIP && !CGM.getLangOpts().CUDAIsDevice &&
5333fe6060f1SDimitry Andric       isa<CUDAKernelCallExpr>(E) &&
5334fe6060f1SDimitry Andric       (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
5335fe6060f1SDimitry Andric     llvm::Value *Handle = Callee.getFunctionPointer();
5336fe6060f1SDimitry Andric     auto *Cast =
5337fe6060f1SDimitry Andric         Builder.CreateBitCast(Handle, Handle->getType()->getPointerTo());
5338fe6060f1SDimitry Andric     auto *Stub = Builder.CreateLoad(Address(Cast, CGM.getPointerAlign()));
5339fe6060f1SDimitry Andric     Callee.setFunctionPointer(Stub);
5340fe6060f1SDimitry Andric   }
5341*0b57cec5SDimitry Andric   llvm::CallBase *CallOrInvoke = nullptr;
5342*0b57cec5SDimitry Andric   RValue Call = EmitCall(FnInfo, Callee, ReturnValue, Args, &CallOrInvoke,
5343fe6060f1SDimitry Andric                          E == MustTailCall, E->getExprLoc());
5344*0b57cec5SDimitry Andric 
5345*0b57cec5SDimitry Andric   // Generate function declaration DISuprogram in order to be used
5346*0b57cec5SDimitry Andric   // in debug info about call sites.
5347*0b57cec5SDimitry Andric   if (CGDebugInfo *DI = getDebugInfo()) {
5348349cc55cSDimitry Andric     if (auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
5349349cc55cSDimitry Andric       FunctionArgList Args;
5350349cc55cSDimitry Andric       QualType ResTy = BuildFunctionArgList(CalleeDecl, Args);
5351349cc55cSDimitry Andric       DI->EmitFuncDeclForCallSite(CallOrInvoke,
5352349cc55cSDimitry Andric                                   DI->getFunctionType(CalleeDecl, ResTy, Args),
5353*0b57cec5SDimitry Andric                                   CalleeDecl);
5354*0b57cec5SDimitry Andric     }
5355349cc55cSDimitry Andric   }
5356*0b57cec5SDimitry Andric 
5357*0b57cec5SDimitry Andric   return Call;
5358*0b57cec5SDimitry Andric }
5359*0b57cec5SDimitry Andric 
5360*0b57cec5SDimitry Andric LValue CodeGenFunction::
5361*0b57cec5SDimitry Andric EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
5362*0b57cec5SDimitry Andric   Address BaseAddr = Address::invalid();
5363*0b57cec5SDimitry Andric   if (E->getOpcode() == BO_PtrMemI) {
5364*0b57cec5SDimitry Andric     BaseAddr = EmitPointerWithAlignment(E->getLHS());
5365*0b57cec5SDimitry Andric   } else {
5366480093f4SDimitry Andric     BaseAddr = EmitLValue(E->getLHS()).getAddress(*this);
5367*0b57cec5SDimitry Andric   }
5368*0b57cec5SDimitry Andric 
5369*0b57cec5SDimitry Andric   llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
5370480093f4SDimitry Andric   const auto *MPT = E->getRHS()->getType()->castAs<MemberPointerType>();
5371*0b57cec5SDimitry Andric 
5372*0b57cec5SDimitry Andric   LValueBaseInfo BaseInfo;
5373*0b57cec5SDimitry Andric   TBAAAccessInfo TBAAInfo;
5374*0b57cec5SDimitry Andric   Address MemberAddr =
5375*0b57cec5SDimitry Andric     EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo,
5376*0b57cec5SDimitry Andric                                     &TBAAInfo);
5377*0b57cec5SDimitry Andric 
5378*0b57cec5SDimitry Andric   return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
5379*0b57cec5SDimitry Andric }
5380*0b57cec5SDimitry Andric 
5381*0b57cec5SDimitry Andric /// Given the address of a temporary variable, produce an r-value of
5382*0b57cec5SDimitry Andric /// its type.
5383*0b57cec5SDimitry Andric RValue CodeGenFunction::convertTempToRValue(Address addr,
5384*0b57cec5SDimitry Andric                                             QualType type,
5385*0b57cec5SDimitry Andric                                             SourceLocation loc) {
5386*0b57cec5SDimitry Andric   LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
5387*0b57cec5SDimitry Andric   switch (getEvaluationKind(type)) {
5388*0b57cec5SDimitry Andric   case TEK_Complex:
5389*0b57cec5SDimitry Andric     return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
5390*0b57cec5SDimitry Andric   case TEK_Aggregate:
5391480093f4SDimitry Andric     return lvalue.asAggregateRValue(*this);
5392*0b57cec5SDimitry Andric   case TEK_Scalar:
5393*0b57cec5SDimitry Andric     return RValue::get(EmitLoadOfScalar(lvalue, loc));
5394*0b57cec5SDimitry Andric   }
5395*0b57cec5SDimitry Andric   llvm_unreachable("bad evaluation kind");
5396*0b57cec5SDimitry Andric }
5397*0b57cec5SDimitry Andric 
5398*0b57cec5SDimitry Andric void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
5399*0b57cec5SDimitry Andric   assert(Val->getType()->isFPOrFPVectorTy());
5400*0b57cec5SDimitry Andric   if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
5401*0b57cec5SDimitry Andric     return;
5402*0b57cec5SDimitry Andric 
5403*0b57cec5SDimitry Andric   llvm::MDBuilder MDHelper(getLLVMContext());
5404*0b57cec5SDimitry Andric   llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
5405*0b57cec5SDimitry Andric 
5406*0b57cec5SDimitry Andric   cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
5407*0b57cec5SDimitry Andric }
5408*0b57cec5SDimitry Andric 
5409*0b57cec5SDimitry Andric namespace {
5410*0b57cec5SDimitry Andric   struct LValueOrRValue {
5411*0b57cec5SDimitry Andric     LValue LV;
5412*0b57cec5SDimitry Andric     RValue RV;
5413*0b57cec5SDimitry Andric   };
5414*0b57cec5SDimitry Andric }
5415*0b57cec5SDimitry Andric 
5416*0b57cec5SDimitry Andric static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
5417*0b57cec5SDimitry Andric                                            const PseudoObjectExpr *E,
5418*0b57cec5SDimitry Andric                                            bool forLValue,
5419*0b57cec5SDimitry Andric                                            AggValueSlot slot) {
5420*0b57cec5SDimitry Andric   SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
5421*0b57cec5SDimitry Andric 
5422*0b57cec5SDimitry Andric   // Find the result expression, if any.
5423*0b57cec5SDimitry Andric   const Expr *resultExpr = E->getResultExpr();
5424*0b57cec5SDimitry Andric   LValueOrRValue result;
5425*0b57cec5SDimitry Andric 
5426*0b57cec5SDimitry Andric   for (PseudoObjectExpr::const_semantics_iterator
5427*0b57cec5SDimitry Andric          i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
5428*0b57cec5SDimitry Andric     const Expr *semantic = *i;
5429*0b57cec5SDimitry Andric 
5430*0b57cec5SDimitry Andric     // If this semantic expression is an opaque value, bind it
5431*0b57cec5SDimitry Andric     // to the result of its source expression.
5432*0b57cec5SDimitry Andric     if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
5433*0b57cec5SDimitry Andric       // Skip unique OVEs.
5434*0b57cec5SDimitry Andric       if (ov->isUnique()) {
5435*0b57cec5SDimitry Andric         assert(ov != resultExpr &&
5436*0b57cec5SDimitry Andric                "A unique OVE cannot be used as the result expression");
5437*0b57cec5SDimitry Andric         continue;
5438*0b57cec5SDimitry Andric       }
5439*0b57cec5SDimitry Andric 
5440*0b57cec5SDimitry Andric       // If this is the result expression, we may need to evaluate
5441*0b57cec5SDimitry Andric       // directly into the slot.
5442*0b57cec5SDimitry Andric       typedef CodeGenFunction::OpaqueValueMappingData OVMA;
5443*0b57cec5SDimitry Andric       OVMA opaqueData;
5444fe6060f1SDimitry Andric       if (ov == resultExpr && ov->isPRValue() && !forLValue &&
5445*0b57cec5SDimitry Andric           CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
5446*0b57cec5SDimitry Andric         CGF.EmitAggExpr(ov->getSourceExpr(), slot);
5447*0b57cec5SDimitry Andric         LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
5448*0b57cec5SDimitry Andric                                        AlignmentSource::Decl);
5449*0b57cec5SDimitry Andric         opaqueData = OVMA::bind(CGF, ov, LV);
5450*0b57cec5SDimitry Andric         result.RV = slot.asRValue();
5451*0b57cec5SDimitry Andric 
5452*0b57cec5SDimitry Andric       // Otherwise, emit as normal.
5453*0b57cec5SDimitry Andric       } else {
5454*0b57cec5SDimitry Andric         opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
5455*0b57cec5SDimitry Andric 
5456*0b57cec5SDimitry Andric         // If this is the result, also evaluate the result now.
5457*0b57cec5SDimitry Andric         if (ov == resultExpr) {
5458*0b57cec5SDimitry Andric           if (forLValue)
5459*0b57cec5SDimitry Andric             result.LV = CGF.EmitLValue(ov);
5460*0b57cec5SDimitry Andric           else
5461*0b57cec5SDimitry Andric             result.RV = CGF.EmitAnyExpr(ov, slot);
5462*0b57cec5SDimitry Andric         }
5463*0b57cec5SDimitry Andric       }
5464*0b57cec5SDimitry Andric 
5465*0b57cec5SDimitry Andric       opaques.push_back(opaqueData);
5466*0b57cec5SDimitry Andric 
5467*0b57cec5SDimitry Andric     // Otherwise, if the expression is the result, evaluate it
5468*0b57cec5SDimitry Andric     // and remember the result.
5469*0b57cec5SDimitry Andric     } else if (semantic == resultExpr) {
5470*0b57cec5SDimitry Andric       if (forLValue)
5471*0b57cec5SDimitry Andric         result.LV = CGF.EmitLValue(semantic);
5472*0b57cec5SDimitry Andric       else
5473*0b57cec5SDimitry Andric         result.RV = CGF.EmitAnyExpr(semantic, slot);
5474*0b57cec5SDimitry Andric 
5475*0b57cec5SDimitry Andric     // Otherwise, evaluate the expression in an ignored context.
5476*0b57cec5SDimitry Andric     } else {
5477*0b57cec5SDimitry Andric       CGF.EmitIgnoredExpr(semantic);
5478*0b57cec5SDimitry Andric     }
5479*0b57cec5SDimitry Andric   }
5480*0b57cec5SDimitry Andric 
5481*0b57cec5SDimitry Andric   // Unbind all the opaques now.
5482*0b57cec5SDimitry Andric   for (unsigned i = 0, e = opaques.size(); i != e; ++i)
5483*0b57cec5SDimitry Andric     opaques[i].unbind(CGF);
5484*0b57cec5SDimitry Andric 
5485*0b57cec5SDimitry Andric   return result;
5486*0b57cec5SDimitry Andric }
5487*0b57cec5SDimitry Andric 
5488*0b57cec5SDimitry Andric RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
5489*0b57cec5SDimitry Andric                                                AggValueSlot slot) {
5490*0b57cec5SDimitry Andric   return emitPseudoObjectExpr(*this, E, false, slot).RV;
5491*0b57cec5SDimitry Andric }
5492*0b57cec5SDimitry Andric 
5493*0b57cec5SDimitry Andric LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
5494*0b57cec5SDimitry Andric   return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
5495*0b57cec5SDimitry Andric }
5496