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 =
1856           cast<llvm::IntegerType>(Addr.getType()->getPointerElementType());
1857       // Expand to the memory bit width.
1858       unsigned MemNumElems = MemIntTy->getPrimitiveSizeInBits();
1859       // <N x i1> --> <P x i1>.
1860       Value = emitBoolVecConversion(Value, MemNumElems, "insertvec");
1861       // <P x i1> --> iP.
1862       Value = Builder.CreateBitCast(Value, MemIntTy);
1863     } else if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1864       // Handle vec3 special.
1865       if (VecTy && cast<llvm::FixedVectorType>(VecTy)->getNumElements() == 3) {
1866         // Our source is a vec3, do a shuffle vector to make it a vec4.
1867         Value = Builder.CreateShuffleVector(Value, ArrayRef<int>{0, 1, 2, -1},
1868                                             "extractVec");
1869         SrcTy = llvm::FixedVectorType::get(VecTy->getElementType(), 4);
1870       }
1871       if (Addr.getElementType() != SrcTy) {
1872         Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1873       }
1874     }
1875   }
1876 
1877   Value = EmitToMemory(Value, Ty);
1878 
1879   LValue AtomicLValue =
1880       LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1881   if (Ty->isAtomicType() ||
1882       (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1883     EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
1884     return;
1885   }
1886 
1887   llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1888   if (isNontemporal) {
1889     llvm::MDNode *Node =
1890         llvm::MDNode::get(Store->getContext(),
1891                           llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1892     Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1893   }
1894 
1895   CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
1896 }
1897 
1898 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1899                                         bool isInit) {
1900   if (lvalue.getType()->isConstantMatrixType()) {
1901     EmitStoreOfMatrixScalar(value, lvalue, isInit, *this);
1902     return;
1903   }
1904 
1905   EmitStoreOfScalar(value, lvalue.getAddress(*this), lvalue.isVolatile(),
1906                     lvalue.getType(), lvalue.getBaseInfo(),
1907                     lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
1908 }
1909 
1910 // Emit a load of a LValue of matrix type. This may require casting the pointer
1911 // to memory address (ArrayType) to a pointer to the value type (VectorType).
1912 static RValue EmitLoadOfMatrixLValue(LValue LV, SourceLocation Loc,
1913                                      CodeGenFunction &CGF) {
1914   assert(LV.getType()->isConstantMatrixType());
1915   Address Addr = MaybeConvertMatrixAddress(LV.getAddress(CGF), CGF);
1916   LV.setAddress(Addr);
1917   return RValue::get(CGF.EmitLoadOfScalar(LV, Loc));
1918 }
1919 
1920 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1921 /// method emits the address of the lvalue, then loads the result as an rvalue,
1922 /// returning the rvalue.
1923 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
1924   if (LV.isObjCWeak()) {
1925     // load of a __weak object.
1926     Address AddrWeakObj = LV.getAddress(*this);
1927     return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1928                                                              AddrWeakObj));
1929   }
1930   if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1931     // In MRC mode, we do a load+autorelease.
1932     if (!getLangOpts().ObjCAutoRefCount) {
1933       return RValue::get(EmitARCLoadWeak(LV.getAddress(*this)));
1934     }
1935 
1936     // In ARC mode, we load retained and then consume the value.
1937     llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress(*this));
1938     Object = EmitObjCConsumeObject(LV.getType(), Object);
1939     return RValue::get(Object);
1940   }
1941 
1942   if (LV.isSimple()) {
1943     assert(!LV.getType()->isFunctionType());
1944 
1945     if (LV.getType()->isConstantMatrixType())
1946       return EmitLoadOfMatrixLValue(LV, Loc, *this);
1947 
1948     // Everything needs a load.
1949     return RValue::get(EmitLoadOfScalar(LV, Loc));
1950   }
1951 
1952   if (LV.isVectorElt()) {
1953     llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
1954                                               LV.isVolatileQualified());
1955     return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1956                                                     "vecext"));
1957   }
1958 
1959   // If this is a reference to a subset of the elements of a vector, either
1960   // shuffle the input or extract/insert them as appropriate.
1961   if (LV.isExtVectorElt()) {
1962     return EmitLoadOfExtVectorElementLValue(LV);
1963   }
1964 
1965   // Global Register variables always invoke intrinsics
1966   if (LV.isGlobalReg())
1967     return EmitLoadOfGlobalRegLValue(LV);
1968 
1969   if (LV.isMatrixElt()) {
1970     llvm::Value *Idx = LV.getMatrixIdx();
1971     if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
1972       const auto *const MatTy = LV.getType()->castAs<ConstantMatrixType>();
1973       llvm::MatrixBuilder MB(Builder);
1974       MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
1975     }
1976     llvm::LoadInst *Load =
1977         Builder.CreateLoad(LV.getMatrixAddress(), LV.isVolatileQualified());
1978     return RValue::get(Builder.CreateExtractElement(Load, Idx, "matrixext"));
1979   }
1980 
1981   assert(LV.isBitField() && "Unknown LValue type!");
1982   return EmitLoadOfBitfieldLValue(LV, Loc);
1983 }
1984 
1985 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1986                                                  SourceLocation Loc) {
1987   const CGBitFieldInfo &Info = LV.getBitFieldInfo();
1988 
1989   // Get the output type.
1990   llvm::Type *ResLTy = ConvertType(LV.getType());
1991 
1992   Address Ptr = LV.getBitFieldAddress();
1993   llvm::Value *Val =
1994       Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
1995 
1996   bool UseVolatile = LV.isVolatileQualified() &&
1997                      Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
1998   const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
1999   const unsigned StorageSize =
2000       UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
2001   if (Info.IsSigned) {
2002     assert(static_cast<unsigned>(Offset + Info.Size) <= StorageSize);
2003     unsigned HighBits = StorageSize - Offset - Info.Size;
2004     if (HighBits)
2005       Val = Builder.CreateShl(Val, HighBits, "bf.shl");
2006     if (Offset + HighBits)
2007       Val = Builder.CreateAShr(Val, Offset + HighBits, "bf.ashr");
2008   } else {
2009     if (Offset)
2010       Val = Builder.CreateLShr(Val, Offset, "bf.lshr");
2011     if (static_cast<unsigned>(Offset) + Info.Size < StorageSize)
2012       Val = Builder.CreateAnd(
2013           Val, llvm::APInt::getLowBitsSet(StorageSize, Info.Size), "bf.clear");
2014   }
2015   Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
2016   EmitScalarRangeCheck(Val, LV.getType(), Loc);
2017   return RValue::get(Val);
2018 }
2019 
2020 // If this is a reference to a subset of the elements of a vector, create an
2021 // appropriate shufflevector.
2022 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
2023   llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
2024                                         LV.isVolatileQualified());
2025 
2026   const llvm::Constant *Elts = LV.getExtVectorElts();
2027 
2028   // If the result of the expression is a non-vector type, we must be extracting
2029   // a single element.  Just codegen as an extractelement.
2030   const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
2031   if (!ExprVT) {
2032     unsigned InIdx = getAccessedFieldNo(0, Elts);
2033     llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
2034     return RValue::get(Builder.CreateExtractElement(Vec, Elt));
2035   }
2036 
2037   // Always use shuffle vector to try to retain the original program structure
2038   unsigned NumResultElts = ExprVT->getNumElements();
2039 
2040   SmallVector<int, 4> Mask;
2041   for (unsigned i = 0; i != NumResultElts; ++i)
2042     Mask.push_back(getAccessedFieldNo(i, Elts));
2043 
2044   Vec = Builder.CreateShuffleVector(Vec, Mask);
2045   return RValue::get(Vec);
2046 }
2047 
2048 /// Generates lvalue for partial ext_vector access.
2049 Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
2050   Address VectorAddress = LV.getExtVectorAddress();
2051   QualType EQT = LV.getType()->castAs<VectorType>()->getElementType();
2052   llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
2053 
2054   Address CastToPointerElement =
2055     Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
2056                                  "conv.ptr.element");
2057 
2058   const llvm::Constant *Elts = LV.getExtVectorElts();
2059   unsigned ix = getAccessedFieldNo(0, Elts);
2060 
2061   Address VectorBasePtrPlusIx =
2062     Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
2063                                    "vector.elt");
2064 
2065   return VectorBasePtrPlusIx;
2066 }
2067 
2068 /// Load of global gamed gegisters are always calls to intrinsics.
2069 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
2070   assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
2071          "Bad type for register variable");
2072   llvm::MDNode *RegName = cast<llvm::MDNode>(
2073       cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
2074 
2075   // We accept integer and pointer types only
2076   llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
2077   llvm::Type *Ty = OrigTy;
2078   if (OrigTy->isPointerTy())
2079     Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2080   llvm::Type *Types[] = { Ty };
2081 
2082   llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
2083   llvm::Value *Call = Builder.CreateCall(
2084       F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
2085   if (OrigTy->isPointerTy())
2086     Call = Builder.CreateIntToPtr(Call, OrigTy);
2087   return RValue::get(Call);
2088 }
2089 
2090 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
2091 /// lvalue, where both are guaranteed to the have the same type, and that type
2092 /// is 'Ty'.
2093 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
2094                                              bool isInit) {
2095   if (!Dst.isSimple()) {
2096     if (Dst.isVectorElt()) {
2097       // Read/modify/write the vector, inserting the new element.
2098       llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
2099                                             Dst.isVolatileQualified());
2100       auto *IRStoreTy = dyn_cast<llvm::IntegerType>(Vec->getType());
2101       if (IRStoreTy) {
2102         auto *IRVecTy = llvm::FixedVectorType::get(
2103             Builder.getInt1Ty(), IRStoreTy->getPrimitiveSizeInBits());
2104         Vec = Builder.CreateBitCast(Vec, IRVecTy);
2105         // iN --> <N x i1>.
2106       }
2107       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
2108                                         Dst.getVectorIdx(), "vecins");
2109       if (IRStoreTy) {
2110         // <N x i1> --> <iN>.
2111         Vec = Builder.CreateBitCast(Vec, IRStoreTy);
2112       }
2113       Builder.CreateStore(Vec, Dst.getVectorAddress(),
2114                           Dst.isVolatileQualified());
2115       return;
2116     }
2117 
2118     // If this is an update of extended vector elements, insert them as
2119     // appropriate.
2120     if (Dst.isExtVectorElt())
2121       return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
2122 
2123     if (Dst.isGlobalReg())
2124       return EmitStoreThroughGlobalRegLValue(Src, Dst);
2125 
2126     if (Dst.isMatrixElt()) {
2127       llvm::Value *Idx = Dst.getMatrixIdx();
2128       if (CGM.getCodeGenOpts().OptimizationLevel > 0) {
2129         const auto *const MatTy = Dst.getType()->castAs<ConstantMatrixType>();
2130         llvm::MatrixBuilder MB(Builder);
2131         MB.CreateIndexAssumption(Idx, MatTy->getNumElementsFlattened());
2132       }
2133       llvm::Instruction *Load = Builder.CreateLoad(Dst.getMatrixAddress());
2134       llvm::Value *Vec =
2135           Builder.CreateInsertElement(Load, Src.getScalarVal(), Idx, "matins");
2136       Builder.CreateStore(Vec, Dst.getMatrixAddress(),
2137                           Dst.isVolatileQualified());
2138       return;
2139     }
2140 
2141     assert(Dst.isBitField() && "Unknown LValue type");
2142     return EmitStoreThroughBitfieldLValue(Src, Dst);
2143   }
2144 
2145   // There's special magic for assigning into an ARC-qualified l-value.
2146   if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
2147     switch (Lifetime) {
2148     case Qualifiers::OCL_None:
2149       llvm_unreachable("present but none");
2150 
2151     case Qualifiers::OCL_ExplicitNone:
2152       // nothing special
2153       break;
2154 
2155     case Qualifiers::OCL_Strong:
2156       if (isInit) {
2157         Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
2158         break;
2159       }
2160       EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
2161       return;
2162 
2163     case Qualifiers::OCL_Weak:
2164       if (isInit)
2165         // Initialize and then skip the primitive store.
2166         EmitARCInitWeak(Dst.getAddress(*this), Src.getScalarVal());
2167       else
2168         EmitARCStoreWeak(Dst.getAddress(*this), Src.getScalarVal(),
2169                          /*ignore*/ true);
2170       return;
2171 
2172     case Qualifiers::OCL_Autoreleasing:
2173       Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
2174                                                      Src.getScalarVal()));
2175       // fall into the normal path
2176       break;
2177     }
2178   }
2179 
2180   if (Dst.isObjCWeak() && !Dst.isNonGC()) {
2181     // load of a __weak object.
2182     Address LvalueDst = Dst.getAddress(*this);
2183     llvm::Value *src = Src.getScalarVal();
2184      CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
2185     return;
2186   }
2187 
2188   if (Dst.isObjCStrong() && !Dst.isNonGC()) {
2189     // load of a __strong object.
2190     Address LvalueDst = Dst.getAddress(*this);
2191     llvm::Value *src = Src.getScalarVal();
2192     if (Dst.isObjCIvar()) {
2193       assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
2194       llvm::Type *ResultType = IntPtrTy;
2195       Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
2196       llvm::Value *RHS = dst.getPointer();
2197       RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
2198       llvm::Value *LHS =
2199         Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
2200                                "sub.ptr.lhs.cast");
2201       llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
2202       CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
2203                                               BytesBetween);
2204     } else if (Dst.isGlobalObjCRef()) {
2205       CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
2206                                                 Dst.isThreadLocalRef());
2207     }
2208     else
2209       CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
2210     return;
2211   }
2212 
2213   assert(Src.isScalar() && "Can't emit an agg store with this method");
2214   EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
2215 }
2216 
2217 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
2218                                                      llvm::Value **Result) {
2219   const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
2220   llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
2221   Address Ptr = Dst.getBitFieldAddress();
2222 
2223   // Get the source value, truncated to the width of the bit-field.
2224   llvm::Value *SrcVal = Src.getScalarVal();
2225 
2226   // Cast the source to the storage type and shift it into place.
2227   SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
2228                                  /*isSigned=*/false);
2229   llvm::Value *MaskedVal = SrcVal;
2230 
2231   const bool UseVolatile =
2232       CGM.getCodeGenOpts().AAPCSBitfieldWidth && Dst.isVolatileQualified() &&
2233       Info.VolatileStorageSize != 0 && isAAPCS(CGM.getTarget());
2234   const unsigned StorageSize =
2235       UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
2236   const unsigned Offset = UseVolatile ? Info.VolatileOffset : Info.Offset;
2237   // See if there are other bits in the bitfield's storage we'll need to load
2238   // and mask together with source before storing.
2239   if (StorageSize != Info.Size) {
2240     assert(StorageSize > Info.Size && "Invalid bitfield size.");
2241     llvm::Value *Val =
2242         Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
2243 
2244     // Mask the source value as needed.
2245     if (!hasBooleanRepresentation(Dst.getType()))
2246       SrcVal = Builder.CreateAnd(
2247           SrcVal, llvm::APInt::getLowBitsSet(StorageSize, Info.Size),
2248           "bf.value");
2249     MaskedVal = SrcVal;
2250     if (Offset)
2251       SrcVal = Builder.CreateShl(SrcVal, Offset, "bf.shl");
2252 
2253     // Mask out the original value.
2254     Val = Builder.CreateAnd(
2255         Val, ~llvm::APInt::getBitsSet(StorageSize, Offset, Offset + Info.Size),
2256         "bf.clear");
2257 
2258     // Or together the unchanged values and the source value.
2259     SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
2260   } else {
2261     assert(Offset == 0);
2262     // According to the AACPS:
2263     // When a volatile bit-field is written, and its container does not overlap
2264     // with any non-bit-field member, its container must be read exactly once
2265     // and written exactly once using the access width appropriate to the type
2266     // of the container. The two accesses are not atomic.
2267     if (Dst.isVolatileQualified() && isAAPCS(CGM.getTarget()) &&
2268         CGM.getCodeGenOpts().ForceAAPCSBitfieldLoad)
2269       Builder.CreateLoad(Ptr, true, "bf.load");
2270   }
2271 
2272   // Write the new value back out.
2273   Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
2274 
2275   // Return the new value of the bit-field, if requested.
2276   if (Result) {
2277     llvm::Value *ResultVal = MaskedVal;
2278 
2279     // Sign extend the value if needed.
2280     if (Info.IsSigned) {
2281       assert(Info.Size <= StorageSize);
2282       unsigned HighBits = StorageSize - Info.Size;
2283       if (HighBits) {
2284         ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
2285         ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
2286       }
2287     }
2288 
2289     ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
2290                                       "bf.result.cast");
2291     *Result = EmitFromMemory(ResultVal, Dst.getType());
2292   }
2293 }
2294 
2295 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
2296                                                                LValue Dst) {
2297   // This access turns into a read/modify/write of the vector.  Load the input
2298   // value now.
2299   llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
2300                                         Dst.isVolatileQualified());
2301   const llvm::Constant *Elts = Dst.getExtVectorElts();
2302 
2303   llvm::Value *SrcVal = Src.getScalarVal();
2304 
2305   if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
2306     unsigned NumSrcElts = VTy->getNumElements();
2307     unsigned NumDstElts =
2308         cast<llvm::FixedVectorType>(Vec->getType())->getNumElements();
2309     if (NumDstElts == NumSrcElts) {
2310       // Use shuffle vector is the src and destination are the same number of
2311       // elements and restore the vector mask since it is on the side it will be
2312       // stored.
2313       SmallVector<int, 4> Mask(NumDstElts);
2314       for (unsigned i = 0; i != NumSrcElts; ++i)
2315         Mask[getAccessedFieldNo(i, Elts)] = i;
2316 
2317       Vec = Builder.CreateShuffleVector(SrcVal, Mask);
2318     } else if (NumDstElts > NumSrcElts) {
2319       // Extended the source vector to the same length and then shuffle it
2320       // into the destination.
2321       // FIXME: since we're shuffling with undef, can we just use the indices
2322       //        into that?  This could be simpler.
2323       SmallVector<int, 4> ExtMask;
2324       for (unsigned i = 0; i != NumSrcElts; ++i)
2325         ExtMask.push_back(i);
2326       ExtMask.resize(NumDstElts, -1);
2327       llvm::Value *ExtSrcVal = Builder.CreateShuffleVector(SrcVal, ExtMask);
2328       // build identity
2329       SmallVector<int, 4> Mask;
2330       for (unsigned i = 0; i != NumDstElts; ++i)
2331         Mask.push_back(i);
2332 
2333       // When the vector size is odd and .odd or .hi is used, the last element
2334       // of the Elts constant array will be one past the size of the vector.
2335       // Ignore the last element here, if it is greater than the mask size.
2336       if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
2337         NumSrcElts--;
2338 
2339       // modify when what gets shuffled in
2340       for (unsigned i = 0; i != NumSrcElts; ++i)
2341         Mask[getAccessedFieldNo(i, Elts)] = i + NumDstElts;
2342       Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, Mask);
2343     } else {
2344       // We should never shorten the vector
2345       llvm_unreachable("unexpected shorten vector length");
2346     }
2347   } else {
2348     // If the Src is a scalar (not a vector) it must be updating one element.
2349     unsigned InIdx = getAccessedFieldNo(0, Elts);
2350     llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
2351     Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
2352   }
2353 
2354   Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
2355                       Dst.isVolatileQualified());
2356 }
2357 
2358 /// Store of global named registers are always calls to intrinsics.
2359 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
2360   assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
2361          "Bad type for register variable");
2362   llvm::MDNode *RegName = cast<llvm::MDNode>(
2363       cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
2364   assert(RegName && "Register LValue is not metadata");
2365 
2366   // We accept integer and pointer types only
2367   llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
2368   llvm::Type *Ty = OrigTy;
2369   if (OrigTy->isPointerTy())
2370     Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2371   llvm::Type *Types[] = { Ty };
2372 
2373   llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
2374   llvm::Value *Value = Src.getScalarVal();
2375   if (OrigTy->isPointerTy())
2376     Value = Builder.CreatePtrToInt(Value, Ty);
2377   Builder.CreateCall(
2378       F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
2379 }
2380 
2381 // setObjCGCLValueClass - sets class of the lvalue for the purpose of
2382 // generating write-barries API. It is currently a global, ivar,
2383 // or neither.
2384 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
2385                                  LValue &LV,
2386                                  bool IsMemberAccess=false) {
2387   if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
2388     return;
2389 
2390   if (isa<ObjCIvarRefExpr>(E)) {
2391     QualType ExpTy = E->getType();
2392     if (IsMemberAccess && ExpTy->isPointerType()) {
2393       // If ivar is a structure pointer, assigning to field of
2394       // this struct follows gcc's behavior and makes it a non-ivar
2395       // writer-barrier conservatively.
2396       ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
2397       if (ExpTy->isRecordType()) {
2398         LV.setObjCIvar(false);
2399         return;
2400       }
2401     }
2402     LV.setObjCIvar(true);
2403     auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
2404     LV.setBaseIvarExp(Exp->getBase());
2405     LV.setObjCArray(E->getType()->isArrayType());
2406     return;
2407   }
2408 
2409   if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
2410     if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
2411       if (VD->hasGlobalStorage()) {
2412         LV.setGlobalObjCRef(true);
2413         LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
2414       }
2415     }
2416     LV.setObjCArray(E->getType()->isArrayType());
2417     return;
2418   }
2419 
2420   if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
2421     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2422     return;
2423   }
2424 
2425   if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
2426     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2427     if (LV.isObjCIvar()) {
2428       // If cast is to a structure pointer, follow gcc's behavior and make it
2429       // a non-ivar write-barrier.
2430       QualType ExpTy = E->getType();
2431       if (ExpTy->isPointerType())
2432         ExpTy = ExpTy->castAs<PointerType>()->getPointeeType();
2433       if (ExpTy->isRecordType())
2434         LV.setObjCIvar(false);
2435     }
2436     return;
2437   }
2438 
2439   if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
2440     setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2441     return;
2442   }
2443 
2444   if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
2445     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2446     return;
2447   }
2448 
2449   if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
2450     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2451     return;
2452   }
2453 
2454   if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
2455     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2456     return;
2457   }
2458 
2459   if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
2460     setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
2461     if (LV.isObjCIvar() && !LV.isObjCArray())
2462       // Using array syntax to assigning to what an ivar points to is not
2463       // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
2464       LV.setObjCIvar(false);
2465     else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
2466       // Using array syntax to assigning to what global points to is not
2467       // same as assigning to the global itself. {id *G;} G[i] = 0;
2468       LV.setGlobalObjCRef(false);
2469     return;
2470   }
2471 
2472   if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
2473     setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
2474     // We don't know if member is an 'ivar', but this flag is looked at
2475     // only in the context of LV.isObjCIvar().
2476     LV.setObjCArray(E->getType()->isArrayType());
2477     return;
2478   }
2479 }
2480 
2481 static llvm::Value *
2482 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
2483                                 llvm::Value *V, llvm::Type *IRType,
2484                                 StringRef Name = StringRef()) {
2485   unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
2486   return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
2487 }
2488 
2489 static LValue EmitThreadPrivateVarDeclLValue(
2490     CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2491     llvm::Type *RealVarTy, SourceLocation Loc) {
2492   if (CGF.CGM.getLangOpts().OpenMPIRBuilder)
2493     Addr = CodeGenFunction::OMPBuilderCBHelpers::getAddrOfThreadPrivate(
2494         CGF, VD, Addr, Loc);
2495   else
2496     Addr =
2497         CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2498 
2499   Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
2500   return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2501 }
2502 
2503 static Address emitDeclTargetVarDeclLValue(CodeGenFunction &CGF,
2504                                            const VarDecl *VD, QualType T) {
2505   llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2506       OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
2507   // Return an invalid address if variable is MT_To and unified
2508   // memory is not enabled. For all other cases: MT_Link and
2509   // MT_To with unified memory, return a valid address.
2510   if (!Res || (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2511                !CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory()))
2512     return Address::invalid();
2513   assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
2514           (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2515            CGF.CGM.getOpenMPRuntime().hasRequiresUnifiedSharedMemory())) &&
2516          "Expected link clause OR to clause with unified memory enabled.");
2517   QualType PtrTy = CGF.getContext().getPointerType(VD->getType());
2518   Address Addr = CGF.CGM.getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
2519   return CGF.EmitLoadOfPointer(Addr, PtrTy->castAs<PointerType>());
2520 }
2521 
2522 Address
2523 CodeGenFunction::EmitLoadOfReference(LValue RefLVal,
2524                                      LValueBaseInfo *PointeeBaseInfo,
2525                                      TBAAAccessInfo *PointeeTBAAInfo) {
2526   llvm::LoadInst *Load =
2527       Builder.CreateLoad(RefLVal.getAddress(*this), RefLVal.isVolatile());
2528   CGM.DecorateInstructionWithTBAA(Load, RefLVal.getTBAAInfo());
2529 
2530   QualType PointeeType = RefLVal.getType()->getPointeeType();
2531   CharUnits Align = CGM.getNaturalTypeAlignment(
2532       PointeeType, PointeeBaseInfo, PointeeTBAAInfo,
2533       /* forPointeeType= */ true);
2534   return Address(Load, ConvertTypeForMem(PointeeType), Align);
2535 }
2536 
2537 LValue CodeGenFunction::EmitLoadOfReferenceLValue(LValue RefLVal) {
2538   LValueBaseInfo PointeeBaseInfo;
2539   TBAAAccessInfo PointeeTBAAInfo;
2540   Address PointeeAddr = EmitLoadOfReference(RefLVal, &PointeeBaseInfo,
2541                                             &PointeeTBAAInfo);
2542   return MakeAddrLValue(PointeeAddr, RefLVal.getType()->getPointeeType(),
2543                         PointeeBaseInfo, PointeeTBAAInfo);
2544 }
2545 
2546 Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2547                                            const PointerType *PtrTy,
2548                                            LValueBaseInfo *BaseInfo,
2549                                            TBAAAccessInfo *TBAAInfo) {
2550   llvm::Value *Addr = Builder.CreateLoad(Ptr);
2551   return Address::deprecated(
2552       Addr,
2553       CGM.getNaturalTypeAlignment(PtrTy->getPointeeType(), BaseInfo, TBAAInfo,
2554                                   /*forPointeeType=*/true));
2555 }
2556 
2557 LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2558                                                 const PointerType *PtrTy) {
2559   LValueBaseInfo BaseInfo;
2560   TBAAAccessInfo TBAAInfo;
2561   Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo, &TBAAInfo);
2562   return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo, TBAAInfo);
2563 }
2564 
2565 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2566                                       const Expr *E, const VarDecl *VD) {
2567   QualType T = E->getType();
2568 
2569   // If it's thread_local, emit a call to its wrapper function instead.
2570   if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2571       CGF.CGM.getCXXABI().usesThreadWrapperFunction(VD))
2572     return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2573   // Check if the variable is marked as declare target with link clause in
2574   // device codegen.
2575   if (CGF.getLangOpts().OpenMPIsDevice) {
2576     Address Addr = emitDeclTargetVarDeclLValue(CGF, VD, T);
2577     if (Addr.isValid())
2578       return CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2579   }
2580 
2581   llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2582   llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2583   V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
2584   CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2585   Address Addr(V, RealVarTy, Alignment);
2586   // Emit reference to the private copy of the variable if it is an OpenMP
2587   // threadprivate variable.
2588   if (CGF.getLangOpts().OpenMP && !CGF.getLangOpts().OpenMPSimd &&
2589       VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2590     return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
2591                                           E->getExprLoc());
2592   }
2593   LValue LV = VD->getType()->isReferenceType() ?
2594       CGF.EmitLoadOfReferenceLValue(Addr, VD->getType(),
2595                                     AlignmentSource::Decl) :
2596       CGF.MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2597   setObjCGCLValueClass(CGF.getContext(), E, LV);
2598   return LV;
2599 }
2600 
2601 static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2602                                                GlobalDecl GD) {
2603   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2604   if (FD->hasAttr<WeakRefAttr>()) {
2605     ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2606     return aliasee.getPointer();
2607   }
2608 
2609   llvm::Constant *V = CGM.GetAddrOfFunction(GD);
2610   if (!FD->hasPrototype()) {
2611     if (const FunctionProtoType *Proto =
2612             FD->getType()->getAs<FunctionProtoType>()) {
2613       // Ugly case: for a K&R-style definition, the type of the definition
2614       // isn't the same as the type of a use.  Correct for this with a
2615       // bitcast.
2616       QualType NoProtoType =
2617           CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2618       NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2619       V = llvm::ConstantExpr::getBitCast(V,
2620                                       CGM.getTypes().ConvertType(NoProtoType));
2621     }
2622   }
2623   return V;
2624 }
2625 
2626 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF, const Expr *E,
2627                                      GlobalDecl GD) {
2628   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2629   llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, GD);
2630   CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
2631   return CGF.MakeAddrLValue(V, E->getType(), Alignment,
2632                             AlignmentSource::Decl);
2633 }
2634 
2635 static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2636                                       llvm::Value *ThisValue) {
2637   QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2638   LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2639   return CGF.EmitLValueForField(LV, FD);
2640 }
2641 
2642 /// Named Registers are named metadata pointing to the register name
2643 /// which will be read from/written to as an argument to the intrinsic
2644 /// @llvm.read/write_register.
2645 /// So far, only the name is being passed down, but other options such as
2646 /// register type, allocation type or even optimization options could be
2647 /// passed down via the metadata node.
2648 static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
2649   SmallString<64> Name("llvm.named.register.");
2650   AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
2651   assert(Asm->getLabel().size() < 64-Name.size() &&
2652       "Register name too big");
2653   Name.append(Asm->getLabel());
2654   llvm::NamedMDNode *M =
2655     CGM.getModule().getOrInsertNamedMetadata(Name);
2656   if (M->getNumOperands() == 0) {
2657     llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2658                                               Asm->getLabel());
2659     llvm::Metadata *Ops[] = {Str};
2660     M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2661   }
2662 
2663   CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2664 
2665   llvm::Value *Ptr =
2666     llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2667   return LValue::MakeGlobalReg(Ptr, Alignment, VD->getType());
2668 }
2669 
2670 /// Determine whether we can emit a reference to \p VD from the current
2671 /// context, despite not necessarily having seen an odr-use of the variable in
2672 /// this context.
2673 static bool canEmitSpuriousReferenceToVariable(CodeGenFunction &CGF,
2674                                                const DeclRefExpr *E,
2675                                                const VarDecl *VD,
2676                                                bool IsConstant) {
2677   // For a variable declared in an enclosing scope, do not emit a spurious
2678   // reference even if we have a capture, as that will emit an unwarranted
2679   // reference to our capture state, and will likely generate worse code than
2680   // emitting a local copy.
2681   if (E->refersToEnclosingVariableOrCapture())
2682     return false;
2683 
2684   // For a local declaration declared in this function, we can always reference
2685   // it even if we don't have an odr-use.
2686   if (VD->hasLocalStorage()) {
2687     return VD->getDeclContext() ==
2688            dyn_cast_or_null<DeclContext>(CGF.CurCodeDecl);
2689   }
2690 
2691   // For a global declaration, we can emit a reference to it if we know
2692   // for sure that we are able to emit a definition of it.
2693   VD = VD->getDefinition(CGF.getContext());
2694   if (!VD)
2695     return false;
2696 
2697   // Don't emit a spurious reference if it might be to a variable that only
2698   // exists on a different device / target.
2699   // FIXME: This is unnecessarily broad. Check whether this would actually be a
2700   // cross-target reference.
2701   if (CGF.getLangOpts().OpenMP || CGF.getLangOpts().CUDA ||
2702       CGF.getLangOpts().OpenCL) {
2703     return false;
2704   }
2705 
2706   // We can emit a spurious reference only if the linkage implies that we'll
2707   // be emitting a non-interposable symbol that will be retained until link
2708   // time.
2709   switch (CGF.CGM.getLLVMLinkageVarDefinition(VD, IsConstant)) {
2710   case llvm::GlobalValue::ExternalLinkage:
2711   case llvm::GlobalValue::LinkOnceODRLinkage:
2712   case llvm::GlobalValue::WeakODRLinkage:
2713   case llvm::GlobalValue::InternalLinkage:
2714   case llvm::GlobalValue::PrivateLinkage:
2715     return true;
2716   default:
2717     return false;
2718   }
2719 }
2720 
2721 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
2722   const NamedDecl *ND = E->getDecl();
2723   QualType T = E->getType();
2724 
2725   assert(E->isNonOdrUse() != NOUR_Unevaluated &&
2726          "should not emit an unevaluated operand");
2727 
2728   if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2729     // Global Named registers access via intrinsics only
2730     if (VD->getStorageClass() == SC_Register &&
2731         VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
2732       return EmitGlobalNamedRegister(VD, CGM);
2733 
2734     // If this DeclRefExpr does not constitute an odr-use of the variable,
2735     // we're not permitted to emit a reference to it in general, and it might
2736     // not be captured if capture would be necessary for a use. Emit the
2737     // constant value directly instead.
2738     if (E->isNonOdrUse() == NOUR_Constant &&
2739         (VD->getType()->isReferenceType() ||
2740          !canEmitSpuriousReferenceToVariable(*this, E, VD, true))) {
2741       VD->getAnyInitializer(VD);
2742       llvm::Constant *Val = ConstantEmitter(*this).emitAbstract(
2743           E->getLocation(), *VD->evaluateValue(), VD->getType());
2744       assert(Val && "failed to emit constant expression");
2745 
2746       Address Addr = Address::invalid();
2747       if (!VD->getType()->isReferenceType()) {
2748         // Spill the constant value to a global.
2749         Addr = CGM.createUnnamedGlobalFrom(*VD, Val,
2750                                            getContext().getDeclAlign(VD));
2751         llvm::Type *VarTy = getTypes().ConvertTypeForMem(VD->getType());
2752         auto *PTy = llvm::PointerType::get(
2753             VarTy, getContext().getTargetAddressSpace(VD->getType()));
2754         if (PTy != Addr.getType())
2755           Addr = Builder.CreatePointerBitCastOrAddrSpaceCast(Addr, PTy, VarTy);
2756       } else {
2757         // Should we be using the alignment of the constant pointer we emitted?
2758         CharUnits Alignment =
2759             CGM.getNaturalTypeAlignment(E->getType(),
2760                                         /* BaseInfo= */ nullptr,
2761                                         /* TBAAInfo= */ nullptr,
2762                                         /* forPointeeType= */ true);
2763         Addr = Address(Val, ConvertTypeForMem(E->getType()), Alignment);
2764       }
2765       return MakeAddrLValue(Addr, T, AlignmentSource::Decl);
2766     }
2767 
2768     // FIXME: Handle other kinds of non-odr-use DeclRefExprs.
2769 
2770     // Check for captured variables.
2771     if (E->refersToEnclosingVariableOrCapture()) {
2772       VD = VD->getCanonicalDecl();
2773       if (auto *FD = LambdaCaptureFields.lookup(VD))
2774         return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2775       if (CapturedStmtInfo) {
2776         auto I = LocalDeclMap.find(VD);
2777         if (I != LocalDeclMap.end()) {
2778           LValue CapLVal;
2779           if (VD->getType()->isReferenceType())
2780             CapLVal = EmitLoadOfReferenceLValue(I->second, VD->getType(),
2781                                                 AlignmentSource::Decl);
2782           else
2783             CapLVal = MakeAddrLValue(I->second, T);
2784           // Mark lvalue as nontemporal if the variable is marked as nontemporal
2785           // in simd context.
2786           if (getLangOpts().OpenMP &&
2787               CGM.getOpenMPRuntime().isNontemporalDecl(VD))
2788             CapLVal.setNontemporal(/*Value=*/true);
2789           return CapLVal;
2790         }
2791         LValue CapLVal =
2792             EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2793                                     CapturedStmtInfo->getContextValue());
2794         Address LValueAddress = CapLVal.getAddress(*this);
2795         CapLVal = MakeAddrLValue(
2796             Address(LValueAddress.getPointer(), LValueAddress.getElementType(),
2797                     getContext().getDeclAlign(VD)),
2798             CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl),
2799             CapLVal.getTBAAInfo());
2800         // Mark lvalue as nontemporal if the variable is marked as nontemporal
2801         // in simd context.
2802         if (getLangOpts().OpenMP &&
2803             CGM.getOpenMPRuntime().isNontemporalDecl(VD))
2804           CapLVal.setNontemporal(/*Value=*/true);
2805         return CapLVal;
2806       }
2807 
2808       assert(isa<BlockDecl>(CurCodeDecl));
2809       Address addr = GetAddrOfBlockDecl(VD);
2810       return MakeAddrLValue(addr, T, AlignmentSource::Decl);
2811     }
2812   }
2813 
2814   // FIXME: We should be able to assert this for FunctionDecls as well!
2815   // FIXME: We should be able to assert this for all DeclRefExprs, not just
2816   // those with a valid source location.
2817   assert((ND->isUsed(false) || !isa<VarDecl>(ND) || E->isNonOdrUse() ||
2818           !E->getLocation().isValid()) &&
2819          "Should not use decl without marking it used!");
2820 
2821   if (ND->hasAttr<WeakRefAttr>()) {
2822     const auto *VD = cast<ValueDecl>(ND);
2823     ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2824     return MakeAddrLValue(Aliasee, T, AlignmentSource::Decl);
2825   }
2826 
2827   if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2828     // Check if this is a global variable.
2829     if (VD->hasLinkage() || VD->isStaticDataMember())
2830       return EmitGlobalVarDeclLValue(*this, E, VD);
2831 
2832     Address addr = Address::invalid();
2833 
2834     // The variable should generally be present in the local decl map.
2835     auto iter = LocalDeclMap.find(VD);
2836     if (iter != LocalDeclMap.end()) {
2837       addr = iter->second;
2838 
2839     // Otherwise, it might be static local we haven't emitted yet for
2840     // some reason; most likely, because it's in an outer function.
2841     } else if (VD->isStaticLocal()) {
2842       llvm::Constant *var = CGM.getOrCreateStaticVarDecl(
2843           *VD, CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false));
2844       addr = Address(
2845           var, ConvertTypeForMem(VD->getType()), getContext().getDeclAlign(VD));
2846 
2847     // No other cases for now.
2848     } else {
2849       llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2850     }
2851 
2852 
2853     // Check for OpenMP threadprivate variables.
2854     if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd &&
2855         VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2856       return EmitThreadPrivateVarDeclLValue(
2857           *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2858           E->getExprLoc());
2859     }
2860 
2861     // Drill into block byref variables.
2862     bool isBlockByref = VD->isEscapingByref();
2863     if (isBlockByref) {
2864       addr = emitBlockByrefAddress(addr, VD);
2865     }
2866 
2867     // Drill into reference types.
2868     LValue LV = VD->getType()->isReferenceType() ?
2869         EmitLoadOfReferenceLValue(addr, VD->getType(), AlignmentSource::Decl) :
2870         MakeAddrLValue(addr, T, AlignmentSource::Decl);
2871 
2872     bool isLocalStorage = VD->hasLocalStorage();
2873 
2874     bool NonGCable = isLocalStorage &&
2875                      !VD->getType()->isReferenceType() &&
2876                      !isBlockByref;
2877     if (NonGCable) {
2878       LV.getQuals().removeObjCGCAttr();
2879       LV.setNonGC(true);
2880     }
2881 
2882     bool isImpreciseLifetime =
2883       (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2884     if (isImpreciseLifetime)
2885       LV.setARCPreciseLifetime(ARCImpreciseLifetime);
2886     setObjCGCLValueClass(getContext(), E, LV);
2887     return LV;
2888   }
2889 
2890   if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
2891     LValue LV = EmitFunctionDeclLValue(*this, E, FD);
2892 
2893     // Emit debuginfo for the function declaration if the target wants to.
2894     if (getContext().getTargetInfo().allowDebugInfoForExternalRef()) {
2895       if (CGDebugInfo *DI = CGM.getModuleDebugInfo()) {
2896         auto *Fn =
2897             cast<llvm::Function>(LV.getPointer(*this)->stripPointerCasts());
2898         if (!Fn->getSubprogram())
2899           DI->EmitFunctionDecl(FD, FD->getLocation(), T, Fn);
2900       }
2901     }
2902 
2903     return LV;
2904   }
2905 
2906   // FIXME: While we're emitting a binding from an enclosing scope, all other
2907   // DeclRefExprs we see should be implicitly treated as if they also refer to
2908   // an enclosing scope.
2909   if (const auto *BD = dyn_cast<BindingDecl>(ND))
2910     return EmitLValue(BD->getBinding());
2911 
2912   // We can form DeclRefExprs naming GUID declarations when reconstituting
2913   // non-type template parameters into expressions.
2914   if (const auto *GD = dyn_cast<MSGuidDecl>(ND))
2915     return MakeAddrLValue(CGM.GetAddrOfMSGuidDecl(GD), T,
2916                           AlignmentSource::Decl);
2917 
2918   if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND))
2919     return MakeAddrLValue(CGM.GetAddrOfTemplateParamObject(TPO), T,
2920                           AlignmentSource::Decl);
2921 
2922   llvm_unreachable("Unhandled DeclRefExpr");
2923 }
2924 
2925 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2926   // __extension__ doesn't affect lvalue-ness.
2927   if (E->getOpcode() == UO_Extension)
2928     return EmitLValue(E->getSubExpr());
2929 
2930   QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
2931   switch (E->getOpcode()) {
2932   default: llvm_unreachable("Unknown unary operator lvalue!");
2933   case UO_Deref: {
2934     QualType T = E->getSubExpr()->getType()->getPointeeType();
2935     assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
2936 
2937     LValueBaseInfo BaseInfo;
2938     TBAAAccessInfo TBAAInfo;
2939     Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo,
2940                                             &TBAAInfo);
2941     LValue LV = MakeAddrLValue(Addr, T, BaseInfo, TBAAInfo);
2942     LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
2943 
2944     // We should not generate __weak write barrier on indirect reference
2945     // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2946     // But, we continue to generate __strong write barrier on indirect write
2947     // into a pointer to object.
2948     if (getLangOpts().ObjC &&
2949         getLangOpts().getGC() != LangOptions::NonGC &&
2950         LV.isObjCWeak())
2951       LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2952     return LV;
2953   }
2954   case UO_Real:
2955   case UO_Imag: {
2956     LValue LV = EmitLValue(E->getSubExpr());
2957     assert(LV.isSimple() && "real/imag on non-ordinary l-value");
2958 
2959     // __real is valid on scalars.  This is a faster way of testing that.
2960     // __imag can only produce an rvalue on scalars.
2961     if (E->getOpcode() == UO_Real &&
2962         !LV.getAddress(*this).getElementType()->isStructTy()) {
2963       assert(E->getSubExpr()->getType()->isArithmeticType());
2964       return LV;
2965     }
2966 
2967     QualType T = ExprTy->castAs<ComplexType>()->getElementType();
2968 
2969     Address Component =
2970         (E->getOpcode() == UO_Real
2971              ? emitAddrOfRealComponent(LV.getAddress(*this), LV.getType())
2972              : emitAddrOfImagComponent(LV.getAddress(*this), LV.getType()));
2973     LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo(),
2974                                    CGM.getTBAAInfoForSubobject(LV, T));
2975     ElemLV.getQuals().addQualifiers(LV.getQuals());
2976     return ElemLV;
2977   }
2978   case UO_PreInc:
2979   case UO_PreDec: {
2980     LValue LV = EmitLValue(E->getSubExpr());
2981     bool isInc = E->getOpcode() == UO_PreInc;
2982 
2983     if (E->getType()->isAnyComplexType())
2984       EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2985     else
2986       EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2987     return LV;
2988   }
2989   }
2990 }
2991 
2992 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
2993   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
2994                         E->getType(), AlignmentSource::Decl);
2995 }
2996 
2997 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
2998   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
2999                         E->getType(), AlignmentSource::Decl);
3000 }
3001 
3002 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
3003   auto SL = E->getFunctionName();
3004   assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
3005   StringRef FnName = CurFn->getName();
3006   if (FnName.startswith("\01"))
3007     FnName = FnName.substr(1);
3008   StringRef NameItems[] = {
3009       PredefinedExpr::getIdentKindName(E->getIdentKind()), FnName};
3010   std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
3011   if (auto *BD = dyn_cast_or_null<BlockDecl>(CurCodeDecl)) {
3012     std::string Name = std::string(SL->getString());
3013     if (!Name.empty()) {
3014       unsigned Discriminator =
3015           CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
3016       if (Discriminator)
3017         Name += "_" + Twine(Discriminator + 1).str();
3018       auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
3019       return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
3020     } else {
3021       auto C =
3022           CGM.GetAddrOfConstantCString(std::string(FnName), GVName.c_str());
3023       return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
3024     }
3025   }
3026   auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
3027   return MakeAddrLValue(C, E->getType(), AlignmentSource::Decl);
3028 }
3029 
3030 /// Emit a type description suitable for use by a runtime sanitizer library. The
3031 /// format of a type descriptor is
3032 ///
3033 /// \code
3034 ///   { i16 TypeKind, i16 TypeInfo }
3035 /// \endcode
3036 ///
3037 /// followed by an array of i8 containing the type name. TypeKind is 0 for an
3038 /// integer, 1 for a floating point value, and -1 for anything else.
3039 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
3040   // Only emit each type's descriptor once.
3041   if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
3042     return C;
3043 
3044   uint16_t TypeKind = -1;
3045   uint16_t TypeInfo = 0;
3046 
3047   if (T->isIntegerType()) {
3048     TypeKind = 0;
3049     TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
3050                (T->isSignedIntegerType() ? 1 : 0);
3051   } else if (T->isFloatingType()) {
3052     TypeKind = 1;
3053     TypeInfo = getContext().getTypeSize(T);
3054   }
3055 
3056   // Format the type name as if for a diagnostic, including quotes and
3057   // optionally an 'aka'.
3058   SmallString<32> Buffer;
3059   CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
3060                                     (intptr_t)T.getAsOpaquePtr(),
3061                                     StringRef(), StringRef(), None, Buffer,
3062                                     None);
3063 
3064   llvm::Constant *Components[] = {
3065     Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
3066     llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
3067   };
3068   llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
3069 
3070   auto *GV = new llvm::GlobalVariable(
3071       CGM.getModule(), Descriptor->getType(),
3072       /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
3073   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3074   CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
3075 
3076   // Remember the descriptor for this type.
3077   CGM.setTypeDescriptorInMap(T, GV);
3078 
3079   return GV;
3080 }
3081 
3082 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
3083   llvm::Type *TargetTy = IntPtrTy;
3084 
3085   if (V->getType() == TargetTy)
3086     return V;
3087 
3088   // Floating-point types which fit into intptr_t are bitcast to integers
3089   // and then passed directly (after zero-extension, if necessary).
3090   if (V->getType()->isFloatingPointTy()) {
3091     unsigned Bits = V->getType()->getPrimitiveSizeInBits().getFixedSize();
3092     if (Bits <= TargetTy->getIntegerBitWidth())
3093       V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
3094                                                          Bits));
3095   }
3096 
3097   // Integers which fit in intptr_t are zero-extended and passed directly.
3098   if (V->getType()->isIntegerTy() &&
3099       V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
3100     return Builder.CreateZExt(V, TargetTy);
3101 
3102   // Pointers are passed directly, everything else is passed by address.
3103   if (!V->getType()->isPointerTy()) {
3104     Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
3105     Builder.CreateStore(V, Ptr);
3106     V = Ptr.getPointer();
3107   }
3108   return Builder.CreatePtrToInt(V, TargetTy);
3109 }
3110 
3111 /// Emit a representation of a SourceLocation for passing to a handler
3112 /// in a sanitizer runtime library. The format for this data is:
3113 /// \code
3114 ///   struct SourceLocation {
3115 ///     const char *Filename;
3116 ///     int32_t Line, Column;
3117 ///   };
3118 /// \endcode
3119 /// For an invalid SourceLocation, the Filename pointer is null.
3120 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
3121   llvm::Constant *Filename;
3122   int Line, Column;
3123 
3124   PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
3125   if (PLoc.isValid()) {
3126     StringRef FilenameString = PLoc.getFilename();
3127 
3128     int PathComponentsToStrip =
3129         CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
3130     if (PathComponentsToStrip < 0) {
3131       assert(PathComponentsToStrip != INT_MIN);
3132       int PathComponentsToKeep = -PathComponentsToStrip;
3133       auto I = llvm::sys::path::rbegin(FilenameString);
3134       auto E = llvm::sys::path::rend(FilenameString);
3135       while (I != E && --PathComponentsToKeep)
3136         ++I;
3137 
3138       FilenameString = FilenameString.substr(I - E);
3139     } else if (PathComponentsToStrip > 0) {
3140       auto I = llvm::sys::path::begin(FilenameString);
3141       auto E = llvm::sys::path::end(FilenameString);
3142       while (I != E && PathComponentsToStrip--)
3143         ++I;
3144 
3145       if (I != E)
3146         FilenameString =
3147             FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
3148       else
3149         FilenameString = llvm::sys::path::filename(FilenameString);
3150     }
3151 
3152     auto FilenameGV =
3153         CGM.GetAddrOfConstantCString(std::string(FilenameString), ".src");
3154     CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
3155                           cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
3156     Filename = FilenameGV.getPointer();
3157     Line = PLoc.getLine();
3158     Column = PLoc.getColumn();
3159   } else {
3160     Filename = llvm::Constant::getNullValue(Int8PtrTy);
3161     Line = Column = 0;
3162   }
3163 
3164   llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
3165                             Builder.getInt32(Column)};
3166 
3167   return llvm::ConstantStruct::getAnon(Data);
3168 }
3169 
3170 namespace {
3171 /// Specify under what conditions this check can be recovered
3172 enum class CheckRecoverableKind {
3173   /// Always terminate program execution if this check fails.
3174   Unrecoverable,
3175   /// Check supports recovering, runtime has both fatal (noreturn) and
3176   /// non-fatal handlers for this check.
3177   Recoverable,
3178   /// Runtime conditionally aborts, always need to support recovery.
3179   AlwaysRecoverable
3180 };
3181 }
3182 
3183 static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
3184   assert(Kind.countPopulation() == 1);
3185   if (Kind == SanitizerKind::Function || Kind == SanitizerKind::Vptr)
3186     return CheckRecoverableKind::AlwaysRecoverable;
3187   else if (Kind == SanitizerKind::Return || Kind == SanitizerKind::Unreachable)
3188     return CheckRecoverableKind::Unrecoverable;
3189   else
3190     return CheckRecoverableKind::Recoverable;
3191 }
3192 
3193 namespace {
3194 struct SanitizerHandlerInfo {
3195   char const *const Name;
3196   unsigned Version;
3197 };
3198 }
3199 
3200 const SanitizerHandlerInfo SanitizerHandlers[] = {
3201 #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
3202     LIST_SANITIZER_CHECKS
3203 #undef SANITIZER_CHECK
3204 };
3205 
3206 static void emitCheckHandlerCall(CodeGenFunction &CGF,
3207                                  llvm::FunctionType *FnType,
3208                                  ArrayRef<llvm::Value *> FnArgs,
3209                                  SanitizerHandler CheckHandler,
3210                                  CheckRecoverableKind RecoverKind, bool IsFatal,
3211                                  llvm::BasicBlock *ContBB) {
3212   assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
3213   Optional<ApplyDebugLocation> DL;
3214   if (!CGF.Builder.getCurrentDebugLocation()) {
3215     // Ensure that the call has at least an artificial debug location.
3216     DL.emplace(CGF, SourceLocation());
3217   }
3218   bool NeedsAbortSuffix =
3219       IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
3220   bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
3221   const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
3222   const StringRef CheckName = CheckInfo.Name;
3223   std::string FnName = "__ubsan_handle_" + CheckName.str();
3224   if (CheckInfo.Version && !MinimalRuntime)
3225     FnName += "_v" + llvm::utostr(CheckInfo.Version);
3226   if (MinimalRuntime)
3227     FnName += "_minimal";
3228   if (NeedsAbortSuffix)
3229     FnName += "_abort";
3230   bool MayReturn =
3231       !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
3232 
3233   llvm::AttrBuilder B(CGF.getLLVMContext());
3234   if (!MayReturn) {
3235     B.addAttribute(llvm::Attribute::NoReturn)
3236         .addAttribute(llvm::Attribute::NoUnwind);
3237   }
3238   B.addUWTableAttr(llvm::UWTableKind::Default);
3239 
3240   llvm::FunctionCallee Fn = CGF.CGM.CreateRuntimeFunction(
3241       FnType, FnName,
3242       llvm::AttributeList::get(CGF.getLLVMContext(),
3243                                llvm::AttributeList::FunctionIndex, B),
3244       /*Local=*/true);
3245   llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
3246   if (!MayReturn) {
3247     HandlerCall->setDoesNotReturn();
3248     CGF.Builder.CreateUnreachable();
3249   } else {
3250     CGF.Builder.CreateBr(ContBB);
3251   }
3252 }
3253 
3254 void CodeGenFunction::EmitCheck(
3255     ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
3256     SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
3257     ArrayRef<llvm::Value *> DynamicArgs) {
3258   assert(IsSanitizerScope);
3259   assert(Checked.size() > 0);
3260   assert(CheckHandler >= 0 &&
3261          size_t(CheckHandler) < llvm::array_lengthof(SanitizerHandlers));
3262   const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
3263 
3264   llvm::Value *FatalCond = nullptr;
3265   llvm::Value *RecoverableCond = nullptr;
3266   llvm::Value *TrapCond = nullptr;
3267   for (int i = 0, n = Checked.size(); i < n; ++i) {
3268     llvm::Value *Check = Checked[i].first;
3269     // -fsanitize-trap= overrides -fsanitize-recover=.
3270     llvm::Value *&Cond =
3271         CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
3272             ? TrapCond
3273             : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
3274                   ? RecoverableCond
3275                   : FatalCond;
3276     Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
3277   }
3278 
3279   if (TrapCond)
3280     EmitTrapCheck(TrapCond, CheckHandler);
3281   if (!FatalCond && !RecoverableCond)
3282     return;
3283 
3284   llvm::Value *JointCond;
3285   if (FatalCond && RecoverableCond)
3286     JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
3287   else
3288     JointCond = FatalCond ? FatalCond : RecoverableCond;
3289   assert(JointCond);
3290 
3291   CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
3292   assert(SanOpts.has(Checked[0].second));
3293 #ifndef NDEBUG
3294   for (int i = 1, n = Checked.size(); i < n; ++i) {
3295     assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
3296            "All recoverable kinds in a single check must be same!");
3297     assert(SanOpts.has(Checked[i].second));
3298   }
3299 #endif
3300 
3301   llvm::BasicBlock *Cont = createBasicBlock("cont");
3302   llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
3303   llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
3304   // Give hint that we very much don't expect to execute the handler
3305   // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
3306   llvm::MDBuilder MDHelper(getLLVMContext());
3307   llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
3308   Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
3309   EmitBlock(Handlers);
3310 
3311   // Handler functions take an i8* pointing to the (handler-specific) static
3312   // information block, followed by a sequence of intptr_t arguments
3313   // representing operand values.
3314   SmallVector<llvm::Value *, 4> Args;
3315   SmallVector<llvm::Type *, 4> ArgTypes;
3316   if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
3317     Args.reserve(DynamicArgs.size() + 1);
3318     ArgTypes.reserve(DynamicArgs.size() + 1);
3319 
3320     // Emit handler arguments and create handler function type.
3321     if (!StaticArgs.empty()) {
3322       llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
3323       auto *InfoPtr =
3324           new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
3325                                    llvm::GlobalVariable::PrivateLinkage, Info);
3326       InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3327       CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
3328       Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
3329       ArgTypes.push_back(Int8PtrTy);
3330     }
3331 
3332     for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
3333       Args.push_back(EmitCheckValue(DynamicArgs[i]));
3334       ArgTypes.push_back(IntPtrTy);
3335     }
3336   }
3337 
3338   llvm::FunctionType *FnType =
3339     llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
3340 
3341   if (!FatalCond || !RecoverableCond) {
3342     // Simple case: we need to generate a single handler call, either
3343     // fatal, or non-fatal.
3344     emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
3345                          (FatalCond != nullptr), Cont);
3346   } else {
3347     // Emit two handler calls: first one for set of unrecoverable checks,
3348     // another one for recoverable.
3349     llvm::BasicBlock *NonFatalHandlerBB =
3350         createBasicBlock("non_fatal." + CheckName);
3351     llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
3352     Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
3353     EmitBlock(FatalHandlerBB);
3354     emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
3355                          NonFatalHandlerBB);
3356     EmitBlock(NonFatalHandlerBB);
3357     emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
3358                          Cont);
3359   }
3360 
3361   EmitBlock(Cont);
3362 }
3363 
3364 void CodeGenFunction::EmitCfiSlowPathCheck(
3365     SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
3366     llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
3367   llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
3368 
3369   llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
3370   llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
3371 
3372   llvm::MDBuilder MDHelper(getLLVMContext());
3373   llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
3374   BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
3375 
3376   EmitBlock(CheckBB);
3377 
3378   bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
3379 
3380   llvm::CallInst *CheckCall;
3381   llvm::FunctionCallee SlowPathFn;
3382   if (WithDiag) {
3383     llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
3384     auto *InfoPtr =
3385         new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
3386                                  llvm::GlobalVariable::PrivateLinkage, Info);
3387     InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3388     CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
3389 
3390     SlowPathFn = CGM.getModule().getOrInsertFunction(
3391         "__cfi_slowpath_diag",
3392         llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
3393                                 false));
3394     CheckCall = Builder.CreateCall(
3395         SlowPathFn, {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
3396   } else {
3397     SlowPathFn = CGM.getModule().getOrInsertFunction(
3398         "__cfi_slowpath",
3399         llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
3400     CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
3401   }
3402 
3403   CGM.setDSOLocal(
3404       cast<llvm::GlobalValue>(SlowPathFn.getCallee()->stripPointerCasts()));
3405   CheckCall->setDoesNotThrow();
3406 
3407   EmitBlock(Cont);
3408 }
3409 
3410 // Emit a stub for __cfi_check function so that the linker knows about this
3411 // symbol in LTO mode.
3412 void CodeGenFunction::EmitCfiCheckStub() {
3413   llvm::Module *M = &CGM.getModule();
3414   auto &Ctx = M->getContext();
3415   llvm::Function *F = llvm::Function::Create(
3416       llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
3417       llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
3418   CGM.setDSOLocal(F);
3419   llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
3420   // FIXME: consider emitting an intrinsic call like
3421   // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
3422   // which can be lowered in CrossDSOCFI pass to the actual contents of
3423   // __cfi_check. This would allow inlining of __cfi_check calls.
3424   llvm::CallInst::Create(
3425       llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
3426   llvm::ReturnInst::Create(Ctx, nullptr, BB);
3427 }
3428 
3429 // This function is basically a switch over the CFI failure kind, which is
3430 // extracted from CFICheckFailData (1st function argument). Each case is either
3431 // llvm.trap or a call to one of the two runtime handlers, based on
3432 // -fsanitize-trap and -fsanitize-recover settings.  Default case (invalid
3433 // failure kind) traps, but this should really never happen.  CFICheckFailData
3434 // can be nullptr if the calling module has -fsanitize-trap behavior for this
3435 // check kind; in this case __cfi_check_fail traps as well.
3436 void CodeGenFunction::EmitCfiCheckFail() {
3437   SanitizerScope SanScope(this);
3438   FunctionArgList Args;
3439   ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
3440                             ImplicitParamDecl::Other);
3441   ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
3442                             ImplicitParamDecl::Other);
3443   Args.push_back(&ArgData);
3444   Args.push_back(&ArgAddr);
3445 
3446   const CGFunctionInfo &FI =
3447     CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
3448 
3449   llvm::Function *F = llvm::Function::Create(
3450       llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
3451       llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
3452 
3453   CGM.SetLLVMFunctionAttributes(GlobalDecl(), FI, F, /*IsThunk=*/false);
3454   CGM.SetLLVMFunctionAttributesForDefinition(nullptr, F);
3455   F->setVisibility(llvm::GlobalValue::HiddenVisibility);
3456 
3457   StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
3458                 SourceLocation());
3459 
3460   // This function is not affected by NoSanitizeList. This function does
3461   // not have a source location, but "src:*" would still apply. Revert any
3462   // changes to SanOpts made in StartFunction.
3463   SanOpts = CGM.getLangOpts().Sanitize;
3464 
3465   llvm::Value *Data =
3466       EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
3467                        CGM.getContext().VoidPtrTy, ArgData.getLocation());
3468   llvm::Value *Addr =
3469       EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
3470                        CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
3471 
3472   // Data == nullptr means the calling module has trap behaviour for this check.
3473   llvm::Value *DataIsNotNullPtr =
3474       Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
3475   EmitTrapCheck(DataIsNotNullPtr, SanitizerHandler::CFICheckFail);
3476 
3477   llvm::StructType *SourceLocationTy =
3478       llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
3479   llvm::StructType *CfiCheckFailDataTy =
3480       llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
3481 
3482   llvm::Value *V = Builder.CreateConstGEP2_32(
3483       CfiCheckFailDataTy,
3484       Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
3485       0);
3486 
3487   Address CheckKindAddr(V, Int8Ty, getIntAlign());
3488   llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
3489 
3490   llvm::Value *AllVtables = llvm::MetadataAsValue::get(
3491       CGM.getLLVMContext(),
3492       llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
3493   llvm::Value *ValidVtable = Builder.CreateZExt(
3494       Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
3495                          {Addr, AllVtables}),
3496       IntPtrTy);
3497 
3498   const std::pair<int, SanitizerMask> CheckKinds[] = {
3499       {CFITCK_VCall, SanitizerKind::CFIVCall},
3500       {CFITCK_NVCall, SanitizerKind::CFINVCall},
3501       {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
3502       {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
3503       {CFITCK_ICall, SanitizerKind::CFIICall}};
3504 
3505   SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
3506   for (auto CheckKindMaskPair : CheckKinds) {
3507     int Kind = CheckKindMaskPair.first;
3508     SanitizerMask Mask = CheckKindMaskPair.second;
3509     llvm::Value *Cond =
3510         Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
3511     if (CGM.getLangOpts().Sanitize.has(Mask))
3512       EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
3513                 {Data, Addr, ValidVtable});
3514     else
3515       EmitTrapCheck(Cond, SanitizerHandler::CFICheckFail);
3516   }
3517 
3518   FinishFunction();
3519   // The only reference to this function will be created during LTO link.
3520   // Make sure it survives until then.
3521   CGM.addUsedGlobal(F);
3522 }
3523 
3524 void CodeGenFunction::EmitUnreachable(SourceLocation Loc) {
3525   if (SanOpts.has(SanitizerKind::Unreachable)) {
3526     SanitizerScope SanScope(this);
3527     EmitCheck(std::make_pair(static_cast<llvm::Value *>(Builder.getFalse()),
3528                              SanitizerKind::Unreachable),
3529               SanitizerHandler::BuiltinUnreachable,
3530               EmitCheckSourceLocation(Loc), None);
3531   }
3532   Builder.CreateUnreachable();
3533 }
3534 
3535 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked,
3536                                     SanitizerHandler CheckHandlerID) {
3537   llvm::BasicBlock *Cont = createBasicBlock("cont");
3538 
3539   // If we're optimizing, collapse all calls to trap down to just one per
3540   // check-type per function to save on code size.
3541   if (TrapBBs.size() <= CheckHandlerID)
3542     TrapBBs.resize(CheckHandlerID + 1);
3543   llvm::BasicBlock *&TrapBB = TrapBBs[CheckHandlerID];
3544 
3545   if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
3546     TrapBB = createBasicBlock("trap");
3547     Builder.CreateCondBr(Checked, Cont, TrapBB);
3548     EmitBlock(TrapBB);
3549 
3550     llvm::CallInst *TrapCall =
3551         Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::ubsantrap),
3552                            llvm::ConstantInt::get(CGM.Int8Ty, CheckHandlerID));
3553 
3554     if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3555       auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3556                                     CGM.getCodeGenOpts().TrapFuncName);
3557       TrapCall->addFnAttr(A);
3558     }
3559     TrapCall->setDoesNotReturn();
3560     TrapCall->setDoesNotThrow();
3561     Builder.CreateUnreachable();
3562   } else {
3563     auto Call = TrapBB->begin();
3564     assert(isa<llvm::CallInst>(Call) && "Expected call in trap BB");
3565 
3566     Call->applyMergedLocation(Call->getDebugLoc(),
3567                               Builder.getCurrentDebugLocation());
3568     Builder.CreateCondBr(Checked, Cont, TrapBB);
3569   }
3570 
3571   EmitBlock(Cont);
3572 }
3573 
3574 llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
3575   llvm::CallInst *TrapCall =
3576       Builder.CreateCall(CGM.getIntrinsic(IntrID));
3577 
3578   if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3579     auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3580                                   CGM.getCodeGenOpts().TrapFuncName);
3581     TrapCall->addFnAttr(A);
3582   }
3583 
3584   return TrapCall;
3585 }
3586 
3587 Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
3588                                                  LValueBaseInfo *BaseInfo,
3589                                                  TBAAAccessInfo *TBAAInfo) {
3590   assert(E->getType()->isArrayType() &&
3591          "Array to pointer decay must have array source type!");
3592 
3593   // Expressions of array type can't be bitfields or vector elements.
3594   LValue LV = EmitLValue(E);
3595   Address Addr = LV.getAddress(*this);
3596 
3597   // If the array type was an incomplete type, we need to make sure
3598   // the decay ends up being the right type.
3599   llvm::Type *NewTy = ConvertType(E->getType());
3600   Addr = Builder.CreateElementBitCast(Addr, NewTy);
3601 
3602   // Note that VLA pointers are always decayed, so we don't need to do
3603   // anything here.
3604   if (!E->getType()->isVariableArrayType()) {
3605     assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3606            "Expected pointer to array");
3607     Addr = Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
3608   }
3609 
3610   // The result of this decay conversion points to an array element within the
3611   // base lvalue. However, since TBAA currently does not support representing
3612   // accesses to elements of member arrays, we conservatively represent accesses
3613   // to the pointee object as if it had no any base lvalue specified.
3614   // TODO: Support TBAA for member arrays.
3615   QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
3616   if (BaseInfo) *BaseInfo = LV.getBaseInfo();
3617   if (TBAAInfo) *TBAAInfo = CGM.getTBAAAccessInfo(EltType);
3618 
3619   return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
3620 }
3621 
3622 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
3623 /// array to pointer, return the array subexpression.
3624 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
3625   // If this isn't just an array->pointer decay, bail out.
3626   const auto *CE = dyn_cast<CastExpr>(E);
3627   if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
3628     return nullptr;
3629 
3630   // If this is a decay from variable width array, bail out.
3631   const Expr *SubExpr = CE->getSubExpr();
3632   if (SubExpr->getType()->isVariableArrayType())
3633     return nullptr;
3634 
3635   return SubExpr;
3636 }
3637 
3638 static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3639                                           llvm::Type *elemType,
3640                                           llvm::Value *ptr,
3641                                           ArrayRef<llvm::Value*> indices,
3642                                           bool inbounds,
3643                                           bool signedIndices,
3644                                           SourceLocation loc,
3645                                     const llvm::Twine &name = "arrayidx") {
3646   if (inbounds) {
3647     return CGF.EmitCheckedInBoundsGEP(elemType, ptr, indices, signedIndices,
3648                                       CodeGenFunction::NotSubtraction, loc,
3649                                       name);
3650   } else {
3651     return CGF.Builder.CreateGEP(elemType, ptr, indices, name);
3652   }
3653 }
3654 
3655 static CharUnits getArrayElementAlign(CharUnits arrayAlign,
3656                                       llvm::Value *idx,
3657                                       CharUnits eltSize) {
3658   // If we have a constant index, we can use the exact offset of the
3659   // element we're accessing.
3660   if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3661     CharUnits offset = constantIdx->getZExtValue() * eltSize;
3662     return arrayAlign.alignmentAtOffset(offset);
3663 
3664   // Otherwise, use the worst-case alignment for any element.
3665   } else {
3666     return arrayAlign.alignmentOfArrayElement(eltSize);
3667   }
3668 }
3669 
3670 static QualType getFixedSizeElementType(const ASTContext &ctx,
3671                                         const VariableArrayType *vla) {
3672   QualType eltType;
3673   do {
3674     eltType = vla->getElementType();
3675   } while ((vla = ctx.getAsVariableArrayType(eltType)));
3676   return eltType;
3677 }
3678 
3679 /// Given an array base, check whether its member access belongs to a record
3680 /// with preserve_access_index attribute or not.
3681 static bool IsPreserveAIArrayBase(CodeGenFunction &CGF, const Expr *ArrayBase) {
3682   if (!ArrayBase || !CGF.getDebugInfo())
3683     return false;
3684 
3685   // Only support base as either a MemberExpr or DeclRefExpr.
3686   // DeclRefExpr to cover cases like:
3687   //    struct s { int a; int b[10]; };
3688   //    struct s *p;
3689   //    p[1].a
3690   // p[1] will generate a DeclRefExpr and p[1].a is a MemberExpr.
3691   // p->b[5] is a MemberExpr example.
3692   const Expr *E = ArrayBase->IgnoreImpCasts();
3693   if (const auto *ME = dyn_cast<MemberExpr>(E))
3694     return ME->getMemberDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
3695 
3696   if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3697     const auto *VarDef = dyn_cast<VarDecl>(DRE->getDecl());
3698     if (!VarDef)
3699       return false;
3700 
3701     const auto *PtrT = VarDef->getType()->getAs<PointerType>();
3702     if (!PtrT)
3703       return false;
3704 
3705     const auto *PointeeT = PtrT->getPointeeType()
3706                              ->getUnqualifiedDesugaredType();
3707     if (const auto *RecT = dyn_cast<RecordType>(PointeeT))
3708       return RecT->getDecl()->hasAttr<BPFPreserveAccessIndexAttr>();
3709     return false;
3710   }
3711 
3712   return false;
3713 }
3714 
3715 static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
3716                                      ArrayRef<llvm::Value *> indices,
3717                                      QualType eltType, bool inbounds,
3718                                      bool signedIndices, SourceLocation loc,
3719                                      QualType *arrayType = nullptr,
3720                                      const Expr *Base = nullptr,
3721                                      const llvm::Twine &name = "arrayidx") {
3722   // All the indices except that last must be zero.
3723 #ifndef NDEBUG
3724   for (auto idx : indices.drop_back())
3725     assert(isa<llvm::ConstantInt>(idx) &&
3726            cast<llvm::ConstantInt>(idx)->isZero());
3727 #endif
3728 
3729   // Determine the element size of the statically-sized base.  This is
3730   // the thing that the indices are expressed in terms of.
3731   if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3732     eltType = getFixedSizeElementType(CGF.getContext(), vla);
3733   }
3734 
3735   // We can use that to compute the best alignment of the element.
3736   CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3737   CharUnits eltAlign =
3738     getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3739 
3740   llvm::Value *eltPtr;
3741   auto LastIndex = dyn_cast<llvm::ConstantInt>(indices.back());
3742   if (!LastIndex ||
3743       (!CGF.IsInPreservedAIRegion && !IsPreserveAIArrayBase(CGF, Base))) {
3744     eltPtr = emitArraySubscriptGEP(
3745         CGF, addr.getElementType(), addr.getPointer(), indices, inbounds,
3746         signedIndices, loc, name);
3747   } else {
3748     // Remember the original array subscript for bpf target
3749     unsigned idx = LastIndex->getZExtValue();
3750     llvm::DIType *DbgInfo = nullptr;
3751     if (arrayType)
3752       DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(*arrayType, loc);
3753     eltPtr = CGF.Builder.CreatePreserveArrayAccessIndex(addr.getElementType(),
3754                                                         addr.getPointer(),
3755                                                         indices.size() - 1,
3756                                                         idx, DbgInfo);
3757   }
3758 
3759   return Address(eltPtr, CGF.ConvertTypeForMem(eltType), eltAlign);
3760 }
3761 
3762 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3763                                                bool Accessed) {
3764   // The index must always be an integer, which is not an aggregate.  Emit it
3765   // in lexical order (this complexity is, sadly, required by C++17).
3766   llvm::Value *IdxPre =
3767       (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
3768   bool SignedIndices = false;
3769   auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
3770     auto *Idx = IdxPre;
3771     if (E->getLHS() != E->getIdx()) {
3772       assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3773       Idx = EmitScalarExpr(E->getIdx());
3774     }
3775 
3776     QualType IdxTy = E->getIdx()->getType();
3777     bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
3778     SignedIndices |= IdxSigned;
3779 
3780     if (SanOpts.has(SanitizerKind::ArrayBounds))
3781       EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3782 
3783     // Extend or truncate the index type to 32 or 64-bits.
3784     if (Promote && Idx->getType() != IntPtrTy)
3785       Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3786 
3787     return Idx;
3788   };
3789   IdxPre = nullptr;
3790 
3791   // If the base is a vector type, then we are forming a vector element lvalue
3792   // with this subscript.
3793   if (E->getBase()->getType()->isVectorType() &&
3794       !isa<ExtVectorElementExpr>(E->getBase())) {
3795     // Emit the vector as an lvalue to get its address.
3796     LValue LHS = EmitLValue(E->getBase());
3797     auto *Idx = EmitIdxAfterBase(/*Promote*/false);
3798     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
3799     return LValue::MakeVectorElt(LHS.getAddress(*this), Idx,
3800                                  E->getBase()->getType(), LHS.getBaseInfo(),
3801                                  TBAAAccessInfo());
3802   }
3803 
3804   // All the other cases basically behave like simple offsetting.
3805 
3806   // Handle the extvector case we ignored above.
3807   if (isa<ExtVectorElementExpr>(E->getBase())) {
3808     LValue LV = EmitLValue(E->getBase());
3809     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3810     Address Addr = EmitExtVectorElementLValue(LV);
3811 
3812     QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
3813     Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
3814                                  SignedIndices, E->getExprLoc());
3815     return MakeAddrLValue(Addr, EltType, LV.getBaseInfo(),
3816                           CGM.getTBAAInfoForSubobject(LV, EltType));
3817   }
3818 
3819   LValueBaseInfo EltBaseInfo;
3820   TBAAAccessInfo EltTBAAInfo;
3821   Address Addr = Address::invalid();
3822   if (const VariableArrayType *vla =
3823            getContext().getAsVariableArrayType(E->getType())) {
3824     // The base must be a pointer, which is not an aggregate.  Emit
3825     // it.  It needs to be emitted first in case it's what captures
3826     // the VLA bounds.
3827     Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3828     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3829 
3830     // The element count here is the total number of non-VLA elements.
3831     llvm::Value *numElements = getVLASize(vla).NumElts;
3832 
3833     // Effectively, the multiply by the VLA size is part of the GEP.
3834     // GEP indexes are signed, and scaling an index isn't permitted to
3835     // signed-overflow, so we use the same semantics for our explicit
3836     // multiply.  We suppress this if overflow is not undefined behavior.
3837     if (getLangOpts().isSignedOverflowDefined()) {
3838       Idx = Builder.CreateMul(Idx, numElements);
3839     } else {
3840       Idx = Builder.CreateNSWMul(Idx, numElements);
3841     }
3842 
3843     Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3844                                  !getLangOpts().isSignedOverflowDefined(),
3845                                  SignedIndices, E->getExprLoc());
3846 
3847   } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3848     // Indexing over an interface, as in "NSString *P; P[4];"
3849 
3850     // Emit the base pointer.
3851     Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3852     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3853 
3854     CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3855     llvm::Value *InterfaceSizeVal =
3856         llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3857 
3858     llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
3859 
3860     // We don't necessarily build correct LLVM struct types for ObjC
3861     // interfaces, so we can't rely on GEP to do this scaling
3862     // correctly, so we need to cast to i8*.  FIXME: is this actually
3863     // true?  A lot of other things in the fragile ABI would break...
3864     llvm::Type *OrigBaseElemTy = Addr.getElementType();
3865     Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3866 
3867     // Do the GEP.
3868     CharUnits EltAlign =
3869       getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
3870     llvm::Value *EltPtr =
3871         emitArraySubscriptGEP(*this, Addr.getElementType(), Addr.getPointer(),
3872                               ScaledIdx, false, SignedIndices, E->getExprLoc());
3873     Addr = Address(EltPtr, Addr.getElementType(), EltAlign);
3874 
3875     // Cast back.
3876     Addr = Builder.CreateElementBitCast(Addr, OrigBaseElemTy);
3877   } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3878     // If this is A[i] where A is an array, the frontend will have decayed the
3879     // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
3880     // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3881     // "gep x, i" here.  Emit one "gep A, 0, i".
3882     assert(Array->getType()->isArrayType() &&
3883            "Array to pointer decay must have array source type!");
3884     LValue ArrayLV;
3885     // For simple multidimensional array indexing, set the 'accessed' flag for
3886     // better bounds-checking of the base expression.
3887     if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3888       ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3889     else
3890       ArrayLV = EmitLValue(Array);
3891     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3892 
3893     // Propagate the alignment from the array itself to the result.
3894     QualType arrayType = Array->getType();
3895     Addr = emitArraySubscriptGEP(
3896         *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
3897         E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3898         E->getExprLoc(), &arrayType, E->getBase());
3899     EltBaseInfo = ArrayLV.getBaseInfo();
3900     EltTBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, E->getType());
3901   } else {
3902     // The base must be a pointer; emit it with an estimate of its alignment.
3903     Addr = EmitPointerWithAlignment(E->getBase(), &EltBaseInfo, &EltTBAAInfo);
3904     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3905     QualType ptrType = E->getBase()->getType();
3906     Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3907                                  !getLangOpts().isSignedOverflowDefined(),
3908                                  SignedIndices, E->getExprLoc(), &ptrType,
3909                                  E->getBase());
3910   }
3911 
3912   LValue LV = MakeAddrLValue(Addr, E->getType(), EltBaseInfo, EltTBAAInfo);
3913 
3914   if (getLangOpts().ObjC &&
3915       getLangOpts().getGC() != LangOptions::NonGC) {
3916     LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
3917     setObjCGCLValueClass(getContext(), E, LV);
3918   }
3919   return LV;
3920 }
3921 
3922 LValue CodeGenFunction::EmitMatrixSubscriptExpr(const MatrixSubscriptExpr *E) {
3923   assert(
3924       !E->isIncomplete() &&
3925       "incomplete matrix subscript expressions should be rejected during Sema");
3926   LValue Base = EmitLValue(E->getBase());
3927   llvm::Value *RowIdx = EmitScalarExpr(E->getRowIdx());
3928   llvm::Value *ColIdx = EmitScalarExpr(E->getColumnIdx());
3929   llvm::Value *NumRows = Builder.getIntN(
3930       RowIdx->getType()->getScalarSizeInBits(),
3931       E->getBase()->getType()->castAs<ConstantMatrixType>()->getNumRows());
3932   llvm::Value *FinalIdx =
3933       Builder.CreateAdd(Builder.CreateMul(ColIdx, NumRows), RowIdx);
3934   return LValue::MakeMatrixElt(
3935       MaybeConvertMatrixAddress(Base.getAddress(*this), *this), FinalIdx,
3936       E->getBase()->getType(), Base.getBaseInfo(), TBAAAccessInfo());
3937 }
3938 
3939 static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
3940                                        LValueBaseInfo &BaseInfo,
3941                                        TBAAAccessInfo &TBAAInfo,
3942                                        QualType BaseTy, QualType ElTy,
3943                                        bool IsLowerBound) {
3944   LValue BaseLVal;
3945   if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3946     BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3947     if (BaseTy->isArrayType()) {
3948       Address Addr = BaseLVal.getAddress(CGF);
3949       BaseInfo = BaseLVal.getBaseInfo();
3950 
3951       // If the array type was an incomplete type, we need to make sure
3952       // the decay ends up being the right type.
3953       llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3954       Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3955 
3956       // Note that VLA pointers are always decayed, so we don't need to do
3957       // anything here.
3958       if (!BaseTy->isVariableArrayType()) {
3959         assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3960                "Expected pointer to array");
3961         Addr = CGF.Builder.CreateConstArrayGEP(Addr, 0, "arraydecay");
3962       }
3963 
3964       return CGF.Builder.CreateElementBitCast(Addr,
3965                                               CGF.ConvertTypeForMem(ElTy));
3966     }
3967     LValueBaseInfo TypeBaseInfo;
3968     TBAAAccessInfo TypeTBAAInfo;
3969     CharUnits Align =
3970         CGF.CGM.getNaturalTypeAlignment(ElTy, &TypeBaseInfo, &TypeTBAAInfo);
3971     BaseInfo.mergeForCast(TypeBaseInfo);
3972     TBAAInfo = CGF.CGM.mergeTBAAInfoForCast(TBAAInfo, TypeTBAAInfo);
3973     return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress(CGF)),
3974                    CGF.ConvertTypeForMem(ElTy), Align);
3975   }
3976   return CGF.EmitPointerWithAlignment(Base, &BaseInfo, &TBAAInfo);
3977 }
3978 
3979 LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3980                                                 bool IsLowerBound) {
3981   QualType BaseTy = OMPArraySectionExpr::getBaseOriginalType(E->getBase());
3982   QualType ResultExprTy;
3983   if (auto *AT = getContext().getAsArrayType(BaseTy))
3984     ResultExprTy = AT->getElementType();
3985   else
3986     ResultExprTy = BaseTy->getPointeeType();
3987   llvm::Value *Idx = nullptr;
3988   if (IsLowerBound || E->getColonLocFirst().isInvalid()) {
3989     // Requesting lower bound or upper bound, but without provided length and
3990     // without ':' symbol for the default length -> length = 1.
3991     // Idx = LowerBound ?: 0;
3992     if (auto *LowerBound = E->getLowerBound()) {
3993       Idx = Builder.CreateIntCast(
3994           EmitScalarExpr(LowerBound), IntPtrTy,
3995           LowerBound->getType()->hasSignedIntegerRepresentation());
3996     } else
3997       Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3998   } else {
3999     // Try to emit length or lower bound as constant. If this is possible, 1
4000     // is subtracted from constant length or lower bound. Otherwise, emit LLVM
4001     // IR (LB + Len) - 1.
4002     auto &C = CGM.getContext();
4003     auto *Length = E->getLength();
4004     llvm::APSInt ConstLength;
4005     if (Length) {
4006       // Idx = LowerBound + Length - 1;
4007       if (Optional<llvm::APSInt> CL = Length->getIntegerConstantExpr(C)) {
4008         ConstLength = CL->zextOrTrunc(PointerWidthInBits);
4009         Length = nullptr;
4010       }
4011       auto *LowerBound = E->getLowerBound();
4012       llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
4013       if (LowerBound) {
4014         if (Optional<llvm::APSInt> LB = LowerBound->getIntegerConstantExpr(C)) {
4015           ConstLowerBound = LB->zextOrTrunc(PointerWidthInBits);
4016           LowerBound = nullptr;
4017         }
4018       }
4019       if (!Length)
4020         --ConstLength;
4021       else if (!LowerBound)
4022         --ConstLowerBound;
4023 
4024       if (Length || LowerBound) {
4025         auto *LowerBoundVal =
4026             LowerBound
4027                 ? Builder.CreateIntCast(
4028                       EmitScalarExpr(LowerBound), IntPtrTy,
4029                       LowerBound->getType()->hasSignedIntegerRepresentation())
4030                 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
4031         auto *LengthVal =
4032             Length
4033                 ? Builder.CreateIntCast(
4034                       EmitScalarExpr(Length), IntPtrTy,
4035                       Length->getType()->hasSignedIntegerRepresentation())
4036                 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
4037         Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
4038                                 /*HasNUW=*/false,
4039                                 !getLangOpts().isSignedOverflowDefined());
4040         if (Length && LowerBound) {
4041           Idx = Builder.CreateSub(
4042               Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
4043               /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
4044         }
4045       } else
4046         Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
4047     } else {
4048       // Idx = ArraySize - 1;
4049       QualType ArrayTy = BaseTy->isPointerType()
4050                              ? E->getBase()->IgnoreParenImpCasts()->getType()
4051                              : BaseTy;
4052       if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
4053         Length = VAT->getSizeExpr();
4054         if (Optional<llvm::APSInt> L = Length->getIntegerConstantExpr(C)) {
4055           ConstLength = *L;
4056           Length = nullptr;
4057         }
4058       } else {
4059         auto *CAT = C.getAsConstantArrayType(ArrayTy);
4060         ConstLength = CAT->getSize();
4061       }
4062       if (Length) {
4063         auto *LengthVal = Builder.CreateIntCast(
4064             EmitScalarExpr(Length), IntPtrTy,
4065             Length->getType()->hasSignedIntegerRepresentation());
4066         Idx = Builder.CreateSub(
4067             LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
4068             /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
4069       } else {
4070         ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
4071         --ConstLength;
4072         Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
4073       }
4074     }
4075   }
4076   assert(Idx);
4077 
4078   Address EltPtr = Address::invalid();
4079   LValueBaseInfo BaseInfo;
4080   TBAAAccessInfo TBAAInfo;
4081   if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
4082     // The base must be a pointer, which is not an aggregate.  Emit
4083     // it.  It needs to be emitted first in case it's what captures
4084     // the VLA bounds.
4085     Address Base =
4086         emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, TBAAInfo,
4087                                 BaseTy, VLA->getElementType(), IsLowerBound);
4088     // The element count here is the total number of non-VLA elements.
4089     llvm::Value *NumElements = getVLASize(VLA).NumElts;
4090 
4091     // Effectively, the multiply by the VLA size is part of the GEP.
4092     // GEP indexes are signed, and scaling an index isn't permitted to
4093     // signed-overflow, so we use the same semantics for our explicit
4094     // multiply.  We suppress this if overflow is not undefined behavior.
4095     if (getLangOpts().isSignedOverflowDefined())
4096       Idx = Builder.CreateMul(Idx, NumElements);
4097     else
4098       Idx = Builder.CreateNSWMul(Idx, NumElements);
4099     EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
4100                                    !getLangOpts().isSignedOverflowDefined(),
4101                                    /*signedIndices=*/false, E->getExprLoc());
4102   } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
4103     // If this is A[i] where A is an array, the frontend will have decayed the
4104     // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
4105     // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
4106     // "gep x, i" here.  Emit one "gep A, 0, i".
4107     assert(Array->getType()->isArrayType() &&
4108            "Array to pointer decay must have array source type!");
4109     LValue ArrayLV;
4110     // For simple multidimensional array indexing, set the 'accessed' flag for
4111     // better bounds-checking of the base expression.
4112     if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
4113       ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
4114     else
4115       ArrayLV = EmitLValue(Array);
4116 
4117     // Propagate the alignment from the array itself to the result.
4118     EltPtr = emitArraySubscriptGEP(
4119         *this, ArrayLV.getAddress(*this), {CGM.getSize(CharUnits::Zero()), Idx},
4120         ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
4121         /*signedIndices=*/false, E->getExprLoc());
4122     BaseInfo = ArrayLV.getBaseInfo();
4123     TBAAInfo = CGM.getTBAAInfoForSubobject(ArrayLV, ResultExprTy);
4124   } else {
4125     Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
4126                                            TBAAInfo, BaseTy, ResultExprTy,
4127                                            IsLowerBound);
4128     EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
4129                                    !getLangOpts().isSignedOverflowDefined(),
4130                                    /*signedIndices=*/false, E->getExprLoc());
4131   }
4132 
4133   return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo, TBAAInfo);
4134 }
4135 
4136 LValue CodeGenFunction::
4137 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
4138   // Emit the base vector as an l-value.
4139   LValue Base;
4140 
4141   // ExtVectorElementExpr's base can either be a vector or pointer to vector.
4142   if (E->isArrow()) {
4143     // If it is a pointer to a vector, emit the address and form an lvalue with
4144     // it.
4145     LValueBaseInfo BaseInfo;
4146     TBAAAccessInfo TBAAInfo;
4147     Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo, &TBAAInfo);
4148     const auto *PT = E->getBase()->getType()->castAs<PointerType>();
4149     Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo, TBAAInfo);
4150     Base.getQuals().removeObjCGCAttr();
4151   } else if (E->getBase()->isGLValue()) {
4152     // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
4153     // emit the base as an lvalue.
4154     assert(E->getBase()->getType()->isVectorType());
4155     Base = EmitLValue(E->getBase());
4156   } else {
4157     // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
4158     assert(E->getBase()->getType()->isVectorType() &&
4159            "Result must be a vector");
4160     llvm::Value *Vec = EmitScalarExpr(E->getBase());
4161 
4162     // Store the vector to memory (because LValue wants an address).
4163     Address VecMem = CreateMemTemp(E->getBase()->getType());
4164     Builder.CreateStore(Vec, VecMem);
4165     Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
4166                           AlignmentSource::Decl);
4167   }
4168 
4169   QualType type =
4170     E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
4171 
4172   // Encode the element access list into a vector of unsigned indices.
4173   SmallVector<uint32_t, 4> Indices;
4174   E->getEncodedElementAccess(Indices);
4175 
4176   if (Base.isSimple()) {
4177     llvm::Constant *CV =
4178         llvm::ConstantDataVector::get(getLLVMContext(), Indices);
4179     return LValue::MakeExtVectorElt(Base.getAddress(*this), CV, type,
4180                                     Base.getBaseInfo(), TBAAAccessInfo());
4181   }
4182   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
4183 
4184   llvm::Constant *BaseElts = Base.getExtVectorElts();
4185   SmallVector<llvm::Constant *, 4> CElts;
4186 
4187   for (unsigned i = 0, e = Indices.size(); i != e; ++i)
4188     CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
4189   llvm::Constant *CV = llvm::ConstantVector::get(CElts);
4190   return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
4191                                   Base.getBaseInfo(), TBAAAccessInfo());
4192 }
4193 
4194 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
4195   if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
4196     EmitIgnoredExpr(E->getBase());
4197     return EmitDeclRefLValue(DRE);
4198   }
4199 
4200   Expr *BaseExpr = E->getBase();
4201   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
4202   LValue BaseLV;
4203   if (E->isArrow()) {
4204     LValueBaseInfo BaseInfo;
4205     TBAAAccessInfo TBAAInfo;
4206     Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo, &TBAAInfo);
4207     QualType PtrTy = BaseExpr->getType()->getPointeeType();
4208     SanitizerSet SkippedChecks;
4209     bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
4210     if (IsBaseCXXThis)
4211       SkippedChecks.set(SanitizerKind::Alignment, true);
4212     if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
4213       SkippedChecks.set(SanitizerKind::Null, true);
4214     EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
4215                   /*Alignment=*/CharUnits::Zero(), SkippedChecks);
4216     BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo, TBAAInfo);
4217   } else
4218     BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
4219 
4220   NamedDecl *ND = E->getMemberDecl();
4221   if (auto *Field = dyn_cast<FieldDecl>(ND)) {
4222     LValue LV = EmitLValueForField(BaseLV, Field);
4223     setObjCGCLValueClass(getContext(), E, LV);
4224     if (getLangOpts().OpenMP) {
4225       // If the member was explicitly marked as nontemporal, mark it as
4226       // nontemporal. If the base lvalue is marked as nontemporal, mark access
4227       // to children as nontemporal too.
4228       if ((IsWrappedCXXThis(BaseExpr) &&
4229            CGM.getOpenMPRuntime().isNontemporalDecl(Field)) ||
4230           BaseLV.isNontemporal())
4231         LV.setNontemporal(/*Value=*/true);
4232     }
4233     return LV;
4234   }
4235 
4236   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
4237     return EmitFunctionDeclLValue(*this, E, FD);
4238 
4239   llvm_unreachable("Unhandled member declaration!");
4240 }
4241 
4242 /// Given that we are currently emitting a lambda, emit an l-value for
4243 /// one of its members.
4244 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
4245   if (CurCodeDecl) {
4246     assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
4247     assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
4248   }
4249   QualType LambdaTagType =
4250     getContext().getTagDeclType(Field->getParent());
4251   LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
4252   return EmitLValueForField(LambdaLV, Field);
4253 }
4254 
4255 /// Get the field index in the debug info. The debug info structure/union
4256 /// will ignore the unnamed bitfields.
4257 unsigned CodeGenFunction::getDebugInfoFIndex(const RecordDecl *Rec,
4258                                              unsigned FieldIndex) {
4259   unsigned I = 0, Skipped = 0;
4260 
4261   for (auto F : Rec->getDefinition()->fields()) {
4262     if (I == FieldIndex)
4263       break;
4264     if (F->isUnnamedBitfield())
4265       Skipped++;
4266     I++;
4267   }
4268 
4269   return FieldIndex - Skipped;
4270 }
4271 
4272 /// Get the address of a zero-sized field within a record. The resulting
4273 /// address doesn't necessarily have the right type.
4274 static Address emitAddrOfZeroSizeField(CodeGenFunction &CGF, Address Base,
4275                                        const FieldDecl *Field) {
4276   CharUnits Offset = CGF.getContext().toCharUnitsFromBits(
4277       CGF.getContext().getFieldOffset(Field));
4278   if (Offset.isZero())
4279     return Base;
4280   Base = CGF.Builder.CreateElementBitCast(Base, CGF.Int8Ty);
4281   return CGF.Builder.CreateConstInBoundsByteGEP(Base, Offset);
4282 }
4283 
4284 /// Drill down to the storage of a field without walking into
4285 /// reference types.
4286 ///
4287 /// The resulting address doesn't necessarily have the right type.
4288 static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
4289                                       const FieldDecl *field) {
4290   if (field->isZeroSize(CGF.getContext()))
4291     return emitAddrOfZeroSizeField(CGF, base, field);
4292 
4293   const RecordDecl *rec = field->getParent();
4294 
4295   unsigned idx =
4296     CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
4297 
4298   return CGF.Builder.CreateStructGEP(base, idx, field->getName());
4299 }
4300 
4301 static Address emitPreserveStructAccess(CodeGenFunction &CGF, LValue base,
4302                                         Address addr, const FieldDecl *field) {
4303   const RecordDecl *rec = field->getParent();
4304   llvm::DIType *DbgInfo = CGF.getDebugInfo()->getOrCreateStandaloneType(
4305       base.getType(), rec->getLocation());
4306 
4307   unsigned idx =
4308       CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
4309 
4310   return CGF.Builder.CreatePreserveStructAccessIndex(
4311       addr, idx, CGF.getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo);
4312 }
4313 
4314 static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
4315   const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
4316   if (!RD)
4317     return false;
4318 
4319   if (RD->isDynamicClass())
4320     return true;
4321 
4322   for (const auto &Base : RD->bases())
4323     if (hasAnyVptr(Base.getType(), Context))
4324       return true;
4325 
4326   for (const FieldDecl *Field : RD->fields())
4327     if (hasAnyVptr(Field->getType(), Context))
4328       return true;
4329 
4330   return false;
4331 }
4332 
4333 LValue CodeGenFunction::EmitLValueForField(LValue base,
4334                                            const FieldDecl *field) {
4335   LValueBaseInfo BaseInfo = base.getBaseInfo();
4336 
4337   if (field->isBitField()) {
4338     const CGRecordLayout &RL =
4339         CGM.getTypes().getCGRecordLayout(field->getParent());
4340     const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
4341     const bool UseVolatile = isAAPCS(CGM.getTarget()) &&
4342                              CGM.getCodeGenOpts().AAPCSBitfieldWidth &&
4343                              Info.VolatileStorageSize != 0 &&
4344                              field->getType()
4345                                  .withCVRQualifiers(base.getVRQualifiers())
4346                                  .isVolatileQualified();
4347     Address Addr = base.getAddress(*this);
4348     unsigned Idx = RL.getLLVMFieldNo(field);
4349     const RecordDecl *rec = field->getParent();
4350     if (!UseVolatile) {
4351       if (!IsInPreservedAIRegion &&
4352           (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
4353         if (Idx != 0)
4354           // For structs, we GEP to the field that the record layout suggests.
4355           Addr = Builder.CreateStructGEP(Addr, Idx, field->getName());
4356       } else {
4357         llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateRecordType(
4358             getContext().getRecordType(rec), rec->getLocation());
4359         Addr = Builder.CreatePreserveStructAccessIndex(
4360             Addr, Idx, getDebugInfoFIndex(rec, field->getFieldIndex()),
4361             DbgInfo);
4362       }
4363     }
4364     const unsigned SS =
4365         UseVolatile ? Info.VolatileStorageSize : Info.StorageSize;
4366     // Get the access type.
4367     llvm::Type *FieldIntTy = llvm::Type::getIntNTy(getLLVMContext(), SS);
4368     if (Addr.getElementType() != FieldIntTy)
4369       Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
4370     if (UseVolatile) {
4371       const unsigned VolatileOffset = Info.VolatileStorageOffset.getQuantity();
4372       if (VolatileOffset)
4373         Addr = Builder.CreateConstInBoundsGEP(Addr, VolatileOffset);
4374     }
4375 
4376     QualType fieldType =
4377         field->getType().withCVRQualifiers(base.getVRQualifiers());
4378     // TODO: Support TBAA for bit fields.
4379     LValueBaseInfo FieldBaseInfo(BaseInfo.getAlignmentSource());
4380     return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo,
4381                                 TBAAAccessInfo());
4382   }
4383 
4384   // Fields of may-alias structures are may-alias themselves.
4385   // FIXME: this should get propagated down through anonymous structs
4386   // and unions.
4387   QualType FieldType = field->getType();
4388   const RecordDecl *rec = field->getParent();
4389   AlignmentSource BaseAlignSource = BaseInfo.getAlignmentSource();
4390   LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(BaseAlignSource));
4391   TBAAAccessInfo FieldTBAAInfo;
4392   if (base.getTBAAInfo().isMayAlias() ||
4393           rec->hasAttr<MayAliasAttr>() || FieldType->isVectorType()) {
4394     FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
4395   } else if (rec->isUnion()) {
4396     // TODO: Support TBAA for unions.
4397     FieldTBAAInfo = TBAAAccessInfo::getMayAliasInfo();
4398   } else {
4399     // If no base type been assigned for the base access, then try to generate
4400     // one for this base lvalue.
4401     FieldTBAAInfo = base.getTBAAInfo();
4402     if (!FieldTBAAInfo.BaseType) {
4403         FieldTBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
4404         assert(!FieldTBAAInfo.Offset &&
4405                "Nonzero offset for an access with no base type!");
4406     }
4407 
4408     // Adjust offset to be relative to the base type.
4409     const ASTRecordLayout &Layout =
4410         getContext().getASTRecordLayout(field->getParent());
4411     unsigned CharWidth = getContext().getCharWidth();
4412     if (FieldTBAAInfo.BaseType)
4413       FieldTBAAInfo.Offset +=
4414           Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
4415 
4416     // Update the final access type and size.
4417     FieldTBAAInfo.AccessType = CGM.getTBAATypeInfo(FieldType);
4418     FieldTBAAInfo.Size =
4419         getContext().getTypeSizeInChars(FieldType).getQuantity();
4420   }
4421 
4422   Address addr = base.getAddress(*this);
4423   if (auto *ClassDef = dyn_cast<CXXRecordDecl>(rec)) {
4424     if (CGM.getCodeGenOpts().StrictVTablePointers &&
4425         ClassDef->isDynamicClass()) {
4426       // Getting to any field of dynamic object requires stripping dynamic
4427       // information provided by invariant.group.  This is because accessing
4428       // fields may leak the real address of dynamic object, which could result
4429       // in miscompilation when leaked pointer would be compared.
4430       auto *stripped = Builder.CreateStripInvariantGroup(addr.getPointer());
4431       addr = Address(stripped, addr.getElementType(), addr.getAlignment());
4432     }
4433   }
4434 
4435   unsigned RecordCVR = base.getVRQualifiers();
4436   if (rec->isUnion()) {
4437     // For unions, there is no pointer adjustment.
4438     if (CGM.getCodeGenOpts().StrictVTablePointers &&
4439         hasAnyVptr(FieldType, getContext()))
4440       // Because unions can easily skip invariant.barriers, we need to add
4441       // a barrier every time CXXRecord field with vptr is referenced.
4442       addr = Builder.CreateLaunderInvariantGroup(addr);
4443 
4444     if (IsInPreservedAIRegion ||
4445         (getDebugInfo() && rec->hasAttr<BPFPreserveAccessIndexAttr>())) {
4446       // Remember the original union field index
4447       llvm::DIType *DbgInfo = getDebugInfo()->getOrCreateStandaloneType(base.getType(),
4448           rec->getLocation());
4449       addr = Address(
4450           Builder.CreatePreserveUnionAccessIndex(
4451               addr.getPointer(), getDebugInfoFIndex(rec, field->getFieldIndex()), DbgInfo),
4452           addr.getElementType(), addr.getAlignment());
4453     }
4454 
4455     if (FieldType->isReferenceType())
4456       addr = Builder.CreateElementBitCast(
4457           addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
4458   } else {
4459     if (!IsInPreservedAIRegion &&
4460         (!getDebugInfo() || !rec->hasAttr<BPFPreserveAccessIndexAttr>()))
4461       // For structs, we GEP to the field that the record layout suggests.
4462       addr = emitAddrOfFieldStorage(*this, addr, field);
4463     else
4464       // Remember the original struct field index
4465       addr = emitPreserveStructAccess(*this, base, addr, field);
4466   }
4467 
4468   // If this is a reference field, load the reference right now.
4469   if (FieldType->isReferenceType()) {
4470     LValue RefLVal =
4471         MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
4472     if (RecordCVR & Qualifiers::Volatile)
4473       RefLVal.getQuals().addVolatile();
4474     addr = EmitLoadOfReference(RefLVal, &FieldBaseInfo, &FieldTBAAInfo);
4475 
4476     // Qualifiers on the struct don't apply to the referencee.
4477     RecordCVR = 0;
4478     FieldType = FieldType->getPointeeType();
4479   }
4480 
4481   // Make sure that the address is pointing to the right type.  This is critical
4482   // for both unions and structs.  A union needs a bitcast, a struct element
4483   // will need a bitcast if the LLVM type laid out doesn't match the desired
4484   // type.
4485   addr = Builder.CreateElementBitCast(
4486       addr, CGM.getTypes().ConvertTypeForMem(FieldType), field->getName());
4487 
4488   if (field->hasAttr<AnnotateAttr>())
4489     addr = EmitFieldAnnotations(field, addr);
4490 
4491   LValue LV = MakeAddrLValue(addr, FieldType, FieldBaseInfo, FieldTBAAInfo);
4492   LV.getQuals().addCVRQualifiers(RecordCVR);
4493 
4494   // __weak attribute on a field is ignored.
4495   if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
4496     LV.getQuals().removeObjCGCAttr();
4497 
4498   return LV;
4499 }
4500 
4501 LValue
4502 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
4503                                                   const FieldDecl *Field) {
4504   QualType FieldType = Field->getType();
4505 
4506   if (!FieldType->isReferenceType())
4507     return EmitLValueForField(Base, Field);
4508 
4509   Address V = emitAddrOfFieldStorage(*this, Base.getAddress(*this), Field);
4510 
4511   // Make sure that the address is pointing to the right type.
4512   llvm::Type *llvmType = ConvertTypeForMem(FieldType);
4513   V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
4514 
4515   // TODO: Generate TBAA information that describes this access as a structure
4516   // member access and not just an access to an object of the field's type. This
4517   // should be similar to what we do in EmitLValueForField().
4518   LValueBaseInfo BaseInfo = Base.getBaseInfo();
4519   AlignmentSource FieldAlignSource = BaseInfo.getAlignmentSource();
4520   LValueBaseInfo FieldBaseInfo(getFieldAlignmentSource(FieldAlignSource));
4521   return MakeAddrLValue(V, FieldType, FieldBaseInfo,
4522                         CGM.getTBAAInfoForSubobject(Base, FieldType));
4523 }
4524 
4525 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
4526   if (E->isFileScope()) {
4527     ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
4528     return MakeAddrLValue(GlobalPtr, E->getType(), AlignmentSource::Decl);
4529   }
4530   if (E->getType()->isVariablyModifiedType())
4531     // make sure to emit the VLA size.
4532     EmitVariablyModifiedType(E->getType());
4533 
4534   Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
4535   const Expr *InitExpr = E->getInitializer();
4536   LValue Result = MakeAddrLValue(DeclPtr, E->getType(), AlignmentSource::Decl);
4537 
4538   EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
4539                    /*Init*/ true);
4540 
4541   // Block-scope compound literals are destroyed at the end of the enclosing
4542   // scope in C.
4543   if (!getLangOpts().CPlusPlus)
4544     if (QualType::DestructionKind DtorKind = E->getType().isDestructedType())
4545       pushLifetimeExtendedDestroy(getCleanupKind(DtorKind), DeclPtr,
4546                                   E->getType(), getDestroyer(DtorKind),
4547                                   DtorKind & EHCleanup);
4548 
4549   return Result;
4550 }
4551 
4552 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
4553   if (!E->isGLValue())
4554     // Initializing an aggregate temporary in C++11: T{...}.
4555     return EmitAggExprToLValue(E);
4556 
4557   // An lvalue initializer list must be initializing a reference.
4558   assert(E->isTransparent() && "non-transparent glvalue init list");
4559   return EmitLValue(E->getInit(0));
4560 }
4561 
4562 /// Emit the operand of a glvalue conditional operator. This is either a glvalue
4563 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
4564 /// LValue is returned and the current block has been terminated.
4565 static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
4566                                                     const Expr *Operand) {
4567   if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
4568     CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
4569     return None;
4570   }
4571 
4572   return CGF.EmitLValue(Operand);
4573 }
4574 
4575 LValue CodeGenFunction::
4576 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
4577   if (!expr->isGLValue()) {
4578     // ?: here should be an aggregate.
4579     assert(hasAggregateEvaluationKind(expr->getType()) &&
4580            "Unexpected conditional operator!");
4581     return EmitAggExprToLValue(expr);
4582   }
4583 
4584   OpaqueValueMapping binding(*this, expr);
4585 
4586   const Expr *condExpr = expr->getCond();
4587   bool CondExprBool;
4588   if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
4589     const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
4590     if (!CondExprBool) std::swap(live, dead);
4591 
4592     if (!ContainsLabel(dead)) {
4593       // If the true case is live, we need to track its region.
4594       if (CondExprBool)
4595         incrementProfileCounter(expr);
4596       // If a throw expression we emit it and return an undefined lvalue
4597       // because it can't be used.
4598       if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(live->IgnoreParens())) {
4599         EmitCXXThrowExpr(ThrowExpr);
4600         llvm::Type *ElemTy = ConvertType(dead->getType());
4601         llvm::Type *Ty = llvm::PointerType::getUnqual(ElemTy);
4602         return MakeAddrLValue(
4603             Address(llvm::UndefValue::get(Ty), ElemTy, CharUnits::One()),
4604             dead->getType());
4605       }
4606       return EmitLValue(live);
4607     }
4608   }
4609 
4610   llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
4611   llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
4612   llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
4613 
4614   ConditionalEvaluation eval(*this);
4615   EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
4616 
4617   // Any temporaries created here are conditional.
4618   EmitBlock(lhsBlock);
4619   incrementProfileCounter(expr);
4620   eval.begin(*this);
4621   Optional<LValue> lhs =
4622       EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
4623   eval.end(*this);
4624 
4625   if (lhs && !lhs->isSimple())
4626     return EmitUnsupportedLValue(expr, "conditional operator");
4627 
4628   lhsBlock = Builder.GetInsertBlock();
4629   if (lhs)
4630     Builder.CreateBr(contBlock);
4631 
4632   // Any temporaries created here are conditional.
4633   EmitBlock(rhsBlock);
4634   eval.begin(*this);
4635   Optional<LValue> rhs =
4636       EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
4637   eval.end(*this);
4638   if (rhs && !rhs->isSimple())
4639     return EmitUnsupportedLValue(expr, "conditional operator");
4640   rhsBlock = Builder.GetInsertBlock();
4641 
4642   EmitBlock(contBlock);
4643 
4644   if (lhs && rhs) {
4645     Address lhsAddr = lhs->getAddress(*this);
4646     Address rhsAddr = rhs->getAddress(*this);
4647     llvm::PHINode *phi = Builder.CreatePHI(lhsAddr.getType(), 2, "cond-lvalue");
4648     phi->addIncoming(lhsAddr.getPointer(), lhsBlock);
4649     phi->addIncoming(rhsAddr.getPointer(), rhsBlock);
4650     Address result(phi, lhsAddr.getElementType(),
4651                    std::min(lhsAddr.getAlignment(), rhsAddr.getAlignment()));
4652     AlignmentSource alignSource =
4653       std::max(lhs->getBaseInfo().getAlignmentSource(),
4654                rhs->getBaseInfo().getAlignmentSource());
4655     TBAAAccessInfo TBAAInfo = CGM.mergeTBAAInfoForConditionalOperator(
4656         lhs->getTBAAInfo(), rhs->getTBAAInfo());
4657     return MakeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource),
4658                           TBAAInfo);
4659   } else {
4660     assert((lhs || rhs) &&
4661            "both operands of glvalue conditional are throw-expressions?");
4662     return lhs ? *lhs : *rhs;
4663   }
4664 }
4665 
4666 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
4667 /// type. If the cast is to a reference, we can have the usual lvalue result,
4668 /// otherwise if a cast is needed by the code generator in an lvalue context,
4669 /// then it must mean that we need the address of an aggregate in order to
4670 /// access one of its members.  This can happen for all the reasons that casts
4671 /// are permitted with aggregate result, including noop aggregate casts, and
4672 /// cast from scalar to union.
4673 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
4674   switch (E->getCastKind()) {
4675   case CK_ToVoid:
4676   case CK_BitCast:
4677   case CK_LValueToRValueBitCast:
4678   case CK_ArrayToPointerDecay:
4679   case CK_FunctionToPointerDecay:
4680   case CK_NullToMemberPointer:
4681   case CK_NullToPointer:
4682   case CK_IntegralToPointer:
4683   case CK_PointerToIntegral:
4684   case CK_PointerToBoolean:
4685   case CK_VectorSplat:
4686   case CK_IntegralCast:
4687   case CK_BooleanToSignedIntegral:
4688   case CK_IntegralToBoolean:
4689   case CK_IntegralToFloating:
4690   case CK_FloatingToIntegral:
4691   case CK_FloatingToBoolean:
4692   case CK_FloatingCast:
4693   case CK_FloatingRealToComplex:
4694   case CK_FloatingComplexToReal:
4695   case CK_FloatingComplexToBoolean:
4696   case CK_FloatingComplexCast:
4697   case CK_FloatingComplexToIntegralComplex:
4698   case CK_IntegralRealToComplex:
4699   case CK_IntegralComplexToReal:
4700   case CK_IntegralComplexToBoolean:
4701   case CK_IntegralComplexCast:
4702   case CK_IntegralComplexToFloatingComplex:
4703   case CK_DerivedToBaseMemberPointer:
4704   case CK_BaseToDerivedMemberPointer:
4705   case CK_MemberPointerToBoolean:
4706   case CK_ReinterpretMemberPointer:
4707   case CK_AnyPointerToBlockPointerCast:
4708   case CK_ARCProduceObject:
4709   case CK_ARCConsumeObject:
4710   case CK_ARCReclaimReturnedObject:
4711   case CK_ARCExtendBlockObject:
4712   case CK_CopyAndAutoreleaseBlockObject:
4713   case CK_IntToOCLSampler:
4714   case CK_FloatingToFixedPoint:
4715   case CK_FixedPointToFloating:
4716   case CK_FixedPointCast:
4717   case CK_FixedPointToBoolean:
4718   case CK_FixedPointToIntegral:
4719   case CK_IntegralToFixedPoint:
4720   case CK_MatrixCast:
4721     return EmitUnsupportedLValue(E, "unexpected cast lvalue");
4722 
4723   case CK_Dependent:
4724     llvm_unreachable("dependent cast kind in IR gen!");
4725 
4726   case CK_BuiltinFnToFnPtr:
4727     llvm_unreachable("builtin functions are handled elsewhere");
4728 
4729   // These are never l-values; just use the aggregate emission code.
4730   case CK_NonAtomicToAtomic:
4731   case CK_AtomicToNonAtomic:
4732     return EmitAggExprToLValue(E);
4733 
4734   case CK_Dynamic: {
4735     LValue LV = EmitLValue(E->getSubExpr());
4736     Address V = LV.getAddress(*this);
4737     const auto *DCE = cast<CXXDynamicCastExpr>(E);
4738     return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
4739   }
4740 
4741   case CK_ConstructorConversion:
4742   case CK_UserDefinedConversion:
4743   case CK_CPointerToObjCPointerCast:
4744   case CK_BlockPointerToObjCPointerCast:
4745   case CK_LValueToRValue:
4746     return EmitLValue(E->getSubExpr());
4747 
4748   case CK_NoOp: {
4749     // CK_NoOp can model a qualification conversion, which can remove an array
4750     // bound and change the IR type.
4751     // FIXME: Once pointee types are removed from IR, remove this.
4752     LValue LV = EmitLValue(E->getSubExpr());
4753     if (LV.isSimple()) {
4754       Address V = LV.getAddress(*this);
4755       if (V.isValid()) {
4756         llvm::Type *T = ConvertTypeForMem(E->getType());
4757         if (V.getElementType() != T)
4758           LV.setAddress(Builder.CreateElementBitCast(V, T));
4759       }
4760     }
4761     return LV;
4762   }
4763 
4764   case CK_UncheckedDerivedToBase:
4765   case CK_DerivedToBase: {
4766     const auto *DerivedClassTy =
4767         E->getSubExpr()->getType()->castAs<RecordType>();
4768     auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
4769 
4770     LValue LV = EmitLValue(E->getSubExpr());
4771     Address This = LV.getAddress(*this);
4772 
4773     // Perform the derived-to-base conversion
4774     Address Base = GetAddressOfBaseClass(
4775         This, DerivedClassDecl, E->path_begin(), E->path_end(),
4776         /*NullCheckValue=*/false, E->getExprLoc());
4777 
4778     // TODO: Support accesses to members of base classes in TBAA. For now, we
4779     // conservatively pretend that the complete object is of the base class
4780     // type.
4781     return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo(),
4782                           CGM.getTBAAInfoForSubobject(LV, E->getType()));
4783   }
4784   case CK_ToUnion:
4785     return EmitAggExprToLValue(E);
4786   case CK_BaseToDerived: {
4787     const auto *DerivedClassTy = E->getType()->castAs<RecordType>();
4788     auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
4789 
4790     LValue LV = EmitLValue(E->getSubExpr());
4791 
4792     // Perform the base-to-derived conversion
4793     Address Derived = GetAddressOfDerivedClass(
4794         LV.getAddress(*this), DerivedClassDecl, E->path_begin(), E->path_end(),
4795         /*NullCheckValue=*/false);
4796 
4797     // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
4798     // performed and the object is not of the derived type.
4799     if (sanitizePerformTypeCheck())
4800       EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
4801                     Derived.getPointer(), E->getType());
4802 
4803     if (SanOpts.has(SanitizerKind::CFIDerivedCast))
4804       EmitVTablePtrCheckForCast(E->getType(), Derived,
4805                                 /*MayBeNull=*/false, CFITCK_DerivedCast,
4806                                 E->getBeginLoc());
4807 
4808     return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo(),
4809                           CGM.getTBAAInfoForSubobject(LV, E->getType()));
4810   }
4811   case CK_LValueBitCast: {
4812     // This must be a reinterpret_cast (or c-style equivalent).
4813     const auto *CE = cast<ExplicitCastExpr>(E);
4814 
4815     CGM.EmitExplicitCastExprType(CE, this);
4816     LValue LV = EmitLValue(E->getSubExpr());
4817     Address V = Builder.CreateElementBitCast(
4818         LV.getAddress(*this),
4819         ConvertTypeForMem(CE->getTypeAsWritten()->getPointeeType()));
4820 
4821     if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
4822       EmitVTablePtrCheckForCast(E->getType(), V,
4823                                 /*MayBeNull=*/false, CFITCK_UnrelatedCast,
4824                                 E->getBeginLoc());
4825 
4826     return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
4827                           CGM.getTBAAInfoForSubobject(LV, E->getType()));
4828   }
4829   case CK_AddressSpaceConversion: {
4830     LValue LV = EmitLValue(E->getSubExpr());
4831     QualType DestTy = getContext().getPointerType(E->getType());
4832     llvm::Value *V = getTargetHooks().performAddrSpaceCast(
4833         *this, LV.getPointer(*this),
4834         E->getSubExpr()->getType().getAddressSpace(),
4835         E->getType().getAddressSpace(), ConvertType(DestTy));
4836     return MakeAddrLValue(Address(V, ConvertTypeForMem(E->getType()),
4837                                   LV.getAddress(*this).getAlignment()),
4838                           E->getType(), LV.getBaseInfo(), LV.getTBAAInfo());
4839   }
4840   case CK_ObjCObjectLValueCast: {
4841     LValue LV = EmitLValue(E->getSubExpr());
4842     Address V = Builder.CreateElementBitCast(LV.getAddress(*this),
4843                                              ConvertType(E->getType()));
4844     return MakeAddrLValue(V, E->getType(), LV.getBaseInfo(),
4845                           CGM.getTBAAInfoForSubobject(LV, E->getType()));
4846   }
4847   case CK_ZeroToOCLOpaqueType:
4848     llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
4849   }
4850 
4851   llvm_unreachable("Unhandled lvalue cast kind?");
4852 }
4853 
4854 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
4855   assert(OpaqueValueMappingData::shouldBindAsLValue(e));
4856   return getOrCreateOpaqueLValueMapping(e);
4857 }
4858 
4859 LValue
4860 CodeGenFunction::getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e) {
4861   assert(OpaqueValueMapping::shouldBindAsLValue(e));
4862 
4863   llvm::DenseMap<const OpaqueValueExpr*,LValue>::iterator
4864       it = OpaqueLValues.find(e);
4865 
4866   if (it != OpaqueLValues.end())
4867     return it->second;
4868 
4869   assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
4870   return EmitLValue(e->getSourceExpr());
4871 }
4872 
4873 RValue
4874 CodeGenFunction::getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e) {
4875   assert(!OpaqueValueMapping::shouldBindAsLValue(e));
4876 
4877   llvm::DenseMap<const OpaqueValueExpr*,RValue>::iterator
4878       it = OpaqueRValues.find(e);
4879 
4880   if (it != OpaqueRValues.end())
4881     return it->second;
4882 
4883   assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
4884   return EmitAnyExpr(e->getSourceExpr());
4885 }
4886 
4887 RValue CodeGenFunction::EmitRValueForField(LValue LV,
4888                                            const FieldDecl *FD,
4889                                            SourceLocation Loc) {
4890   QualType FT = FD->getType();
4891   LValue FieldLV = EmitLValueForField(LV, FD);
4892   switch (getEvaluationKind(FT)) {
4893   case TEK_Complex:
4894     return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
4895   case TEK_Aggregate:
4896     return FieldLV.asAggregateRValue(*this);
4897   case TEK_Scalar:
4898     // This routine is used to load fields one-by-one to perform a copy, so
4899     // don't load reference fields.
4900     if (FD->getType()->isReferenceType())
4901       return RValue::get(FieldLV.getPointer(*this));
4902     // Call EmitLoadOfScalar except when the lvalue is a bitfield to emit a
4903     // primitive load.
4904     if (FieldLV.isBitField())
4905       return EmitLoadOfLValue(FieldLV, Loc);
4906     return RValue::get(EmitLoadOfScalar(FieldLV, Loc));
4907   }
4908   llvm_unreachable("bad evaluation kind");
4909 }
4910 
4911 //===--------------------------------------------------------------------===//
4912 //                             Expression Emission
4913 //===--------------------------------------------------------------------===//
4914 
4915 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
4916                                      ReturnValueSlot ReturnValue) {
4917   // Builtins never have block type.
4918   if (E->getCallee()->getType()->isBlockPointerType())
4919     return EmitBlockCallExpr(E, ReturnValue);
4920 
4921   if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
4922     return EmitCXXMemberCallExpr(CE, ReturnValue);
4923 
4924   if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
4925     return EmitCUDAKernelCallExpr(CE, ReturnValue);
4926 
4927   if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
4928     if (const CXXMethodDecl *MD =
4929           dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
4930       return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
4931 
4932   CGCallee callee = EmitCallee(E->getCallee());
4933 
4934   if (callee.isBuiltin()) {
4935     return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
4936                            E, ReturnValue);
4937   }
4938 
4939   if (callee.isPseudoDestructor()) {
4940     return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
4941   }
4942 
4943   return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
4944 }
4945 
4946 /// Emit a CallExpr without considering whether it might be a subclass.
4947 RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
4948                                            ReturnValueSlot ReturnValue) {
4949   CGCallee Callee = EmitCallee(E->getCallee());
4950   return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
4951 }
4952 
4953 static CGCallee EmitDirectCallee(CodeGenFunction &CGF, GlobalDecl GD) {
4954   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
4955 
4956   if (auto builtinID = FD->getBuiltinID()) {
4957     std::string FDInlineName = (FD->getName() + ".inline").str();
4958     // When directing calling an inline builtin, call it through it's mangled
4959     // name to make it clear it's not the actual builtin.
4960     if (FD->isInlineBuiltinDeclaration() &&
4961         CGF.CurFn->getName() != FDInlineName) {
4962       llvm::Constant *CalleePtr = EmitFunctionDeclPointer(CGF.CGM, GD);
4963       llvm::Function *Fn = llvm::cast<llvm::Function>(CalleePtr);
4964       llvm::Module *M = Fn->getParent();
4965       llvm::Function *Clone = M->getFunction(FDInlineName);
4966       if (!Clone) {
4967         Clone = llvm::Function::Create(Fn->getFunctionType(),
4968                                        llvm::GlobalValue::InternalLinkage,
4969                                        Fn->getAddressSpace(), FDInlineName, M);
4970         Clone->addFnAttr(llvm::Attribute::AlwaysInline);
4971       }
4972       return CGCallee::forDirect(Clone, GD);
4973     }
4974 
4975     // Replaceable builtins provide their own implementation of a builtin. If we
4976     // are in an inline builtin implementation, avoid trivial infinite
4977     // recursion.
4978     else
4979       return CGCallee::forBuiltin(builtinID, FD);
4980   }
4981 
4982   llvm::Constant *CalleePtr = EmitFunctionDeclPointer(CGF.CGM, GD);
4983   if (CGF.CGM.getLangOpts().CUDA && !CGF.CGM.getLangOpts().CUDAIsDevice &&
4984       FD->hasAttr<CUDAGlobalAttr>())
4985     CalleePtr = CGF.CGM.getCUDARuntime().getKernelStub(
4986         cast<llvm::GlobalValue>(CalleePtr->stripPointerCasts()));
4987 
4988   return CGCallee::forDirect(CalleePtr, GD);
4989 }
4990 
4991 CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
4992   E = E->IgnoreParens();
4993 
4994   // Look through function-to-pointer decay.
4995   if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
4996     if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
4997         ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
4998       return EmitCallee(ICE->getSubExpr());
4999     }
5000 
5001   // Resolve direct calls.
5002   } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
5003     if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
5004       return EmitDirectCallee(*this, FD);
5005     }
5006   } else if (auto ME = dyn_cast<MemberExpr>(E)) {
5007     if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
5008       EmitIgnoredExpr(ME->getBase());
5009       return EmitDirectCallee(*this, FD);
5010     }
5011 
5012   // Look through template substitutions.
5013   } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
5014     return EmitCallee(NTTP->getReplacement());
5015 
5016   // Treat pseudo-destructor calls differently.
5017   } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
5018     return CGCallee::forPseudoDestructor(PDE);
5019   }
5020 
5021   // Otherwise, we have an indirect reference.
5022   llvm::Value *calleePtr;
5023   QualType functionType;
5024   if (auto ptrType = E->getType()->getAs<PointerType>()) {
5025     calleePtr = EmitScalarExpr(E);
5026     functionType = ptrType->getPointeeType();
5027   } else {
5028     functionType = E->getType();
5029     calleePtr = EmitLValue(E).getPointer(*this);
5030   }
5031   assert(functionType->isFunctionType());
5032 
5033   GlobalDecl GD;
5034   if (const auto *VD =
5035           dyn_cast_or_null<VarDecl>(E->getReferencedDeclOfCallee()))
5036     GD = GlobalDecl(VD);
5037 
5038   CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), GD);
5039   CGCallee callee(calleeInfo, calleePtr);
5040   return callee;
5041 }
5042 
5043 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
5044   // Comma expressions just emit their LHS then their RHS as an l-value.
5045   if (E->getOpcode() == BO_Comma) {
5046     EmitIgnoredExpr(E->getLHS());
5047     EnsureInsertPoint();
5048     return EmitLValue(E->getRHS());
5049   }
5050 
5051   if (E->getOpcode() == BO_PtrMemD ||
5052       E->getOpcode() == BO_PtrMemI)
5053     return EmitPointerToDataMemberBinaryExpr(E);
5054 
5055   assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
5056 
5057   // Note that in all of these cases, __block variables need the RHS
5058   // evaluated first just in case the variable gets moved by the RHS.
5059 
5060   switch (getEvaluationKind(E->getType())) {
5061   case TEK_Scalar: {
5062     switch (E->getLHS()->getType().getObjCLifetime()) {
5063     case Qualifiers::OCL_Strong:
5064       return EmitARCStoreStrong(E, /*ignored*/ false).first;
5065 
5066     case Qualifiers::OCL_Autoreleasing:
5067       return EmitARCStoreAutoreleasing(E).first;
5068 
5069     // No reason to do any of these differently.
5070     case Qualifiers::OCL_None:
5071     case Qualifiers::OCL_ExplicitNone:
5072     case Qualifiers::OCL_Weak:
5073       break;
5074     }
5075 
5076     RValue RV = EmitAnyExpr(E->getRHS());
5077     LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
5078     if (RV.isScalar())
5079       EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
5080     EmitStoreThroughLValue(RV, LV);
5081     if (getLangOpts().OpenMP)
5082       CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(*this,
5083                                                                 E->getLHS());
5084     return LV;
5085   }
5086 
5087   case TEK_Complex:
5088     return EmitComplexAssignmentLValue(E);
5089 
5090   case TEK_Aggregate:
5091     return EmitAggExprToLValue(E);
5092   }
5093   llvm_unreachable("bad evaluation kind");
5094 }
5095 
5096 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
5097   RValue RV = EmitCallExpr(E);
5098 
5099   if (!RV.isScalar())
5100     return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
5101                           AlignmentSource::Decl);
5102 
5103   assert(E->getCallReturnType(getContext())->isReferenceType() &&
5104          "Can't have a scalar return unless the return type is a "
5105          "reference type!");
5106 
5107   return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
5108 }
5109 
5110 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
5111   // FIXME: This shouldn't require another copy.
5112   return EmitAggExprToLValue(E);
5113 }
5114 
5115 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
5116   assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
5117          && "binding l-value to type which needs a temporary");
5118   AggValueSlot Slot = CreateAggTemp(E->getType());
5119   EmitCXXConstructExpr(E, Slot);
5120   return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
5121 }
5122 
5123 LValue
5124 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
5125   return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
5126 }
5127 
5128 Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
5129   return Builder.CreateElementBitCast(CGM.GetAddrOfMSGuidDecl(E->getGuidDecl()),
5130                                       ConvertType(E->getType()));
5131 }
5132 
5133 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
5134   return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
5135                         AlignmentSource::Decl);
5136 }
5137 
5138 LValue
5139 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
5140   AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
5141   Slot.setExternallyDestructed();
5142   EmitAggExpr(E->getSubExpr(), Slot);
5143   EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
5144   return MakeAddrLValue(Slot.getAddress(), E->getType(), AlignmentSource::Decl);
5145 }
5146 
5147 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
5148   RValue RV = EmitObjCMessageExpr(E);
5149 
5150   if (!RV.isScalar())
5151     return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
5152                           AlignmentSource::Decl);
5153 
5154   assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
5155          "Can't have a scalar return unless the return type is a "
5156          "reference type!");
5157 
5158   return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
5159 }
5160 
5161 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
5162   Address V =
5163     CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
5164   return MakeAddrLValue(V, E->getType(), AlignmentSource::Decl);
5165 }
5166 
5167 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
5168                                              const ObjCIvarDecl *Ivar) {
5169   return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
5170 }
5171 
5172 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
5173                                           llvm::Value *BaseValue,
5174                                           const ObjCIvarDecl *Ivar,
5175                                           unsigned CVRQualifiers) {
5176   return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
5177                                                    Ivar, CVRQualifiers);
5178 }
5179 
5180 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
5181   // FIXME: A lot of the code below could be shared with EmitMemberExpr.
5182   llvm::Value *BaseValue = nullptr;
5183   const Expr *BaseExpr = E->getBase();
5184   Qualifiers BaseQuals;
5185   QualType ObjectTy;
5186   if (E->isArrow()) {
5187     BaseValue = EmitScalarExpr(BaseExpr);
5188     ObjectTy = BaseExpr->getType()->getPointeeType();
5189     BaseQuals = ObjectTy.getQualifiers();
5190   } else {
5191     LValue BaseLV = EmitLValue(BaseExpr);
5192     BaseValue = BaseLV.getPointer(*this);
5193     ObjectTy = BaseExpr->getType();
5194     BaseQuals = ObjectTy.getQualifiers();
5195   }
5196 
5197   LValue LV =
5198     EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
5199                       BaseQuals.getCVRQualifiers());
5200   setObjCGCLValueClass(getContext(), E, LV);
5201   return LV;
5202 }
5203 
5204 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
5205   // Can only get l-value for message expression returning aggregate type
5206   RValue RV = EmitAnyExprToTemp(E);
5207   return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
5208                         AlignmentSource::Decl);
5209 }
5210 
5211 RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
5212                                  const CallExpr *E, ReturnValueSlot ReturnValue,
5213                                  llvm::Value *Chain) {
5214   // Get the actual function type. The callee type will always be a pointer to
5215   // function type or a block pointer type.
5216   assert(CalleeType->isFunctionPointerType() &&
5217          "Call must have function pointer type!");
5218 
5219   const Decl *TargetDecl =
5220       OrigCallee.getAbstractInfo().getCalleeDecl().getDecl();
5221 
5222   CalleeType = getContext().getCanonicalType(CalleeType);
5223 
5224   auto PointeeType = cast<PointerType>(CalleeType)->getPointeeType();
5225 
5226   CGCallee Callee = OrigCallee;
5227 
5228   if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
5229       (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
5230     if (llvm::Constant *PrefixSig =
5231             CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
5232       SanitizerScope SanScope(this);
5233       // Remove any (C++17) exception specifications, to allow calling e.g. a
5234       // noexcept function through a non-noexcept pointer.
5235       auto ProtoTy =
5236         getContext().getFunctionTypeWithExceptionSpec(PointeeType, EST_None);
5237       llvm::Constant *FTRTTIConst =
5238           CGM.GetAddrOfRTTIDescriptor(ProtoTy, /*ForEH=*/true);
5239       llvm::Type *PrefixSigType = PrefixSig->getType();
5240       llvm::StructType *PrefixStructTy = llvm::StructType::get(
5241           CGM.getLLVMContext(), {PrefixSigType, Int32Ty}, /*isPacked=*/true);
5242 
5243       llvm::Value *CalleePtr = Callee.getFunctionPointer();
5244 
5245       llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
5246           CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
5247       llvm::Value *CalleeSigPtr =
5248           Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
5249       llvm::Value *CalleeSig =
5250           Builder.CreateAlignedLoad(PrefixSigType, CalleeSigPtr, getIntAlign());
5251       llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
5252 
5253       llvm::BasicBlock *Cont = createBasicBlock("cont");
5254       llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
5255       Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
5256 
5257       EmitBlock(TypeCheck);
5258       llvm::Value *CalleeRTTIPtr =
5259           Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
5260       llvm::Value *CalleeRTTIEncoded =
5261           Builder.CreateAlignedLoad(Int32Ty, CalleeRTTIPtr, getPointerAlign());
5262       llvm::Value *CalleeRTTI =
5263           DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded);
5264       llvm::Value *CalleeRTTIMatch =
5265           Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
5266       llvm::Constant *StaticData[] = {EmitCheckSourceLocation(E->getBeginLoc()),
5267                                       EmitCheckTypeDescriptor(CalleeType)};
5268       EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
5269                 SanitizerHandler::FunctionTypeMismatch, StaticData,
5270                 {CalleePtr, CalleeRTTI, FTRTTIConst});
5271 
5272       Builder.CreateBr(Cont);
5273       EmitBlock(Cont);
5274     }
5275   }
5276 
5277   const auto *FnType = cast<FunctionType>(PointeeType);
5278 
5279   // If we are checking indirect calls and this call is indirect, check that the
5280   // function pointer is a member of the bit set for the function type.
5281   if (SanOpts.has(SanitizerKind::CFIICall) &&
5282       (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
5283     SanitizerScope SanScope(this);
5284     EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
5285 
5286     llvm::Metadata *MD;
5287     if (CGM.getCodeGenOpts().SanitizeCfiICallGeneralizePointers)
5288       MD = CGM.CreateMetadataIdentifierGeneralized(QualType(FnType, 0));
5289     else
5290       MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
5291 
5292     llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
5293 
5294     llvm::Value *CalleePtr = Callee.getFunctionPointer();
5295     llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
5296     llvm::Value *TypeTest = Builder.CreateCall(
5297         CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
5298 
5299     auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
5300     llvm::Constant *StaticData[] = {
5301         llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
5302         EmitCheckSourceLocation(E->getBeginLoc()),
5303         EmitCheckTypeDescriptor(QualType(FnType, 0)),
5304     };
5305     if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
5306       EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
5307                            CastedCallee, StaticData);
5308     } else {
5309       EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
5310                 SanitizerHandler::CFICheckFail, StaticData,
5311                 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
5312     }
5313   }
5314 
5315   CallArgList Args;
5316   if (Chain)
5317     Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
5318              CGM.getContext().VoidPtrTy);
5319 
5320   // C++17 requires that we evaluate arguments to a call using assignment syntax
5321   // right-to-left, and that we evaluate arguments to certain other operators
5322   // left-to-right. Note that we allow this to override the order dictated by
5323   // the calling convention on the MS ABI, which means that parameter
5324   // destruction order is not necessarily reverse construction order.
5325   // FIXME: Revisit this based on C++ committee response to unimplementability.
5326   EvaluationOrder Order = EvaluationOrder::Default;
5327   if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
5328     if (OCE->isAssignmentOp())
5329       Order = EvaluationOrder::ForceRightToLeft;
5330     else {
5331       switch (OCE->getOperator()) {
5332       case OO_LessLess:
5333       case OO_GreaterGreater:
5334       case OO_AmpAmp:
5335       case OO_PipePipe:
5336       case OO_Comma:
5337       case OO_ArrowStar:
5338         Order = EvaluationOrder::ForceLeftToRight;
5339         break;
5340       default:
5341         break;
5342       }
5343     }
5344   }
5345 
5346   EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
5347                E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
5348 
5349   const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
5350       Args, FnType, /*ChainCall=*/Chain);
5351 
5352   // C99 6.5.2.2p6:
5353   //   If the expression that denotes the called function has a type
5354   //   that does not include a prototype, [the default argument
5355   //   promotions are performed]. If the number of arguments does not
5356   //   equal the number of parameters, the behavior is undefined. If
5357   //   the function is defined with a type that includes a prototype,
5358   //   and either the prototype ends with an ellipsis (, ...) or the
5359   //   types of the arguments after promotion are not compatible with
5360   //   the types of the parameters, the behavior is undefined. If the
5361   //   function is defined with a type that does not include a
5362   //   prototype, and the types of the arguments after promotion are
5363   //   not compatible with those of the parameters after promotion,
5364   //   the behavior is undefined [except in some trivial cases].
5365   // That is, in the general case, we should assume that a call
5366   // through an unprototyped function type works like a *non-variadic*
5367   // call.  The way we make this work is to cast to the exact type
5368   // of the promoted arguments.
5369   //
5370   // Chain calls use this same code path to add the invisible chain parameter
5371   // to the function type.
5372   if (isa<FunctionNoProtoType>(FnType) || Chain) {
5373     llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
5374     int AS = Callee.getFunctionPointer()->getType()->getPointerAddressSpace();
5375     CalleeTy = CalleeTy->getPointerTo(AS);
5376 
5377     llvm::Value *CalleePtr = Callee.getFunctionPointer();
5378     CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
5379     Callee.setFunctionPointer(CalleePtr);
5380   }
5381 
5382   // HIP function pointer contains kernel handle when it is used in triple
5383   // chevron. The kernel stub needs to be loaded from kernel handle and used
5384   // as callee.
5385   if (CGM.getLangOpts().HIP && !CGM.getLangOpts().CUDAIsDevice &&
5386       isa<CUDAKernelCallExpr>(E) &&
5387       (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
5388     llvm::Value *Handle = Callee.getFunctionPointer();
5389     auto *Cast =
5390         Builder.CreateBitCast(Handle, Handle->getType()->getPointerTo());
5391     auto *Stub = Builder.CreateLoad(
5392         Address(Cast, Handle->getType(), CGM.getPointerAlign()));
5393     Callee.setFunctionPointer(Stub);
5394   }
5395   llvm::CallBase *CallOrInvoke = nullptr;
5396   RValue Call = EmitCall(FnInfo, Callee, ReturnValue, Args, &CallOrInvoke,
5397                          E == MustTailCall, E->getExprLoc());
5398 
5399   // Generate function declaration DISuprogram in order to be used
5400   // in debug info about call sites.
5401   if (CGDebugInfo *DI = getDebugInfo()) {
5402     if (auto *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
5403       FunctionArgList Args;
5404       QualType ResTy = BuildFunctionArgList(CalleeDecl, Args);
5405       DI->EmitFuncDeclForCallSite(CallOrInvoke,
5406                                   DI->getFunctionType(CalleeDecl, ResTy, Args),
5407                                   CalleeDecl);
5408     }
5409   }
5410 
5411   return Call;
5412 }
5413 
5414 LValue CodeGenFunction::
5415 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
5416   Address BaseAddr = Address::invalid();
5417   if (E->getOpcode() == BO_PtrMemI) {
5418     BaseAddr = EmitPointerWithAlignment(E->getLHS());
5419   } else {
5420     BaseAddr = EmitLValue(E->getLHS()).getAddress(*this);
5421   }
5422 
5423   llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
5424   const auto *MPT = E->getRHS()->getType()->castAs<MemberPointerType>();
5425 
5426   LValueBaseInfo BaseInfo;
5427   TBAAAccessInfo TBAAInfo;
5428   Address MemberAddr =
5429     EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo,
5430                                     &TBAAInfo);
5431 
5432   return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo, TBAAInfo);
5433 }
5434 
5435 /// Given the address of a temporary variable, produce an r-value of
5436 /// its type.
5437 RValue CodeGenFunction::convertTempToRValue(Address addr,
5438                                             QualType type,
5439                                             SourceLocation loc) {
5440   LValue lvalue = MakeAddrLValue(addr, type, AlignmentSource::Decl);
5441   switch (getEvaluationKind(type)) {
5442   case TEK_Complex:
5443     return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
5444   case TEK_Aggregate:
5445     return lvalue.asAggregateRValue(*this);
5446   case TEK_Scalar:
5447     return RValue::get(EmitLoadOfScalar(lvalue, loc));
5448   }
5449   llvm_unreachable("bad evaluation kind");
5450 }
5451 
5452 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
5453   assert(Val->getType()->isFPOrFPVectorTy());
5454   if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
5455     return;
5456 
5457   llvm::MDBuilder MDHelper(getLLVMContext());
5458   llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
5459 
5460   cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
5461 }
5462 
5463 namespace {
5464   struct LValueOrRValue {
5465     LValue LV;
5466     RValue RV;
5467   };
5468 }
5469 
5470 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
5471                                            const PseudoObjectExpr *E,
5472                                            bool forLValue,
5473                                            AggValueSlot slot) {
5474   SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
5475 
5476   // Find the result expression, if any.
5477   const Expr *resultExpr = E->getResultExpr();
5478   LValueOrRValue result;
5479 
5480   for (PseudoObjectExpr::const_semantics_iterator
5481          i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
5482     const Expr *semantic = *i;
5483 
5484     // If this semantic expression is an opaque value, bind it
5485     // to the result of its source expression.
5486     if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
5487       // Skip unique OVEs.
5488       if (ov->isUnique()) {
5489         assert(ov != resultExpr &&
5490                "A unique OVE cannot be used as the result expression");
5491         continue;
5492       }
5493 
5494       // If this is the result expression, we may need to evaluate
5495       // directly into the slot.
5496       typedef CodeGenFunction::OpaqueValueMappingData OVMA;
5497       OVMA opaqueData;
5498       if (ov == resultExpr && ov->isPRValue() && !forLValue &&
5499           CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
5500         CGF.EmitAggExpr(ov->getSourceExpr(), slot);
5501         LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
5502                                        AlignmentSource::Decl);
5503         opaqueData = OVMA::bind(CGF, ov, LV);
5504         result.RV = slot.asRValue();
5505 
5506       // Otherwise, emit as normal.
5507       } else {
5508         opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
5509 
5510         // If this is the result, also evaluate the result now.
5511         if (ov == resultExpr) {
5512           if (forLValue)
5513             result.LV = CGF.EmitLValue(ov);
5514           else
5515             result.RV = CGF.EmitAnyExpr(ov, slot);
5516         }
5517       }
5518 
5519       opaques.push_back(opaqueData);
5520 
5521     // Otherwise, if the expression is the result, evaluate it
5522     // and remember the result.
5523     } else if (semantic == resultExpr) {
5524       if (forLValue)
5525         result.LV = CGF.EmitLValue(semantic);
5526       else
5527         result.RV = CGF.EmitAnyExpr(semantic, slot);
5528 
5529     // Otherwise, evaluate the expression in an ignored context.
5530     } else {
5531       CGF.EmitIgnoredExpr(semantic);
5532     }
5533   }
5534 
5535   // Unbind all the opaques now.
5536   for (unsigned i = 0, e = opaques.size(); i != e; ++i)
5537     opaques[i].unbind(CGF);
5538 
5539   return result;
5540 }
5541 
5542 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
5543                                                AggValueSlot slot) {
5544   return emitPseudoObjectExpr(*this, E, false, slot).RV;
5545 }
5546 
5547 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
5548   return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
5549 }
5550