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