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