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