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