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