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