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