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