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