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(), LV.getTBAAInfo());
1178     }
1179     // FIXME: Is it possible to create an ExprWithCleanups that produces a
1180     // bitfield lvalue or some other non-simple lvalue?
1181     return LV;
1182   }
1183 
1184   case Expr::CXXDefaultArgExprClass:
1185     return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
1186   case Expr::CXXDefaultInitExprClass: {
1187     CXXDefaultInitExprScope Scope(*this);
1188     return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
1189   }
1190   case Expr::CXXTypeidExprClass:
1191     return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
1192 
1193   case Expr::ObjCMessageExprClass:
1194     return EmitObjCMessageExprLValue(cast<ObjCMessageExpr>(E));
1195   case Expr::ObjCIvarRefExprClass:
1196     return EmitObjCIvarRefLValue(cast<ObjCIvarRefExpr>(E));
1197   case Expr::StmtExprClass:
1198     return EmitStmtExprLValue(cast<StmtExpr>(E));
1199   case Expr::UnaryOperatorClass:
1200     return EmitUnaryOpLValue(cast<UnaryOperator>(E));
1201   case Expr::ArraySubscriptExprClass:
1202     return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
1203   case Expr::OMPArraySectionExprClass:
1204     return EmitOMPArraySectionExpr(cast<OMPArraySectionExpr>(E));
1205   case Expr::ExtVectorElementExprClass:
1206     return EmitExtVectorElementExpr(cast<ExtVectorElementExpr>(E));
1207   case Expr::MemberExprClass:
1208     return EmitMemberExpr(cast<MemberExpr>(E));
1209   case Expr::CompoundLiteralExprClass:
1210     return EmitCompoundLiteralLValue(cast<CompoundLiteralExpr>(E));
1211   case Expr::ConditionalOperatorClass:
1212     return EmitConditionalOperatorLValue(cast<ConditionalOperator>(E));
1213   case Expr::BinaryConditionalOperatorClass:
1214     return EmitConditionalOperatorLValue(cast<BinaryConditionalOperator>(E));
1215   case Expr::ChooseExprClass:
1216     return EmitLValue(cast<ChooseExpr>(E)->getChosenSubExpr());
1217   case Expr::OpaqueValueExprClass:
1218     return EmitOpaqueValueLValue(cast<OpaqueValueExpr>(E));
1219   case Expr::SubstNonTypeTemplateParmExprClass:
1220     return EmitLValue(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement());
1221   case Expr::ImplicitCastExprClass:
1222   case Expr::CStyleCastExprClass:
1223   case Expr::CXXFunctionalCastExprClass:
1224   case Expr::CXXStaticCastExprClass:
1225   case Expr::CXXDynamicCastExprClass:
1226   case Expr::CXXReinterpretCastExprClass:
1227   case Expr::CXXConstCastExprClass:
1228   case Expr::ObjCBridgedCastExprClass:
1229     return EmitCastLValue(cast<CastExpr>(E));
1230 
1231   case Expr::MaterializeTemporaryExprClass:
1232     return EmitMaterializeTemporaryExpr(cast<MaterializeTemporaryExpr>(E));
1233 
1234   case Expr::CoawaitExprClass:
1235     return EmitCoawaitLValue(cast<CoawaitExpr>(E));
1236   case Expr::CoyieldExprClass:
1237     return EmitCoyieldLValue(cast<CoyieldExpr>(E));
1238   }
1239 }
1240 
1241 /// Given an object of the given canonical type, can we safely copy a
1242 /// value out of it based on its initializer?
1243 static bool isConstantEmittableObjectType(QualType type) {
1244   assert(type.isCanonical());
1245   assert(!type->isReferenceType());
1246 
1247   // Must be const-qualified but non-volatile.
1248   Qualifiers qs = type.getLocalQualifiers();
1249   if (!qs.hasConst() || qs.hasVolatile()) return false;
1250 
1251   // Otherwise, all object types satisfy this except C++ classes with
1252   // mutable subobjects or non-trivial copy/destroy behavior.
1253   if (const auto *RT = dyn_cast<RecordType>(type))
1254     if (const auto *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1255       if (RD->hasMutableFields() || !RD->isTrivial())
1256         return false;
1257 
1258   return true;
1259 }
1260 
1261 /// Can we constant-emit a load of a reference to a variable of the
1262 /// given type?  This is different from predicates like
1263 /// Decl::isUsableInConstantExpressions because we do want it to apply
1264 /// in situations that don't necessarily satisfy the language's rules
1265 /// for this (e.g. C++'s ODR-use rules).  For example, we want to able
1266 /// to do this with const float variables even if those variables
1267 /// aren't marked 'constexpr'.
1268 enum ConstantEmissionKind {
1269   CEK_None,
1270   CEK_AsReferenceOnly,
1271   CEK_AsValueOrReference,
1272   CEK_AsValueOnly
1273 };
1274 static ConstantEmissionKind checkVarTypeForConstantEmission(QualType type) {
1275   type = type.getCanonicalType();
1276   if (const auto *ref = dyn_cast<ReferenceType>(type)) {
1277     if (isConstantEmittableObjectType(ref->getPointeeType()))
1278       return CEK_AsValueOrReference;
1279     return CEK_AsReferenceOnly;
1280   }
1281   if (isConstantEmittableObjectType(type))
1282     return CEK_AsValueOnly;
1283   return CEK_None;
1284 }
1285 
1286 /// Try to emit a reference to the given value without producing it as
1287 /// an l-value.  This is actually more than an optimization: we can't
1288 /// produce an l-value for variables that we never actually captured
1289 /// in a block or lambda, which means const int variables or constexpr
1290 /// literals or similar.
1291 CodeGenFunction::ConstantEmission
1292 CodeGenFunction::tryEmitAsConstant(DeclRefExpr *refExpr) {
1293   ValueDecl *value = refExpr->getDecl();
1294 
1295   // The value needs to be an enum constant or a constant variable.
1296   ConstantEmissionKind CEK;
1297   if (isa<ParmVarDecl>(value)) {
1298     CEK = CEK_None;
1299   } else if (auto *var = dyn_cast<VarDecl>(value)) {
1300     CEK = checkVarTypeForConstantEmission(var->getType());
1301   } else if (isa<EnumConstantDecl>(value)) {
1302     CEK = CEK_AsValueOnly;
1303   } else {
1304     CEK = CEK_None;
1305   }
1306   if (CEK == CEK_None) return ConstantEmission();
1307 
1308   Expr::EvalResult result;
1309   bool resultIsReference;
1310   QualType resultType;
1311 
1312   // It's best to evaluate all the way as an r-value if that's permitted.
1313   if (CEK != CEK_AsReferenceOnly &&
1314       refExpr->EvaluateAsRValue(result, getContext())) {
1315     resultIsReference = false;
1316     resultType = refExpr->getType();
1317 
1318   // Otherwise, try to evaluate as an l-value.
1319   } else if (CEK != CEK_AsValueOnly &&
1320              refExpr->EvaluateAsLValue(result, getContext())) {
1321     resultIsReference = true;
1322     resultType = value->getType();
1323 
1324   // Failure.
1325   } else {
1326     return ConstantEmission();
1327   }
1328 
1329   // In any case, if the initializer has side-effects, abandon ship.
1330   if (result.HasSideEffects)
1331     return ConstantEmission();
1332 
1333   // Emit as a constant.
1334   auto C = ConstantEmitter(*this).emitAbstract(refExpr->getLocation(),
1335                                                result.Val, resultType);
1336 
1337   // Make sure we emit a debug reference to the global variable.
1338   // This should probably fire even for
1339   if (isa<VarDecl>(value)) {
1340     if (!getContext().DeclMustBeEmitted(cast<VarDecl>(value)))
1341       EmitDeclRefExprDbgValue(refExpr, result.Val);
1342   } else {
1343     assert(isa<EnumConstantDecl>(value));
1344     EmitDeclRefExprDbgValue(refExpr, result.Val);
1345   }
1346 
1347   // If we emitted a reference constant, we need to dereference that.
1348   if (resultIsReference)
1349     return ConstantEmission::forReference(C);
1350 
1351   return ConstantEmission::forValue(C);
1352 }
1353 
1354 static DeclRefExpr *tryToConvertMemberExprToDeclRefExpr(CodeGenFunction &CGF,
1355                                                         const MemberExpr *ME) {
1356   if (auto *VD = dyn_cast<VarDecl>(ME->getMemberDecl())) {
1357     // Try to emit static variable member expressions as DREs.
1358     return DeclRefExpr::Create(
1359         CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), VD,
1360         /*RefersToEnclosingVariableOrCapture=*/false, ME->getExprLoc(),
1361         ME->getType(), ME->getValueKind());
1362   }
1363   return nullptr;
1364 }
1365 
1366 CodeGenFunction::ConstantEmission
1367 CodeGenFunction::tryEmitAsConstant(const MemberExpr *ME) {
1368   if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, ME))
1369     return tryEmitAsConstant(DRE);
1370   return ConstantEmission();
1371 }
1372 
1373 llvm::Value *CodeGenFunction::EmitLoadOfScalar(LValue lvalue,
1374                                                SourceLocation Loc) {
1375   return EmitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
1376                           lvalue.getType(), Loc, lvalue.getBaseInfo(),
1377                           lvalue.getTBAAInfo(), lvalue.isNontemporal());
1378 }
1379 
1380 static bool hasBooleanRepresentation(QualType Ty) {
1381   if (Ty->isBooleanType())
1382     return true;
1383 
1384   if (const EnumType *ET = Ty->getAs<EnumType>())
1385     return ET->getDecl()->getIntegerType()->isBooleanType();
1386 
1387   if (const AtomicType *AT = Ty->getAs<AtomicType>())
1388     return hasBooleanRepresentation(AT->getValueType());
1389 
1390   return false;
1391 }
1392 
1393 static bool getRangeForType(CodeGenFunction &CGF, QualType Ty,
1394                             llvm::APInt &Min, llvm::APInt &End,
1395                             bool StrictEnums, bool IsBool) {
1396   const EnumType *ET = Ty->getAs<EnumType>();
1397   bool IsRegularCPlusPlusEnum = CGF.getLangOpts().CPlusPlus && StrictEnums &&
1398                                 ET && !ET->getDecl()->isFixed();
1399   if (!IsBool && !IsRegularCPlusPlusEnum)
1400     return false;
1401 
1402   if (IsBool) {
1403     Min = llvm::APInt(CGF.getContext().getTypeSize(Ty), 0);
1404     End = llvm::APInt(CGF.getContext().getTypeSize(Ty), 2);
1405   } else {
1406     const EnumDecl *ED = ET->getDecl();
1407     llvm::Type *LTy = CGF.ConvertTypeForMem(ED->getIntegerType());
1408     unsigned Bitwidth = LTy->getScalarSizeInBits();
1409     unsigned NumNegativeBits = ED->getNumNegativeBits();
1410     unsigned NumPositiveBits = ED->getNumPositiveBits();
1411 
1412     if (NumNegativeBits) {
1413       unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
1414       assert(NumBits <= Bitwidth);
1415       End = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
1416       Min = -End;
1417     } else {
1418       assert(NumPositiveBits <= Bitwidth);
1419       End = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
1420       Min = llvm::APInt(Bitwidth, 0);
1421     }
1422   }
1423   return true;
1424 }
1425 
1426 llvm::MDNode *CodeGenFunction::getRangeForLoadFromType(QualType Ty) {
1427   llvm::APInt Min, End;
1428   if (!getRangeForType(*this, Ty, Min, End, CGM.getCodeGenOpts().StrictEnums,
1429                        hasBooleanRepresentation(Ty)))
1430     return nullptr;
1431 
1432   llvm::MDBuilder MDHelper(getLLVMContext());
1433   return MDHelper.createRange(Min, End);
1434 }
1435 
1436 bool CodeGenFunction::EmitScalarRangeCheck(llvm::Value *Value, QualType Ty,
1437                                            SourceLocation Loc) {
1438   bool HasBoolCheck = SanOpts.has(SanitizerKind::Bool);
1439   bool HasEnumCheck = SanOpts.has(SanitizerKind::Enum);
1440   if (!HasBoolCheck && !HasEnumCheck)
1441     return false;
1442 
1443   bool IsBool = hasBooleanRepresentation(Ty) ||
1444                 NSAPI(CGM.getContext()).isObjCBOOLType(Ty);
1445   bool NeedsBoolCheck = HasBoolCheck && IsBool;
1446   bool NeedsEnumCheck = HasEnumCheck && Ty->getAs<EnumType>();
1447   if (!NeedsBoolCheck && !NeedsEnumCheck)
1448     return false;
1449 
1450   // Single-bit booleans don't need to be checked. Special-case this to avoid
1451   // a bit width mismatch when handling bitfield values. This is handled by
1452   // EmitFromMemory for the non-bitfield case.
1453   if (IsBool &&
1454       cast<llvm::IntegerType>(Value->getType())->getBitWidth() == 1)
1455     return false;
1456 
1457   llvm::APInt Min, End;
1458   if (!getRangeForType(*this, Ty, Min, End, /*StrictEnums=*/true, IsBool))
1459     return true;
1460 
1461   auto &Ctx = getLLVMContext();
1462   SanitizerScope SanScope(this);
1463   llvm::Value *Check;
1464   --End;
1465   if (!Min) {
1466     Check = Builder.CreateICmpULE(Value, llvm::ConstantInt::get(Ctx, End));
1467   } else {
1468     llvm::Value *Upper =
1469         Builder.CreateICmpSLE(Value, llvm::ConstantInt::get(Ctx, End));
1470     llvm::Value *Lower =
1471         Builder.CreateICmpSGE(Value, llvm::ConstantInt::get(Ctx, Min));
1472     Check = Builder.CreateAnd(Upper, Lower);
1473   }
1474   llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc),
1475                                   EmitCheckTypeDescriptor(Ty)};
1476   SanitizerMask Kind =
1477       NeedsEnumCheck ? SanitizerKind::Enum : SanitizerKind::Bool;
1478   EmitCheck(std::make_pair(Check, Kind), SanitizerHandler::LoadInvalidValue,
1479             StaticArgs, EmitCheckValue(Value));
1480   return true;
1481 }
1482 
1483 llvm::Value *CodeGenFunction::EmitLoadOfScalar(Address Addr, bool Volatile,
1484                                                QualType Ty,
1485                                                SourceLocation Loc,
1486                                                LValueBaseInfo BaseInfo,
1487                                                TBAAAccessInfo TBAAInfo,
1488                                                bool isNontemporal) {
1489   if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1490     // For better performance, handle vector loads differently.
1491     if (Ty->isVectorType()) {
1492       const llvm::Type *EltTy = Addr.getElementType();
1493 
1494       const auto *VTy = cast<llvm::VectorType>(EltTy);
1495 
1496       // Handle vectors of size 3 like size 4 for better performance.
1497       if (VTy->getNumElements() == 3) {
1498 
1499         // Bitcast to vec4 type.
1500         llvm::VectorType *vec4Ty =
1501             llvm::VectorType::get(VTy->getElementType(), 4);
1502         Address Cast = Builder.CreateElementBitCast(Addr, vec4Ty, "castToVec4");
1503         // Now load value.
1504         llvm::Value *V = Builder.CreateLoad(Cast, Volatile, "loadVec4");
1505 
1506         // Shuffle vector to get vec3.
1507         V = Builder.CreateShuffleVector(V, llvm::UndefValue::get(vec4Ty),
1508                                         {0, 1, 2}, "extractVec");
1509         return EmitFromMemory(V, Ty);
1510       }
1511     }
1512   }
1513 
1514   // Atomic operations have to be done on integral types.
1515   LValue AtomicLValue =
1516       LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1517   if (Ty->isAtomicType() || LValueIsSuitableForInlineAtomic(AtomicLValue)) {
1518     return EmitAtomicLoad(AtomicLValue, Loc).getScalarVal();
1519   }
1520 
1521   llvm::LoadInst *Load = Builder.CreateLoad(Addr, Volatile);
1522   if (isNontemporal) {
1523     llvm::MDNode *Node = llvm::MDNode::get(
1524         Load->getContext(), llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1525     Load->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1526   }
1527 
1528   if (BaseInfo.getMayAlias())
1529     TBAAInfo = CGM.getTBAAMayAliasAccessInfo();
1530   CGM.DecorateInstructionWithTBAA(Load, TBAAInfo);
1531 
1532   if (EmitScalarRangeCheck(Load, Ty, Loc)) {
1533     // In order to prevent the optimizer from throwing away the check, don't
1534     // attach range metadata to the load.
1535   } else if (CGM.getCodeGenOpts().OptimizationLevel > 0)
1536     if (llvm::MDNode *RangeInfo = getRangeForLoadFromType(Ty))
1537       Load->setMetadata(llvm::LLVMContext::MD_range, RangeInfo);
1538 
1539   return EmitFromMemory(Load, Ty);
1540 }
1541 
1542 llvm::Value *CodeGenFunction::EmitToMemory(llvm::Value *Value, QualType Ty) {
1543   // Bool has a different representation in memory than in registers.
1544   if (hasBooleanRepresentation(Ty)) {
1545     // This should really always be an i1, but sometimes it's already
1546     // an i8, and it's awkward to track those cases down.
1547     if (Value->getType()->isIntegerTy(1))
1548       return Builder.CreateZExt(Value, ConvertTypeForMem(Ty), "frombool");
1549     assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1550            "wrong value rep of bool");
1551   }
1552 
1553   return Value;
1554 }
1555 
1556 llvm::Value *CodeGenFunction::EmitFromMemory(llvm::Value *Value, QualType Ty) {
1557   // Bool has a different representation in memory than in registers.
1558   if (hasBooleanRepresentation(Ty)) {
1559     assert(Value->getType()->isIntegerTy(getContext().getTypeSize(Ty)) &&
1560            "wrong value rep of bool");
1561     return Builder.CreateTrunc(Value, Builder.getInt1Ty(), "tobool");
1562   }
1563 
1564   return Value;
1565 }
1566 
1567 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, Address Addr,
1568                                         bool Volatile, QualType Ty,
1569                                         LValueBaseInfo BaseInfo,
1570                                         TBAAAccessInfo TBAAInfo,
1571                                         bool isInit, bool isNontemporal) {
1572   if (!CGM.getCodeGenOpts().PreserveVec3Type) {
1573     // Handle vectors differently to get better performance.
1574     if (Ty->isVectorType()) {
1575       llvm::Type *SrcTy = Value->getType();
1576       auto *VecTy = dyn_cast<llvm::VectorType>(SrcTy);
1577       // Handle vec3 special.
1578       if (VecTy && VecTy->getNumElements() == 3) {
1579         // Our source is a vec3, do a shuffle vector to make it a vec4.
1580         llvm::Constant *Mask[] = {Builder.getInt32(0), Builder.getInt32(1),
1581                                   Builder.getInt32(2),
1582                                   llvm::UndefValue::get(Builder.getInt32Ty())};
1583         llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1584         Value = Builder.CreateShuffleVector(Value, llvm::UndefValue::get(VecTy),
1585                                             MaskV, "extractVec");
1586         SrcTy = llvm::VectorType::get(VecTy->getElementType(), 4);
1587       }
1588       if (Addr.getElementType() != SrcTy) {
1589         Addr = Builder.CreateElementBitCast(Addr, SrcTy, "storetmp");
1590       }
1591     }
1592   }
1593 
1594   Value = EmitToMemory(Value, Ty);
1595 
1596   LValue AtomicLValue =
1597       LValue::MakeAddr(Addr, Ty, getContext(), BaseInfo, TBAAInfo);
1598   if (Ty->isAtomicType() ||
1599       (!isInit && LValueIsSuitableForInlineAtomic(AtomicLValue))) {
1600     EmitAtomicStore(RValue::get(Value), AtomicLValue, isInit);
1601     return;
1602   }
1603 
1604   llvm::StoreInst *Store = Builder.CreateStore(Value, Addr, Volatile);
1605   if (isNontemporal) {
1606     llvm::MDNode *Node =
1607         llvm::MDNode::get(Store->getContext(),
1608                           llvm::ConstantAsMetadata::get(Builder.getInt32(1)));
1609     Store->setMetadata(CGM.getModule().getMDKindID("nontemporal"), Node);
1610   }
1611 
1612   if (BaseInfo.getMayAlias())
1613     TBAAInfo = CGM.getTBAAMayAliasAccessInfo();
1614   CGM.DecorateInstructionWithTBAA(Store, TBAAInfo);
1615 }
1616 
1617 void CodeGenFunction::EmitStoreOfScalar(llvm::Value *value, LValue lvalue,
1618                                         bool isInit) {
1619   EmitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
1620                     lvalue.getType(), lvalue.getBaseInfo(),
1621                     lvalue.getTBAAInfo(), isInit, lvalue.isNontemporal());
1622 }
1623 
1624 /// EmitLoadOfLValue - Given an expression that represents a value lvalue, this
1625 /// method emits the address of the lvalue, then loads the result as an rvalue,
1626 /// returning the rvalue.
1627 RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
1628   if (LV.isObjCWeak()) {
1629     // load of a __weak object.
1630     Address AddrWeakObj = LV.getAddress();
1631     return RValue::get(CGM.getObjCRuntime().EmitObjCWeakRead(*this,
1632                                                              AddrWeakObj));
1633   }
1634   if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
1635     // In MRC mode, we do a load+autorelease.
1636     if (!getLangOpts().ObjCAutoRefCount) {
1637       return RValue::get(EmitARCLoadWeak(LV.getAddress()));
1638     }
1639 
1640     // In ARC mode, we load retained and then consume the value.
1641     llvm::Value *Object = EmitARCLoadWeakRetained(LV.getAddress());
1642     Object = EmitObjCConsumeObject(LV.getType(), Object);
1643     return RValue::get(Object);
1644   }
1645 
1646   if (LV.isSimple()) {
1647     assert(!LV.getType()->isFunctionType());
1648 
1649     // Everything needs a load.
1650     return RValue::get(EmitLoadOfScalar(LV, Loc));
1651   }
1652 
1653   if (LV.isVectorElt()) {
1654     llvm::LoadInst *Load = Builder.CreateLoad(LV.getVectorAddress(),
1655                                               LV.isVolatileQualified());
1656     return RValue::get(Builder.CreateExtractElement(Load, LV.getVectorIdx(),
1657                                                     "vecext"));
1658   }
1659 
1660   // If this is a reference to a subset of the elements of a vector, either
1661   // shuffle the input or extract/insert them as appropriate.
1662   if (LV.isExtVectorElt())
1663     return EmitLoadOfExtVectorElementLValue(LV);
1664 
1665   // Global Register variables always invoke intrinsics
1666   if (LV.isGlobalReg())
1667     return EmitLoadOfGlobalRegLValue(LV);
1668 
1669   assert(LV.isBitField() && "Unknown LValue type!");
1670   return EmitLoadOfBitfieldLValue(LV, Loc);
1671 }
1672 
1673 RValue CodeGenFunction::EmitLoadOfBitfieldLValue(LValue LV,
1674                                                  SourceLocation Loc) {
1675   const CGBitFieldInfo &Info = LV.getBitFieldInfo();
1676 
1677   // Get the output type.
1678   llvm::Type *ResLTy = ConvertType(LV.getType());
1679 
1680   Address Ptr = LV.getBitFieldAddress();
1681   llvm::Value *Val = Builder.CreateLoad(Ptr, LV.isVolatileQualified(), "bf.load");
1682 
1683   if (Info.IsSigned) {
1684     assert(static_cast<unsigned>(Info.Offset + Info.Size) <= Info.StorageSize);
1685     unsigned HighBits = Info.StorageSize - Info.Offset - Info.Size;
1686     if (HighBits)
1687       Val = Builder.CreateShl(Val, HighBits, "bf.shl");
1688     if (Info.Offset + HighBits)
1689       Val = Builder.CreateAShr(Val, Info.Offset + HighBits, "bf.ashr");
1690   } else {
1691     if (Info.Offset)
1692       Val = Builder.CreateLShr(Val, Info.Offset, "bf.lshr");
1693     if (static_cast<unsigned>(Info.Offset) + Info.Size < Info.StorageSize)
1694       Val = Builder.CreateAnd(Val, llvm::APInt::getLowBitsSet(Info.StorageSize,
1695                                                               Info.Size),
1696                               "bf.clear");
1697   }
1698   Val = Builder.CreateIntCast(Val, ResLTy, Info.IsSigned, "bf.cast");
1699   EmitScalarRangeCheck(Val, LV.getType(), Loc);
1700   return RValue::get(Val);
1701 }
1702 
1703 // If this is a reference to a subset of the elements of a vector, create an
1704 // appropriate shufflevector.
1705 RValue CodeGenFunction::EmitLoadOfExtVectorElementLValue(LValue LV) {
1706   llvm::Value *Vec = Builder.CreateLoad(LV.getExtVectorAddress(),
1707                                         LV.isVolatileQualified());
1708 
1709   const llvm::Constant *Elts = LV.getExtVectorElts();
1710 
1711   // If the result of the expression is a non-vector type, we must be extracting
1712   // a single element.  Just codegen as an extractelement.
1713   const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1714   if (!ExprVT) {
1715     unsigned InIdx = getAccessedFieldNo(0, Elts);
1716     llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
1717     return RValue::get(Builder.CreateExtractElement(Vec, Elt));
1718   }
1719 
1720   // Always use shuffle vector to try to retain the original program structure
1721   unsigned NumResultElts = ExprVT->getNumElements();
1722 
1723   SmallVector<llvm::Constant*, 4> Mask;
1724   for (unsigned i = 0; i != NumResultElts; ++i)
1725     Mask.push_back(Builder.getInt32(getAccessedFieldNo(i, Elts)));
1726 
1727   llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1728   Vec = Builder.CreateShuffleVector(Vec, llvm::UndefValue::get(Vec->getType()),
1729                                     MaskV);
1730   return RValue::get(Vec);
1731 }
1732 
1733 /// @brief Generates lvalue for partial ext_vector access.
1734 Address CodeGenFunction::EmitExtVectorElementLValue(LValue LV) {
1735   Address VectorAddress = LV.getExtVectorAddress();
1736   const VectorType *ExprVT = LV.getType()->getAs<VectorType>();
1737   QualType EQT = ExprVT->getElementType();
1738   llvm::Type *VectorElementTy = CGM.getTypes().ConvertType(EQT);
1739 
1740   Address CastToPointerElement =
1741     Builder.CreateElementBitCast(VectorAddress, VectorElementTy,
1742                                  "conv.ptr.element");
1743 
1744   const llvm::Constant *Elts = LV.getExtVectorElts();
1745   unsigned ix = getAccessedFieldNo(0, Elts);
1746 
1747   Address VectorBasePtrPlusIx =
1748     Builder.CreateConstInBoundsGEP(CastToPointerElement, ix,
1749                                    getContext().getTypeSizeInChars(EQT),
1750                                    "vector.elt");
1751 
1752   return VectorBasePtrPlusIx;
1753 }
1754 
1755 /// @brief Load of global gamed gegisters are always calls to intrinsics.
1756 RValue CodeGenFunction::EmitLoadOfGlobalRegLValue(LValue LV) {
1757   assert((LV.getType()->isIntegerType() || LV.getType()->isPointerType()) &&
1758          "Bad type for register variable");
1759   llvm::MDNode *RegName = cast<llvm::MDNode>(
1760       cast<llvm::MetadataAsValue>(LV.getGlobalReg())->getMetadata());
1761 
1762   // We accept integer and pointer types only
1763   llvm::Type *OrigTy = CGM.getTypes().ConvertType(LV.getType());
1764   llvm::Type *Ty = OrigTy;
1765   if (OrigTy->isPointerTy())
1766     Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
1767   llvm::Type *Types[] = { Ty };
1768 
1769   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::read_register, Types);
1770   llvm::Value *Call = Builder.CreateCall(
1771       F, llvm::MetadataAsValue::get(Ty->getContext(), RegName));
1772   if (OrigTy->isPointerTy())
1773     Call = Builder.CreateIntToPtr(Call, OrigTy);
1774   return RValue::get(Call);
1775 }
1776 
1777 
1778 /// EmitStoreThroughLValue - Store the specified rvalue into the specified
1779 /// lvalue, where both are guaranteed to the have the same type, and that type
1780 /// is 'Ty'.
1781 void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
1782                                              bool isInit) {
1783   if (!Dst.isSimple()) {
1784     if (Dst.isVectorElt()) {
1785       // Read/modify/write the vector, inserting the new element.
1786       llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddress(),
1787                                             Dst.isVolatileQualified());
1788       Vec = Builder.CreateInsertElement(Vec, Src.getScalarVal(),
1789                                         Dst.getVectorIdx(), "vecins");
1790       Builder.CreateStore(Vec, Dst.getVectorAddress(),
1791                           Dst.isVolatileQualified());
1792       return;
1793     }
1794 
1795     // If this is an update of extended vector elements, insert them as
1796     // appropriate.
1797     if (Dst.isExtVectorElt())
1798       return EmitStoreThroughExtVectorComponentLValue(Src, Dst);
1799 
1800     if (Dst.isGlobalReg())
1801       return EmitStoreThroughGlobalRegLValue(Src, Dst);
1802 
1803     assert(Dst.isBitField() && "Unknown LValue type");
1804     return EmitStoreThroughBitfieldLValue(Src, Dst);
1805   }
1806 
1807   // There's special magic for assigning into an ARC-qualified l-value.
1808   if (Qualifiers::ObjCLifetime Lifetime = Dst.getQuals().getObjCLifetime()) {
1809     switch (Lifetime) {
1810     case Qualifiers::OCL_None:
1811       llvm_unreachable("present but none");
1812 
1813     case Qualifiers::OCL_ExplicitNone:
1814       // nothing special
1815       break;
1816 
1817     case Qualifiers::OCL_Strong:
1818       if (isInit) {
1819         Src = RValue::get(EmitARCRetain(Dst.getType(), Src.getScalarVal()));
1820         break;
1821       }
1822       EmitARCStoreStrong(Dst, Src.getScalarVal(), /*ignore*/ true);
1823       return;
1824 
1825     case Qualifiers::OCL_Weak:
1826       if (isInit)
1827         // Initialize and then skip the primitive store.
1828         EmitARCInitWeak(Dst.getAddress(), Src.getScalarVal());
1829       else
1830         EmitARCStoreWeak(Dst.getAddress(), Src.getScalarVal(), /*ignore*/ true);
1831       return;
1832 
1833     case Qualifiers::OCL_Autoreleasing:
1834       Src = RValue::get(EmitObjCExtendObjectLifetime(Dst.getType(),
1835                                                      Src.getScalarVal()));
1836       // fall into the normal path
1837       break;
1838     }
1839   }
1840 
1841   if (Dst.isObjCWeak() && !Dst.isNonGC()) {
1842     // load of a __weak object.
1843     Address LvalueDst = Dst.getAddress();
1844     llvm::Value *src = Src.getScalarVal();
1845      CGM.getObjCRuntime().EmitObjCWeakAssign(*this, src, LvalueDst);
1846     return;
1847   }
1848 
1849   if (Dst.isObjCStrong() && !Dst.isNonGC()) {
1850     // load of a __strong object.
1851     Address LvalueDst = Dst.getAddress();
1852     llvm::Value *src = Src.getScalarVal();
1853     if (Dst.isObjCIvar()) {
1854       assert(Dst.getBaseIvarExp() && "BaseIvarExp is NULL");
1855       llvm::Type *ResultType = IntPtrTy;
1856       Address dst = EmitPointerWithAlignment(Dst.getBaseIvarExp());
1857       llvm::Value *RHS = dst.getPointer();
1858       RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1859       llvm::Value *LHS =
1860         Builder.CreatePtrToInt(LvalueDst.getPointer(), ResultType,
1861                                "sub.ptr.lhs.cast");
1862       llvm::Value *BytesBetween = Builder.CreateSub(LHS, RHS, "ivar.offset");
1863       CGM.getObjCRuntime().EmitObjCIvarAssign(*this, src, dst,
1864                                               BytesBetween);
1865     } else if (Dst.isGlobalObjCRef()) {
1866       CGM.getObjCRuntime().EmitObjCGlobalAssign(*this, src, LvalueDst,
1867                                                 Dst.isThreadLocalRef());
1868     }
1869     else
1870       CGM.getObjCRuntime().EmitObjCStrongCastAssign(*this, src, LvalueDst);
1871     return;
1872   }
1873 
1874   assert(Src.isScalar() && "Can't emit an agg store with this method");
1875   EmitStoreOfScalar(Src.getScalarVal(), Dst, isInit);
1876 }
1877 
1878 void CodeGenFunction::EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst,
1879                                                      llvm::Value **Result) {
1880   const CGBitFieldInfo &Info = Dst.getBitFieldInfo();
1881   llvm::Type *ResLTy = ConvertTypeForMem(Dst.getType());
1882   Address Ptr = Dst.getBitFieldAddress();
1883 
1884   // Get the source value, truncated to the width of the bit-field.
1885   llvm::Value *SrcVal = Src.getScalarVal();
1886 
1887   // Cast the source to the storage type and shift it into place.
1888   SrcVal = Builder.CreateIntCast(SrcVal, Ptr.getElementType(),
1889                                  /*IsSigned=*/false);
1890   llvm::Value *MaskedVal = SrcVal;
1891 
1892   // See if there are other bits in the bitfield's storage we'll need to load
1893   // and mask together with source before storing.
1894   if (Info.StorageSize != Info.Size) {
1895     assert(Info.StorageSize > Info.Size && "Invalid bitfield size.");
1896     llvm::Value *Val =
1897       Builder.CreateLoad(Ptr, Dst.isVolatileQualified(), "bf.load");
1898 
1899     // Mask the source value as needed.
1900     if (!hasBooleanRepresentation(Dst.getType()))
1901       SrcVal = Builder.CreateAnd(SrcVal,
1902                                  llvm::APInt::getLowBitsSet(Info.StorageSize,
1903                                                             Info.Size),
1904                                  "bf.value");
1905     MaskedVal = SrcVal;
1906     if (Info.Offset)
1907       SrcVal = Builder.CreateShl(SrcVal, Info.Offset, "bf.shl");
1908 
1909     // Mask out the original value.
1910     Val = Builder.CreateAnd(Val,
1911                             ~llvm::APInt::getBitsSet(Info.StorageSize,
1912                                                      Info.Offset,
1913                                                      Info.Offset + Info.Size),
1914                             "bf.clear");
1915 
1916     // Or together the unchanged values and the source value.
1917     SrcVal = Builder.CreateOr(Val, SrcVal, "bf.set");
1918   } else {
1919     assert(Info.Offset == 0);
1920   }
1921 
1922   // Write the new value back out.
1923   Builder.CreateStore(SrcVal, Ptr, Dst.isVolatileQualified());
1924 
1925   // Return the new value of the bit-field, if requested.
1926   if (Result) {
1927     llvm::Value *ResultVal = MaskedVal;
1928 
1929     // Sign extend the value if needed.
1930     if (Info.IsSigned) {
1931       assert(Info.Size <= Info.StorageSize);
1932       unsigned HighBits = Info.StorageSize - Info.Size;
1933       if (HighBits) {
1934         ResultVal = Builder.CreateShl(ResultVal, HighBits, "bf.result.shl");
1935         ResultVal = Builder.CreateAShr(ResultVal, HighBits, "bf.result.ashr");
1936       }
1937     }
1938 
1939     ResultVal = Builder.CreateIntCast(ResultVal, ResLTy, Info.IsSigned,
1940                                       "bf.result.cast");
1941     *Result = EmitFromMemory(ResultVal, Dst.getType());
1942   }
1943 }
1944 
1945 void CodeGenFunction::EmitStoreThroughExtVectorComponentLValue(RValue Src,
1946                                                                LValue Dst) {
1947   // This access turns into a read/modify/write of the vector.  Load the input
1948   // value now.
1949   llvm::Value *Vec = Builder.CreateLoad(Dst.getExtVectorAddress(),
1950                                         Dst.isVolatileQualified());
1951   const llvm::Constant *Elts = Dst.getExtVectorElts();
1952 
1953   llvm::Value *SrcVal = Src.getScalarVal();
1954 
1955   if (const VectorType *VTy = Dst.getType()->getAs<VectorType>()) {
1956     unsigned NumSrcElts = VTy->getNumElements();
1957     unsigned NumDstElts = Vec->getType()->getVectorNumElements();
1958     if (NumDstElts == NumSrcElts) {
1959       // Use shuffle vector is the src and destination are the same number of
1960       // elements and restore the vector mask since it is on the side it will be
1961       // stored.
1962       SmallVector<llvm::Constant*, 4> Mask(NumDstElts);
1963       for (unsigned i = 0; i != NumSrcElts; ++i)
1964         Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i);
1965 
1966       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1967       Vec = Builder.CreateShuffleVector(SrcVal,
1968                                         llvm::UndefValue::get(Vec->getType()),
1969                                         MaskV);
1970     } else if (NumDstElts > NumSrcElts) {
1971       // Extended the source vector to the same length and then shuffle it
1972       // into the destination.
1973       // FIXME: since we're shuffling with undef, can we just use the indices
1974       //        into that?  This could be simpler.
1975       SmallVector<llvm::Constant*, 4> ExtMask;
1976       for (unsigned i = 0; i != NumSrcElts; ++i)
1977         ExtMask.push_back(Builder.getInt32(i));
1978       ExtMask.resize(NumDstElts, llvm::UndefValue::get(Int32Ty));
1979       llvm::Value *ExtMaskV = llvm::ConstantVector::get(ExtMask);
1980       llvm::Value *ExtSrcVal =
1981         Builder.CreateShuffleVector(SrcVal,
1982                                     llvm::UndefValue::get(SrcVal->getType()),
1983                                     ExtMaskV);
1984       // build identity
1985       SmallVector<llvm::Constant*, 4> Mask;
1986       for (unsigned i = 0; i != NumDstElts; ++i)
1987         Mask.push_back(Builder.getInt32(i));
1988 
1989       // When the vector size is odd and .odd or .hi is used, the last element
1990       // of the Elts constant array will be one past the size of the vector.
1991       // Ignore the last element here, if it is greater than the mask size.
1992       if (getAccessedFieldNo(NumSrcElts - 1, Elts) == Mask.size())
1993         NumSrcElts--;
1994 
1995       // modify when what gets shuffled in
1996       for (unsigned i = 0; i != NumSrcElts; ++i)
1997         Mask[getAccessedFieldNo(i, Elts)] = Builder.getInt32(i+NumDstElts);
1998       llvm::Value *MaskV = llvm::ConstantVector::get(Mask);
1999       Vec = Builder.CreateShuffleVector(Vec, ExtSrcVal, MaskV);
2000     } else {
2001       // We should never shorten the vector
2002       llvm_unreachable("unexpected shorten vector length");
2003     }
2004   } else {
2005     // If the Src is a scalar (not a vector) it must be updating one element.
2006     unsigned InIdx = getAccessedFieldNo(0, Elts);
2007     llvm::Value *Elt = llvm::ConstantInt::get(SizeTy, InIdx);
2008     Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt);
2009   }
2010 
2011   Builder.CreateStore(Vec, Dst.getExtVectorAddress(),
2012                       Dst.isVolatileQualified());
2013 }
2014 
2015 /// @brief Store of global named registers are always calls to intrinsics.
2016 void CodeGenFunction::EmitStoreThroughGlobalRegLValue(RValue Src, LValue Dst) {
2017   assert((Dst.getType()->isIntegerType() || Dst.getType()->isPointerType()) &&
2018          "Bad type for register variable");
2019   llvm::MDNode *RegName = cast<llvm::MDNode>(
2020       cast<llvm::MetadataAsValue>(Dst.getGlobalReg())->getMetadata());
2021   assert(RegName && "Register LValue is not metadata");
2022 
2023   // We accept integer and pointer types only
2024   llvm::Type *OrigTy = CGM.getTypes().ConvertType(Dst.getType());
2025   llvm::Type *Ty = OrigTy;
2026   if (OrigTy->isPointerTy())
2027     Ty = CGM.getTypes().getDataLayout().getIntPtrType(OrigTy);
2028   llvm::Type *Types[] = { Ty };
2029 
2030   llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::write_register, Types);
2031   llvm::Value *Value = Src.getScalarVal();
2032   if (OrigTy->isPointerTy())
2033     Value = Builder.CreatePtrToInt(Value, Ty);
2034   Builder.CreateCall(
2035       F, {llvm::MetadataAsValue::get(Ty->getContext(), RegName), Value});
2036 }
2037 
2038 // setObjCGCLValueClass - sets class of the lvalue for the purpose of
2039 // generating write-barries API. It is currently a global, ivar,
2040 // or neither.
2041 static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
2042                                  LValue &LV,
2043                                  bool IsMemberAccess=false) {
2044   if (Ctx.getLangOpts().getGC() == LangOptions::NonGC)
2045     return;
2046 
2047   if (isa<ObjCIvarRefExpr>(E)) {
2048     QualType ExpTy = E->getType();
2049     if (IsMemberAccess && ExpTy->isPointerType()) {
2050       // If ivar is a structure pointer, assigning to field of
2051       // this struct follows gcc's behavior and makes it a non-ivar
2052       // writer-barrier conservatively.
2053       ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2054       if (ExpTy->isRecordType()) {
2055         LV.setObjCIvar(false);
2056         return;
2057       }
2058     }
2059     LV.setObjCIvar(true);
2060     auto *Exp = cast<ObjCIvarRefExpr>(const_cast<Expr *>(E));
2061     LV.setBaseIvarExp(Exp->getBase());
2062     LV.setObjCArray(E->getType()->isArrayType());
2063     return;
2064   }
2065 
2066   if (const auto *Exp = dyn_cast<DeclRefExpr>(E)) {
2067     if (const auto *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
2068       if (VD->hasGlobalStorage()) {
2069         LV.setGlobalObjCRef(true);
2070         LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
2071       }
2072     }
2073     LV.setObjCArray(E->getType()->isArrayType());
2074     return;
2075   }
2076 
2077   if (const auto *Exp = dyn_cast<UnaryOperator>(E)) {
2078     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2079     return;
2080   }
2081 
2082   if (const auto *Exp = dyn_cast<ParenExpr>(E)) {
2083     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2084     if (LV.isObjCIvar()) {
2085       // If cast is to a structure pointer, follow gcc's behavior and make it
2086       // a non-ivar write-barrier.
2087       QualType ExpTy = E->getType();
2088       if (ExpTy->isPointerType())
2089         ExpTy = ExpTy->getAs<PointerType>()->getPointeeType();
2090       if (ExpTy->isRecordType())
2091         LV.setObjCIvar(false);
2092     }
2093     return;
2094   }
2095 
2096   if (const auto *Exp = dyn_cast<GenericSelectionExpr>(E)) {
2097     setObjCGCLValueClass(Ctx, Exp->getResultExpr(), LV);
2098     return;
2099   }
2100 
2101   if (const auto *Exp = dyn_cast<ImplicitCastExpr>(E)) {
2102     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2103     return;
2104   }
2105 
2106   if (const auto *Exp = dyn_cast<CStyleCastExpr>(E)) {
2107     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2108     return;
2109   }
2110 
2111   if (const auto *Exp = dyn_cast<ObjCBridgedCastExpr>(E)) {
2112     setObjCGCLValueClass(Ctx, Exp->getSubExpr(), LV, IsMemberAccess);
2113     return;
2114   }
2115 
2116   if (const auto *Exp = dyn_cast<ArraySubscriptExpr>(E)) {
2117     setObjCGCLValueClass(Ctx, Exp->getBase(), LV);
2118     if (LV.isObjCIvar() && !LV.isObjCArray())
2119       // Using array syntax to assigning to what an ivar points to is not
2120       // same as assigning to the ivar itself. {id *Names;} Names[i] = 0;
2121       LV.setObjCIvar(false);
2122     else if (LV.isGlobalObjCRef() && !LV.isObjCArray())
2123       // Using array syntax to assigning to what global points to is not
2124       // same as assigning to the global itself. {id *G;} G[i] = 0;
2125       LV.setGlobalObjCRef(false);
2126     return;
2127   }
2128 
2129   if (const auto *Exp = dyn_cast<MemberExpr>(E)) {
2130     setObjCGCLValueClass(Ctx, Exp->getBase(), LV, true);
2131     // We don't know if member is an 'ivar', but this flag is looked at
2132     // only in the context of LV.isObjCIvar().
2133     LV.setObjCArray(E->getType()->isArrayType());
2134     return;
2135   }
2136 }
2137 
2138 static llvm::Value *
2139 EmitBitCastOfLValueToProperType(CodeGenFunction &CGF,
2140                                 llvm::Value *V, llvm::Type *IRType,
2141                                 StringRef Name = StringRef()) {
2142   unsigned AS = cast<llvm::PointerType>(V->getType())->getAddressSpace();
2143   return CGF.Builder.CreateBitCast(V, IRType->getPointerTo(AS), Name);
2144 }
2145 
2146 static LValue EmitThreadPrivateVarDeclLValue(
2147     CodeGenFunction &CGF, const VarDecl *VD, QualType T, Address Addr,
2148     llvm::Type *RealVarTy, SourceLocation Loc) {
2149   Addr = CGF.CGM.getOpenMPRuntime().getAddrOfThreadPrivate(CGF, VD, Addr, Loc);
2150   Addr = CGF.Builder.CreateElementBitCast(Addr, RealVarTy);
2151   LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2152   return CGF.MakeAddrLValue(Addr, T, BaseInfo);
2153 }
2154 
2155 Address CodeGenFunction::EmitLoadOfReference(Address Addr,
2156                                              const ReferenceType *RefTy,
2157                                              LValueBaseInfo *BaseInfo) {
2158   llvm::Value *Ptr = Builder.CreateLoad(Addr);
2159   return Address(Ptr, getNaturalTypeAlignment(RefTy->getPointeeType(),
2160                                               BaseInfo, /*forPointee*/ true));
2161 }
2162 
2163 LValue CodeGenFunction::EmitLoadOfReferenceLValue(Address RefAddr,
2164                                                   const ReferenceType *RefTy) {
2165   LValueBaseInfo BaseInfo;
2166   Address Addr = EmitLoadOfReference(RefAddr, RefTy, &BaseInfo);
2167   return MakeAddrLValue(Addr, RefTy->getPointeeType(), BaseInfo);
2168 }
2169 
2170 Address CodeGenFunction::EmitLoadOfPointer(Address Ptr,
2171                                            const PointerType *PtrTy,
2172                                            LValueBaseInfo *BaseInfo) {
2173   llvm::Value *Addr = Builder.CreateLoad(Ptr);
2174   return Address(Addr, getNaturalTypeAlignment(PtrTy->getPointeeType(),
2175                                                BaseInfo,
2176                                                /*forPointeeType=*/true));
2177 }
2178 
2179 LValue CodeGenFunction::EmitLoadOfPointerLValue(Address PtrAddr,
2180                                                 const PointerType *PtrTy) {
2181   LValueBaseInfo BaseInfo;
2182   Address Addr = EmitLoadOfPointer(PtrAddr, PtrTy, &BaseInfo);
2183   return MakeAddrLValue(Addr, PtrTy->getPointeeType(), BaseInfo);
2184 }
2185 
2186 static LValue EmitGlobalVarDeclLValue(CodeGenFunction &CGF,
2187                                       const Expr *E, const VarDecl *VD) {
2188   QualType T = E->getType();
2189 
2190   // If it's thread_local, emit a call to its wrapper function instead.
2191   if (VD->getTLSKind() == VarDecl::TLS_Dynamic &&
2192       CGF.CGM.getCXXABI().usesThreadWrapperFunction())
2193     return CGF.CGM.getCXXABI().EmitThreadLocalVarDeclLValue(CGF, VD, T);
2194 
2195   llvm::Value *V = CGF.CGM.GetAddrOfGlobalVar(VD);
2196   llvm::Type *RealVarTy = CGF.getTypes().ConvertTypeForMem(VD->getType());
2197   V = EmitBitCastOfLValueToProperType(CGF, V, RealVarTy);
2198   CharUnits Alignment = CGF.getContext().getDeclAlign(VD);
2199   Address Addr(V, Alignment);
2200   LValue LV;
2201   // Emit reference to the private copy of the variable if it is an OpenMP
2202   // threadprivate variable.
2203   if (CGF.getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>())
2204     return EmitThreadPrivateVarDeclLValue(CGF, VD, T, Addr, RealVarTy,
2205                                           E->getExprLoc());
2206   if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2207     LV = CGF.EmitLoadOfReferenceLValue(Addr, RefTy);
2208   } else {
2209     LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2210     LV = CGF.MakeAddrLValue(Addr, T, BaseInfo);
2211   }
2212   setObjCGCLValueClass(CGF.getContext(), E, LV);
2213   return LV;
2214 }
2215 
2216 static llvm::Constant *EmitFunctionDeclPointer(CodeGenModule &CGM,
2217                                                const FunctionDecl *FD) {
2218   if (FD->hasAttr<WeakRefAttr>()) {
2219     ConstantAddress aliasee = CGM.GetWeakRefReference(FD);
2220     return aliasee.getPointer();
2221   }
2222 
2223   llvm::Constant *V = CGM.GetAddrOfFunction(FD);
2224   if (!FD->hasPrototype()) {
2225     if (const FunctionProtoType *Proto =
2226             FD->getType()->getAs<FunctionProtoType>()) {
2227       // Ugly case: for a K&R-style definition, the type of the definition
2228       // isn't the same as the type of a use.  Correct for this with a
2229       // bitcast.
2230       QualType NoProtoType =
2231           CGM.getContext().getFunctionNoProtoType(Proto->getReturnType());
2232       NoProtoType = CGM.getContext().getPointerType(NoProtoType);
2233       V = llvm::ConstantExpr::getBitCast(V,
2234                                       CGM.getTypes().ConvertType(NoProtoType));
2235     }
2236   }
2237   return V;
2238 }
2239 
2240 static LValue EmitFunctionDeclLValue(CodeGenFunction &CGF,
2241                                      const Expr *E, const FunctionDecl *FD) {
2242   llvm::Value *V = EmitFunctionDeclPointer(CGF.CGM, FD);
2243   CharUnits Alignment = CGF.getContext().getDeclAlign(FD);
2244   LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2245   return CGF.MakeAddrLValue(V, E->getType(), Alignment, BaseInfo);
2246 }
2247 
2248 static LValue EmitCapturedFieldLValue(CodeGenFunction &CGF, const FieldDecl *FD,
2249                                       llvm::Value *ThisValue) {
2250   QualType TagType = CGF.getContext().getTagDeclType(FD->getParent());
2251   LValue LV = CGF.MakeNaturalAlignAddrLValue(ThisValue, TagType);
2252   return CGF.EmitLValueForField(LV, FD);
2253 }
2254 
2255 /// Named Registers are named metadata pointing to the register name
2256 /// which will be read from/written to as an argument to the intrinsic
2257 /// @llvm.read/write_register.
2258 /// So far, only the name is being passed down, but other options such as
2259 /// register type, allocation type or even optimization options could be
2260 /// passed down via the metadata node.
2261 static LValue EmitGlobalNamedRegister(const VarDecl *VD, CodeGenModule &CGM) {
2262   SmallString<64> Name("llvm.named.register.");
2263   AsmLabelAttr *Asm = VD->getAttr<AsmLabelAttr>();
2264   assert(Asm->getLabel().size() < 64-Name.size() &&
2265       "Register name too big");
2266   Name.append(Asm->getLabel());
2267   llvm::NamedMDNode *M =
2268     CGM.getModule().getOrInsertNamedMetadata(Name);
2269   if (M->getNumOperands() == 0) {
2270     llvm::MDString *Str = llvm::MDString::get(CGM.getLLVMContext(),
2271                                               Asm->getLabel());
2272     llvm::Metadata *Ops[] = {Str};
2273     M->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
2274   }
2275 
2276   CharUnits Alignment = CGM.getContext().getDeclAlign(VD);
2277 
2278   llvm::Value *Ptr =
2279     llvm::MetadataAsValue::get(CGM.getLLVMContext(), M->getOperand(0));
2280   return LValue::MakeGlobalReg(Address(Ptr, Alignment), VD->getType());
2281 }
2282 
2283 LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
2284   const NamedDecl *ND = E->getDecl();
2285   QualType T = E->getType();
2286 
2287   if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2288     // Global Named registers access via intrinsics only
2289     if (VD->getStorageClass() == SC_Register &&
2290         VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
2291       return EmitGlobalNamedRegister(VD, CGM);
2292 
2293     // A DeclRefExpr for a reference initialized by a constant expression can
2294     // appear without being odr-used. Directly emit the constant initializer.
2295     const Expr *Init = VD->getAnyInitializer(VD);
2296     if (Init && !isa<ParmVarDecl>(VD) && VD->getType()->isReferenceType() &&
2297         VD->isUsableInConstantExpressions(getContext()) &&
2298         VD->checkInitIsICE() &&
2299         // Do not emit if it is private OpenMP variable.
2300         !(E->refersToEnclosingVariableOrCapture() &&
2301           ((CapturedStmtInfo &&
2302             (LocalDeclMap.count(VD->getCanonicalDecl()) ||
2303              CapturedStmtInfo->lookup(VD->getCanonicalDecl()))) ||
2304            LambdaCaptureFields.lookup(VD->getCanonicalDecl()) ||
2305            isa<BlockDecl>(CurCodeDecl)))) {
2306       llvm::Constant *Val =
2307         ConstantEmitter(*this).emitAbstract(E->getLocation(),
2308                                             *VD->evaluateValue(),
2309                                             VD->getType());
2310       assert(Val && "failed to emit reference constant expression");
2311       // FIXME: Eventually we will want to emit vector element references.
2312 
2313       // Should we be using the alignment of the constant pointer we emitted?
2314       CharUnits Alignment = getNaturalTypeAlignment(E->getType(), nullptr,
2315                                                     /*pointee*/ true);
2316       LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2317       return MakeAddrLValue(Address(Val, Alignment), T, BaseInfo);
2318     }
2319 
2320     // Check for captured variables.
2321     if (E->refersToEnclosingVariableOrCapture()) {
2322       VD = VD->getCanonicalDecl();
2323       if (auto *FD = LambdaCaptureFields.lookup(VD))
2324         return EmitCapturedFieldLValue(*this, FD, CXXABIThisValue);
2325       else if (CapturedStmtInfo) {
2326         auto I = LocalDeclMap.find(VD);
2327         if (I != LocalDeclMap.end()) {
2328           if (auto RefTy = VD->getType()->getAs<ReferenceType>())
2329             return EmitLoadOfReferenceLValue(I->second, RefTy);
2330           return MakeAddrLValue(I->second, T);
2331         }
2332         LValue CapLVal =
2333             EmitCapturedFieldLValue(*this, CapturedStmtInfo->lookup(VD),
2334                                     CapturedStmtInfo->getContextValue());
2335         bool MayAlias = CapLVal.getBaseInfo().getMayAlias();
2336         return MakeAddrLValue(
2337             Address(CapLVal.getPointer(), getContext().getDeclAlign(VD)),
2338             CapLVal.getType(), LValueBaseInfo(AlignmentSource::Decl, MayAlias));
2339       }
2340 
2341       assert(isa<BlockDecl>(CurCodeDecl));
2342       Address addr = GetAddrOfBlockDecl(VD, VD->hasAttr<BlocksAttr>());
2343       LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2344       return MakeAddrLValue(addr, T, BaseInfo);
2345     }
2346   }
2347 
2348   // FIXME: We should be able to assert this for FunctionDecls as well!
2349   // FIXME: We should be able to assert this for all DeclRefExprs, not just
2350   // those with a valid source location.
2351   assert((ND->isUsed(false) || !isa<VarDecl>(ND) ||
2352           !E->getLocation().isValid()) &&
2353          "Should not use decl without marking it used!");
2354 
2355   if (ND->hasAttr<WeakRefAttr>()) {
2356     const auto *VD = cast<ValueDecl>(ND);
2357     ConstantAddress Aliasee = CGM.GetWeakRefReference(VD);
2358     return MakeAddrLValue(Aliasee, T,
2359                           LValueBaseInfo(AlignmentSource::Decl, false));
2360   }
2361 
2362   if (const auto *VD = dyn_cast<VarDecl>(ND)) {
2363     // Check if this is a global variable.
2364     if (VD->hasLinkage() || VD->isStaticDataMember())
2365       return EmitGlobalVarDeclLValue(*this, E, VD);
2366 
2367     Address addr = Address::invalid();
2368 
2369     // The variable should generally be present in the local decl map.
2370     auto iter = LocalDeclMap.find(VD);
2371     if (iter != LocalDeclMap.end()) {
2372       addr = iter->second;
2373 
2374     // Otherwise, it might be static local we haven't emitted yet for
2375     // some reason; most likely, because it's in an outer function.
2376     } else if (VD->isStaticLocal()) {
2377       addr = Address(CGM.getOrCreateStaticVarDecl(
2378           *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false)),
2379                      getContext().getDeclAlign(VD));
2380 
2381     // No other cases for now.
2382     } else {
2383       llvm_unreachable("DeclRefExpr for Decl not entered in LocalDeclMap?");
2384     }
2385 
2386 
2387     // Check for OpenMP threadprivate variables.
2388     if (getLangOpts().OpenMP && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
2389       return EmitThreadPrivateVarDeclLValue(
2390           *this, VD, T, addr, getTypes().ConvertTypeForMem(VD->getType()),
2391           E->getExprLoc());
2392     }
2393 
2394     // Drill into block byref variables.
2395     bool isBlockByref = VD->hasAttr<BlocksAttr>();
2396     if (isBlockByref) {
2397       addr = emitBlockByrefAddress(addr, VD);
2398     }
2399 
2400     // Drill into reference types.
2401     LValue LV;
2402     if (auto RefTy = VD->getType()->getAs<ReferenceType>()) {
2403       LV = EmitLoadOfReferenceLValue(addr, RefTy);
2404     } else {
2405       LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2406       LV = MakeAddrLValue(addr, T, BaseInfo);
2407     }
2408 
2409     bool isLocalStorage = VD->hasLocalStorage();
2410 
2411     bool NonGCable = isLocalStorage &&
2412                      !VD->getType()->isReferenceType() &&
2413                      !isBlockByref;
2414     if (NonGCable) {
2415       LV.getQuals().removeObjCGCAttr();
2416       LV.setNonGC(true);
2417     }
2418 
2419     bool isImpreciseLifetime =
2420       (isLocalStorage && !VD->hasAttr<ObjCPreciseLifetimeAttr>());
2421     if (isImpreciseLifetime)
2422       LV.setARCPreciseLifetime(ARCImpreciseLifetime);
2423     setObjCGCLValueClass(getContext(), E, LV);
2424     return LV;
2425   }
2426 
2427   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2428     return EmitFunctionDeclLValue(*this, E, FD);
2429 
2430   // FIXME: While we're emitting a binding from an enclosing scope, all other
2431   // DeclRefExprs we see should be implicitly treated as if they also refer to
2432   // an enclosing scope.
2433   if (const auto *BD = dyn_cast<BindingDecl>(ND))
2434     return EmitLValue(BD->getBinding());
2435 
2436   llvm_unreachable("Unhandled DeclRefExpr");
2437 }
2438 
2439 LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
2440   // __extension__ doesn't affect lvalue-ness.
2441   if (E->getOpcode() == UO_Extension)
2442     return EmitLValue(E->getSubExpr());
2443 
2444   QualType ExprTy = getContext().getCanonicalType(E->getSubExpr()->getType());
2445   switch (E->getOpcode()) {
2446   default: llvm_unreachable("Unknown unary operator lvalue!");
2447   case UO_Deref: {
2448     QualType T = E->getSubExpr()->getType()->getPointeeType();
2449     assert(!T.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
2450 
2451     LValueBaseInfo BaseInfo;
2452     Address Addr = EmitPointerWithAlignment(E->getSubExpr(), &BaseInfo);
2453     LValue LV = MakeAddrLValue(Addr, T, BaseInfo);
2454     LV.getQuals().setAddressSpace(ExprTy.getAddressSpace());
2455 
2456     // We should not generate __weak write barrier on indirect reference
2457     // of a pointer to object; as in void foo (__weak id *param); *param = 0;
2458     // But, we continue to generate __strong write barrier on indirect write
2459     // into a pointer to object.
2460     if (getLangOpts().ObjC1 &&
2461         getLangOpts().getGC() != LangOptions::NonGC &&
2462         LV.isObjCWeak())
2463       LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
2464     return LV;
2465   }
2466   case UO_Real:
2467   case UO_Imag: {
2468     LValue LV = EmitLValue(E->getSubExpr());
2469     assert(LV.isSimple() && "real/imag on non-ordinary l-value");
2470 
2471     // __real is valid on scalars.  This is a faster way of testing that.
2472     // __imag can only produce an rvalue on scalars.
2473     if (E->getOpcode() == UO_Real &&
2474         !LV.getAddress().getElementType()->isStructTy()) {
2475       assert(E->getSubExpr()->getType()->isArithmeticType());
2476       return LV;
2477     }
2478 
2479     QualType T = ExprTy->castAs<ComplexType>()->getElementType();
2480 
2481     Address Component =
2482       (E->getOpcode() == UO_Real
2483          ? emitAddrOfRealComponent(LV.getAddress(), LV.getType())
2484          : emitAddrOfImagComponent(LV.getAddress(), LV.getType()));
2485     LValue ElemLV = MakeAddrLValue(Component, T, LV.getBaseInfo());
2486     ElemLV.getQuals().addQualifiers(LV.getQuals());
2487     return ElemLV;
2488   }
2489   case UO_PreInc:
2490   case UO_PreDec: {
2491     LValue LV = EmitLValue(E->getSubExpr());
2492     bool isInc = E->getOpcode() == UO_PreInc;
2493 
2494     if (E->getType()->isAnyComplexType())
2495       EmitComplexPrePostIncDec(E, LV, isInc, true/*isPre*/);
2496     else
2497       EmitScalarPrePostIncDec(E, LV, isInc, true/*isPre*/);
2498     return LV;
2499   }
2500   }
2501 }
2502 
2503 LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
2504   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromLiteral(E),
2505                         E->getType(),
2506                         LValueBaseInfo(AlignmentSource::Decl, false));
2507 }
2508 
2509 LValue CodeGenFunction::EmitObjCEncodeExprLValue(const ObjCEncodeExpr *E) {
2510   return MakeAddrLValue(CGM.GetAddrOfConstantStringFromObjCEncode(E),
2511                         E->getType(),
2512                         LValueBaseInfo(AlignmentSource::Decl, false));
2513 }
2514 
2515 LValue CodeGenFunction::EmitPredefinedLValue(const PredefinedExpr *E) {
2516   auto SL = E->getFunctionName();
2517   assert(SL != nullptr && "No StringLiteral name in PredefinedExpr");
2518   StringRef FnName = CurFn->getName();
2519   if (FnName.startswith("\01"))
2520     FnName = FnName.substr(1);
2521   StringRef NameItems[] = {
2522       PredefinedExpr::getIdentTypeName(E->getIdentType()), FnName};
2523   std::string GVName = llvm::join(NameItems, NameItems + 2, ".");
2524   LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
2525   if (auto *BD = dyn_cast<BlockDecl>(CurCodeDecl)) {
2526     std::string Name = SL->getString();
2527     if (!Name.empty()) {
2528       unsigned Discriminator =
2529           CGM.getCXXABI().getMangleContext().getBlockId(BD, true);
2530       if (Discriminator)
2531         Name += "_" + Twine(Discriminator + 1).str();
2532       auto C = CGM.GetAddrOfConstantCString(Name, GVName.c_str());
2533       return MakeAddrLValue(C, E->getType(), BaseInfo);
2534     } else {
2535       auto C = CGM.GetAddrOfConstantCString(FnName, GVName.c_str());
2536       return MakeAddrLValue(C, E->getType(), BaseInfo);
2537     }
2538   }
2539   auto C = CGM.GetAddrOfConstantStringFromLiteral(SL, GVName);
2540   return MakeAddrLValue(C, E->getType(), BaseInfo);
2541 }
2542 
2543 /// Emit a type description suitable for use by a runtime sanitizer library. The
2544 /// format of a type descriptor is
2545 ///
2546 /// \code
2547 ///   { i16 TypeKind, i16 TypeInfo }
2548 /// \endcode
2549 ///
2550 /// followed by an array of i8 containing the type name. TypeKind is 0 for an
2551 /// integer, 1 for a floating point value, and -1 for anything else.
2552 llvm::Constant *CodeGenFunction::EmitCheckTypeDescriptor(QualType T) {
2553   // Only emit each type's descriptor once.
2554   if (llvm::Constant *C = CGM.getTypeDescriptorFromMap(T))
2555     return C;
2556 
2557   uint16_t TypeKind = -1;
2558   uint16_t TypeInfo = 0;
2559 
2560   if (T->isIntegerType()) {
2561     TypeKind = 0;
2562     TypeInfo = (llvm::Log2_32(getContext().getTypeSize(T)) << 1) |
2563                (T->isSignedIntegerType() ? 1 : 0);
2564   } else if (T->isFloatingType()) {
2565     TypeKind = 1;
2566     TypeInfo = getContext().getTypeSize(T);
2567   }
2568 
2569   // Format the type name as if for a diagnostic, including quotes and
2570   // optionally an 'aka'.
2571   SmallString<32> Buffer;
2572   CGM.getDiags().ConvertArgToString(DiagnosticsEngine::ak_qualtype,
2573                                     (intptr_t)T.getAsOpaquePtr(),
2574                                     StringRef(), StringRef(), None, Buffer,
2575                                     None);
2576 
2577   llvm::Constant *Components[] = {
2578     Builder.getInt16(TypeKind), Builder.getInt16(TypeInfo),
2579     llvm::ConstantDataArray::getString(getLLVMContext(), Buffer)
2580   };
2581   llvm::Constant *Descriptor = llvm::ConstantStruct::getAnon(Components);
2582 
2583   auto *GV = new llvm::GlobalVariable(
2584       CGM.getModule(), Descriptor->getType(),
2585       /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, Descriptor);
2586   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2587   CGM.getSanitizerMetadata()->disableSanitizerForGlobal(GV);
2588 
2589   // Remember the descriptor for this type.
2590   CGM.setTypeDescriptorInMap(T, GV);
2591 
2592   return GV;
2593 }
2594 
2595 llvm::Value *CodeGenFunction::EmitCheckValue(llvm::Value *V) {
2596   llvm::Type *TargetTy = IntPtrTy;
2597 
2598   if (V->getType() == TargetTy)
2599     return V;
2600 
2601   // Floating-point types which fit into intptr_t are bitcast to integers
2602   // and then passed directly (after zero-extension, if necessary).
2603   if (V->getType()->isFloatingPointTy()) {
2604     unsigned Bits = V->getType()->getPrimitiveSizeInBits();
2605     if (Bits <= TargetTy->getIntegerBitWidth())
2606       V = Builder.CreateBitCast(V, llvm::Type::getIntNTy(getLLVMContext(),
2607                                                          Bits));
2608   }
2609 
2610   // Integers which fit in intptr_t are zero-extended and passed directly.
2611   if (V->getType()->isIntegerTy() &&
2612       V->getType()->getIntegerBitWidth() <= TargetTy->getIntegerBitWidth())
2613     return Builder.CreateZExt(V, TargetTy);
2614 
2615   // Pointers are passed directly, everything else is passed by address.
2616   if (!V->getType()->isPointerTy()) {
2617     Address Ptr = CreateDefaultAlignTempAlloca(V->getType());
2618     Builder.CreateStore(V, Ptr);
2619     V = Ptr.getPointer();
2620   }
2621   return Builder.CreatePtrToInt(V, TargetTy);
2622 }
2623 
2624 /// \brief Emit a representation of a SourceLocation for passing to a handler
2625 /// in a sanitizer runtime library. The format for this data is:
2626 /// \code
2627 ///   struct SourceLocation {
2628 ///     const char *Filename;
2629 ///     int32_t Line, Column;
2630 ///   };
2631 /// \endcode
2632 /// For an invalid SourceLocation, the Filename pointer is null.
2633 llvm::Constant *CodeGenFunction::EmitCheckSourceLocation(SourceLocation Loc) {
2634   llvm::Constant *Filename;
2635   int Line, Column;
2636 
2637   PresumedLoc PLoc = getContext().getSourceManager().getPresumedLoc(Loc);
2638   if (PLoc.isValid()) {
2639     StringRef FilenameString = PLoc.getFilename();
2640 
2641     int PathComponentsToStrip =
2642         CGM.getCodeGenOpts().EmitCheckPathComponentsToStrip;
2643     if (PathComponentsToStrip < 0) {
2644       assert(PathComponentsToStrip != INT_MIN);
2645       int PathComponentsToKeep = -PathComponentsToStrip;
2646       auto I = llvm::sys::path::rbegin(FilenameString);
2647       auto E = llvm::sys::path::rend(FilenameString);
2648       while (I != E && --PathComponentsToKeep)
2649         ++I;
2650 
2651       FilenameString = FilenameString.substr(I - E);
2652     } else if (PathComponentsToStrip > 0) {
2653       auto I = llvm::sys::path::begin(FilenameString);
2654       auto E = llvm::sys::path::end(FilenameString);
2655       while (I != E && PathComponentsToStrip--)
2656         ++I;
2657 
2658       if (I != E)
2659         FilenameString =
2660             FilenameString.substr(I - llvm::sys::path::begin(FilenameString));
2661       else
2662         FilenameString = llvm::sys::path::filename(FilenameString);
2663     }
2664 
2665     auto FilenameGV = CGM.GetAddrOfConstantCString(FilenameString, ".src");
2666     CGM.getSanitizerMetadata()->disableSanitizerForGlobal(
2667                           cast<llvm::GlobalVariable>(FilenameGV.getPointer()));
2668     Filename = FilenameGV.getPointer();
2669     Line = PLoc.getLine();
2670     Column = PLoc.getColumn();
2671   } else {
2672     Filename = llvm::Constant::getNullValue(Int8PtrTy);
2673     Line = Column = 0;
2674   }
2675 
2676   llvm::Constant *Data[] = {Filename, Builder.getInt32(Line),
2677                             Builder.getInt32(Column)};
2678 
2679   return llvm::ConstantStruct::getAnon(Data);
2680 }
2681 
2682 namespace {
2683 /// \brief Specify under what conditions this check can be recovered
2684 enum class CheckRecoverableKind {
2685   /// Always terminate program execution if this check fails.
2686   Unrecoverable,
2687   /// Check supports recovering, runtime has both fatal (noreturn) and
2688   /// non-fatal handlers for this check.
2689   Recoverable,
2690   /// Runtime conditionally aborts, always need to support recovery.
2691   AlwaysRecoverable
2692 };
2693 }
2694 
2695 static CheckRecoverableKind getRecoverableKind(SanitizerMask Kind) {
2696   assert(llvm::countPopulation(Kind) == 1);
2697   switch (Kind) {
2698   case SanitizerKind::Vptr:
2699     return CheckRecoverableKind::AlwaysRecoverable;
2700   case SanitizerKind::Return:
2701   case SanitizerKind::Unreachable:
2702     return CheckRecoverableKind::Unrecoverable;
2703   default:
2704     return CheckRecoverableKind::Recoverable;
2705   }
2706 }
2707 
2708 namespace {
2709 struct SanitizerHandlerInfo {
2710   char const *const Name;
2711   unsigned Version;
2712 };
2713 }
2714 
2715 const SanitizerHandlerInfo SanitizerHandlers[] = {
2716 #define SANITIZER_CHECK(Enum, Name, Version) {#Name, Version},
2717     LIST_SANITIZER_CHECKS
2718 #undef SANITIZER_CHECK
2719 };
2720 
2721 static void emitCheckHandlerCall(CodeGenFunction &CGF,
2722                                  llvm::FunctionType *FnType,
2723                                  ArrayRef<llvm::Value *> FnArgs,
2724                                  SanitizerHandler CheckHandler,
2725                                  CheckRecoverableKind RecoverKind, bool IsFatal,
2726                                  llvm::BasicBlock *ContBB) {
2727   assert(IsFatal || RecoverKind != CheckRecoverableKind::Unrecoverable);
2728   bool NeedsAbortSuffix =
2729       IsFatal && RecoverKind != CheckRecoverableKind::Unrecoverable;
2730   bool MinimalRuntime = CGF.CGM.getCodeGenOpts().SanitizeMinimalRuntime;
2731   const SanitizerHandlerInfo &CheckInfo = SanitizerHandlers[CheckHandler];
2732   const StringRef CheckName = CheckInfo.Name;
2733   std::string FnName = "__ubsan_handle_" + CheckName.str();
2734   if (CheckInfo.Version && !MinimalRuntime)
2735     FnName += "_v" + llvm::utostr(CheckInfo.Version);
2736   if (MinimalRuntime)
2737     FnName += "_minimal";
2738   if (NeedsAbortSuffix)
2739     FnName += "_abort";
2740   bool MayReturn =
2741       !IsFatal || RecoverKind == CheckRecoverableKind::AlwaysRecoverable;
2742 
2743   llvm::AttrBuilder B;
2744   if (!MayReturn) {
2745     B.addAttribute(llvm::Attribute::NoReturn)
2746         .addAttribute(llvm::Attribute::NoUnwind);
2747   }
2748   B.addAttribute(llvm::Attribute::UWTable);
2749 
2750   llvm::Value *Fn = CGF.CGM.CreateRuntimeFunction(
2751       FnType, FnName,
2752       llvm::AttributeList::get(CGF.getLLVMContext(),
2753                                llvm::AttributeList::FunctionIndex, B),
2754       /*Local=*/true);
2755   llvm::CallInst *HandlerCall = CGF.EmitNounwindRuntimeCall(Fn, FnArgs);
2756   if (!MayReturn) {
2757     HandlerCall->setDoesNotReturn();
2758     CGF.Builder.CreateUnreachable();
2759   } else {
2760     CGF.Builder.CreateBr(ContBB);
2761   }
2762 }
2763 
2764 void CodeGenFunction::EmitCheck(
2765     ArrayRef<std::pair<llvm::Value *, SanitizerMask>> Checked,
2766     SanitizerHandler CheckHandler, ArrayRef<llvm::Constant *> StaticArgs,
2767     ArrayRef<llvm::Value *> DynamicArgs) {
2768   assert(IsSanitizerScope);
2769   assert(Checked.size() > 0);
2770   assert(CheckHandler >= 0 &&
2771          CheckHandler < sizeof(SanitizerHandlers) / sizeof(*SanitizerHandlers));
2772   const StringRef CheckName = SanitizerHandlers[CheckHandler].Name;
2773 
2774   llvm::Value *FatalCond = nullptr;
2775   llvm::Value *RecoverableCond = nullptr;
2776   llvm::Value *TrapCond = nullptr;
2777   for (int i = 0, n = Checked.size(); i < n; ++i) {
2778     llvm::Value *Check = Checked[i].first;
2779     // -fsanitize-trap= overrides -fsanitize-recover=.
2780     llvm::Value *&Cond =
2781         CGM.getCodeGenOpts().SanitizeTrap.has(Checked[i].second)
2782             ? TrapCond
2783             : CGM.getCodeGenOpts().SanitizeRecover.has(Checked[i].second)
2784                   ? RecoverableCond
2785                   : FatalCond;
2786     Cond = Cond ? Builder.CreateAnd(Cond, Check) : Check;
2787   }
2788 
2789   if (TrapCond)
2790     EmitTrapCheck(TrapCond);
2791   if (!FatalCond && !RecoverableCond)
2792     return;
2793 
2794   llvm::Value *JointCond;
2795   if (FatalCond && RecoverableCond)
2796     JointCond = Builder.CreateAnd(FatalCond, RecoverableCond);
2797   else
2798     JointCond = FatalCond ? FatalCond : RecoverableCond;
2799   assert(JointCond);
2800 
2801   CheckRecoverableKind RecoverKind = getRecoverableKind(Checked[0].second);
2802   assert(SanOpts.has(Checked[0].second));
2803 #ifndef NDEBUG
2804   for (int i = 1, n = Checked.size(); i < n; ++i) {
2805     assert(RecoverKind == getRecoverableKind(Checked[i].second) &&
2806            "All recoverable kinds in a single check must be same!");
2807     assert(SanOpts.has(Checked[i].second));
2808   }
2809 #endif
2810 
2811   llvm::BasicBlock *Cont = createBasicBlock("cont");
2812   llvm::BasicBlock *Handlers = createBasicBlock("handler." + CheckName);
2813   llvm::Instruction *Branch = Builder.CreateCondBr(JointCond, Cont, Handlers);
2814   // Give hint that we very much don't expect to execute the handler
2815   // Value chosen to match UR_NONTAKEN_WEIGHT, see BranchProbabilityInfo.cpp
2816   llvm::MDBuilder MDHelper(getLLVMContext());
2817   llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2818   Branch->setMetadata(llvm::LLVMContext::MD_prof, Node);
2819   EmitBlock(Handlers);
2820 
2821   // Handler functions take an i8* pointing to the (handler-specific) static
2822   // information block, followed by a sequence of intptr_t arguments
2823   // representing operand values.
2824   SmallVector<llvm::Value *, 4> Args;
2825   SmallVector<llvm::Type *, 4> ArgTypes;
2826   if (!CGM.getCodeGenOpts().SanitizeMinimalRuntime) {
2827     Args.reserve(DynamicArgs.size() + 1);
2828     ArgTypes.reserve(DynamicArgs.size() + 1);
2829 
2830     // Emit handler arguments and create handler function type.
2831     if (!StaticArgs.empty()) {
2832       llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2833       auto *InfoPtr =
2834           new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2835                                    llvm::GlobalVariable::PrivateLinkage, Info);
2836       InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2837       CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2838       Args.push_back(Builder.CreateBitCast(InfoPtr, Int8PtrTy));
2839       ArgTypes.push_back(Int8PtrTy);
2840     }
2841 
2842     for (size_t i = 0, n = DynamicArgs.size(); i != n; ++i) {
2843       Args.push_back(EmitCheckValue(DynamicArgs[i]));
2844       ArgTypes.push_back(IntPtrTy);
2845     }
2846   }
2847 
2848   llvm::FunctionType *FnType =
2849     llvm::FunctionType::get(CGM.VoidTy, ArgTypes, false);
2850 
2851   if (!FatalCond || !RecoverableCond) {
2852     // Simple case: we need to generate a single handler call, either
2853     // fatal, or non-fatal.
2854     emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind,
2855                          (FatalCond != nullptr), Cont);
2856   } else {
2857     // Emit two handler calls: first one for set of unrecoverable checks,
2858     // another one for recoverable.
2859     llvm::BasicBlock *NonFatalHandlerBB =
2860         createBasicBlock("non_fatal." + CheckName);
2861     llvm::BasicBlock *FatalHandlerBB = createBasicBlock("fatal." + CheckName);
2862     Builder.CreateCondBr(FatalCond, NonFatalHandlerBB, FatalHandlerBB);
2863     EmitBlock(FatalHandlerBB);
2864     emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, true,
2865                          NonFatalHandlerBB);
2866     EmitBlock(NonFatalHandlerBB);
2867     emitCheckHandlerCall(*this, FnType, Args, CheckHandler, RecoverKind, false,
2868                          Cont);
2869   }
2870 
2871   EmitBlock(Cont);
2872 }
2873 
2874 void CodeGenFunction::EmitCfiSlowPathCheck(
2875     SanitizerMask Kind, llvm::Value *Cond, llvm::ConstantInt *TypeId,
2876     llvm::Value *Ptr, ArrayRef<llvm::Constant *> StaticArgs) {
2877   llvm::BasicBlock *Cont = createBasicBlock("cfi.cont");
2878 
2879   llvm::BasicBlock *CheckBB = createBasicBlock("cfi.slowpath");
2880   llvm::BranchInst *BI = Builder.CreateCondBr(Cond, Cont, CheckBB);
2881 
2882   llvm::MDBuilder MDHelper(getLLVMContext());
2883   llvm::MDNode *Node = MDHelper.createBranchWeights((1U << 20) - 1, 1);
2884   BI->setMetadata(llvm::LLVMContext::MD_prof, Node);
2885 
2886   EmitBlock(CheckBB);
2887 
2888   bool WithDiag = !CGM.getCodeGenOpts().SanitizeTrap.has(Kind);
2889 
2890   llvm::CallInst *CheckCall;
2891   if (WithDiag) {
2892     llvm::Constant *Info = llvm::ConstantStruct::getAnon(StaticArgs);
2893     auto *InfoPtr =
2894         new llvm::GlobalVariable(CGM.getModule(), Info->getType(), false,
2895                                  llvm::GlobalVariable::PrivateLinkage, Info);
2896     InfoPtr->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2897     CGM.getSanitizerMetadata()->disableSanitizerForGlobal(InfoPtr);
2898 
2899     llvm::Constant *SlowPathDiagFn = CGM.getModule().getOrInsertFunction(
2900         "__cfi_slowpath_diag",
2901         llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy},
2902                                 false));
2903     CheckCall = Builder.CreateCall(
2904         SlowPathDiagFn,
2905         {TypeId, Ptr, Builder.CreateBitCast(InfoPtr, Int8PtrTy)});
2906   } else {
2907     llvm::Constant *SlowPathFn = CGM.getModule().getOrInsertFunction(
2908         "__cfi_slowpath",
2909         llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy}, false));
2910     CheckCall = Builder.CreateCall(SlowPathFn, {TypeId, Ptr});
2911   }
2912 
2913   CheckCall->setDoesNotThrow();
2914 
2915   EmitBlock(Cont);
2916 }
2917 
2918 // Emit a stub for __cfi_check function so that the linker knows about this
2919 // symbol in LTO mode.
2920 void CodeGenFunction::EmitCfiCheckStub() {
2921   llvm::Module *M = &CGM.getModule();
2922   auto &Ctx = M->getContext();
2923   llvm::Function *F = llvm::Function::Create(
2924       llvm::FunctionType::get(VoidTy, {Int64Ty, Int8PtrTy, Int8PtrTy}, false),
2925       llvm::GlobalValue::WeakAnyLinkage, "__cfi_check", M);
2926   llvm::BasicBlock *BB = llvm::BasicBlock::Create(Ctx, "entry", F);
2927   // FIXME: consider emitting an intrinsic call like
2928   // call void @llvm.cfi_check(i64 %0, i8* %1, i8* %2)
2929   // which can be lowered in CrossDSOCFI pass to the actual contents of
2930   // __cfi_check. This would allow inlining of __cfi_check calls.
2931   llvm::CallInst::Create(
2932       llvm::Intrinsic::getDeclaration(M, llvm::Intrinsic::trap), "", BB);
2933   llvm::ReturnInst::Create(Ctx, nullptr, BB);
2934 }
2935 
2936 // This function is basically a switch over the CFI failure kind, which is
2937 // extracted from CFICheckFailData (1st function argument). Each case is either
2938 // llvm.trap or a call to one of the two runtime handlers, based on
2939 // -fsanitize-trap and -fsanitize-recover settings.  Default case (invalid
2940 // failure kind) traps, but this should really never happen.  CFICheckFailData
2941 // can be nullptr if the calling module has -fsanitize-trap behavior for this
2942 // check kind; in this case __cfi_check_fail traps as well.
2943 void CodeGenFunction::EmitCfiCheckFail() {
2944   SanitizerScope SanScope(this);
2945   FunctionArgList Args;
2946   ImplicitParamDecl ArgData(getContext(), getContext().VoidPtrTy,
2947                             ImplicitParamDecl::Other);
2948   ImplicitParamDecl ArgAddr(getContext(), getContext().VoidPtrTy,
2949                             ImplicitParamDecl::Other);
2950   Args.push_back(&ArgData);
2951   Args.push_back(&ArgAddr);
2952 
2953   const CGFunctionInfo &FI =
2954     CGM.getTypes().arrangeBuiltinFunctionDeclaration(getContext().VoidTy, Args);
2955 
2956   llvm::Function *F = llvm::Function::Create(
2957       llvm::FunctionType::get(VoidTy, {VoidPtrTy, VoidPtrTy}, false),
2958       llvm::GlobalValue::WeakODRLinkage, "__cfi_check_fail", &CGM.getModule());
2959   F->setVisibility(llvm::GlobalValue::HiddenVisibility);
2960 
2961   StartFunction(GlobalDecl(), CGM.getContext().VoidTy, F, FI, Args,
2962                 SourceLocation());
2963 
2964   llvm::Value *Data =
2965       EmitLoadOfScalar(GetAddrOfLocalVar(&ArgData), /*Volatile=*/false,
2966                        CGM.getContext().VoidPtrTy, ArgData.getLocation());
2967   llvm::Value *Addr =
2968       EmitLoadOfScalar(GetAddrOfLocalVar(&ArgAddr), /*Volatile=*/false,
2969                        CGM.getContext().VoidPtrTy, ArgAddr.getLocation());
2970 
2971   // Data == nullptr means the calling module has trap behaviour for this check.
2972   llvm::Value *DataIsNotNullPtr =
2973       Builder.CreateICmpNE(Data, llvm::ConstantPointerNull::get(Int8PtrTy));
2974   EmitTrapCheck(DataIsNotNullPtr);
2975 
2976   llvm::StructType *SourceLocationTy =
2977       llvm::StructType::get(VoidPtrTy, Int32Ty, Int32Ty);
2978   llvm::StructType *CfiCheckFailDataTy =
2979       llvm::StructType::get(Int8Ty, SourceLocationTy, VoidPtrTy);
2980 
2981   llvm::Value *V = Builder.CreateConstGEP2_32(
2982       CfiCheckFailDataTy,
2983       Builder.CreatePointerCast(Data, CfiCheckFailDataTy->getPointerTo(0)), 0,
2984       0);
2985   Address CheckKindAddr(V, getIntAlign());
2986   llvm::Value *CheckKind = Builder.CreateLoad(CheckKindAddr);
2987 
2988   llvm::Value *AllVtables = llvm::MetadataAsValue::get(
2989       CGM.getLLVMContext(),
2990       llvm::MDString::get(CGM.getLLVMContext(), "all-vtables"));
2991   llvm::Value *ValidVtable = Builder.CreateZExt(
2992       Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test),
2993                          {Addr, AllVtables}),
2994       IntPtrTy);
2995 
2996   const std::pair<int, SanitizerMask> CheckKinds[] = {
2997       {CFITCK_VCall, SanitizerKind::CFIVCall},
2998       {CFITCK_NVCall, SanitizerKind::CFINVCall},
2999       {CFITCK_DerivedCast, SanitizerKind::CFIDerivedCast},
3000       {CFITCK_UnrelatedCast, SanitizerKind::CFIUnrelatedCast},
3001       {CFITCK_ICall, SanitizerKind::CFIICall}};
3002 
3003   SmallVector<std::pair<llvm::Value *, SanitizerMask>, 5> Checks;
3004   for (auto CheckKindMaskPair : CheckKinds) {
3005     int Kind = CheckKindMaskPair.first;
3006     SanitizerMask Mask = CheckKindMaskPair.second;
3007     llvm::Value *Cond =
3008         Builder.CreateICmpNE(CheckKind, llvm::ConstantInt::get(Int8Ty, Kind));
3009     if (CGM.getLangOpts().Sanitize.has(Mask))
3010       EmitCheck(std::make_pair(Cond, Mask), SanitizerHandler::CFICheckFail, {},
3011                 {Data, Addr, ValidVtable});
3012     else
3013       EmitTrapCheck(Cond);
3014   }
3015 
3016   FinishFunction();
3017   // The only reference to this function will be created during LTO link.
3018   // Make sure it survives until then.
3019   CGM.addUsedGlobal(F);
3020 }
3021 
3022 void CodeGenFunction::EmitTrapCheck(llvm::Value *Checked) {
3023   llvm::BasicBlock *Cont = createBasicBlock("cont");
3024 
3025   // If we're optimizing, collapse all calls to trap down to just one per
3026   // function to save on code size.
3027   if (!CGM.getCodeGenOpts().OptimizationLevel || !TrapBB) {
3028     TrapBB = createBasicBlock("trap");
3029     Builder.CreateCondBr(Checked, Cont, TrapBB);
3030     EmitBlock(TrapBB);
3031     llvm::CallInst *TrapCall = EmitTrapCall(llvm::Intrinsic::trap);
3032     TrapCall->setDoesNotReturn();
3033     TrapCall->setDoesNotThrow();
3034     Builder.CreateUnreachable();
3035   } else {
3036     Builder.CreateCondBr(Checked, Cont, TrapBB);
3037   }
3038 
3039   EmitBlock(Cont);
3040 }
3041 
3042 llvm::CallInst *CodeGenFunction::EmitTrapCall(llvm::Intrinsic::ID IntrID) {
3043   llvm::CallInst *TrapCall = Builder.CreateCall(CGM.getIntrinsic(IntrID));
3044 
3045   if (!CGM.getCodeGenOpts().TrapFuncName.empty()) {
3046     auto A = llvm::Attribute::get(getLLVMContext(), "trap-func-name",
3047                                   CGM.getCodeGenOpts().TrapFuncName);
3048     TrapCall->addAttribute(llvm::AttributeList::FunctionIndex, A);
3049   }
3050 
3051   return TrapCall;
3052 }
3053 
3054 Address CodeGenFunction::EmitArrayToPointerDecay(const Expr *E,
3055                                                  LValueBaseInfo *BaseInfo) {
3056   assert(E->getType()->isArrayType() &&
3057          "Array to pointer decay must have array source type!");
3058 
3059   // Expressions of array type can't be bitfields or vector elements.
3060   LValue LV = EmitLValue(E);
3061   Address Addr = LV.getAddress();
3062   if (BaseInfo) *BaseInfo = LV.getBaseInfo();
3063 
3064   // If the array type was an incomplete type, we need to make sure
3065   // the decay ends up being the right type.
3066   llvm::Type *NewTy = ConvertType(E->getType());
3067   Addr = Builder.CreateElementBitCast(Addr, NewTy);
3068 
3069   // Note that VLA pointers are always decayed, so we don't need to do
3070   // anything here.
3071   if (!E->getType()->isVariableArrayType()) {
3072     assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3073            "Expected pointer to array");
3074     Addr = Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(), "arraydecay");
3075   }
3076 
3077   QualType EltType = E->getType()->castAsArrayTypeUnsafe()->getElementType();
3078   return Builder.CreateElementBitCast(Addr, ConvertTypeForMem(EltType));
3079 }
3080 
3081 /// isSimpleArrayDecayOperand - If the specified expr is a simple decay from an
3082 /// array to pointer, return the array subexpression.
3083 static const Expr *isSimpleArrayDecayOperand(const Expr *E) {
3084   // If this isn't just an array->pointer decay, bail out.
3085   const auto *CE = dyn_cast<CastExpr>(E);
3086   if (!CE || CE->getCastKind() != CK_ArrayToPointerDecay)
3087     return nullptr;
3088 
3089   // If this is a decay from variable width array, bail out.
3090   const Expr *SubExpr = CE->getSubExpr();
3091   if (SubExpr->getType()->isVariableArrayType())
3092     return nullptr;
3093 
3094   return SubExpr;
3095 }
3096 
3097 static llvm::Value *emitArraySubscriptGEP(CodeGenFunction &CGF,
3098                                           llvm::Value *ptr,
3099                                           ArrayRef<llvm::Value*> indices,
3100                                           bool inbounds,
3101                                           bool signedIndices,
3102                                           SourceLocation loc,
3103                                     const llvm::Twine &name = "arrayidx") {
3104   if (inbounds) {
3105     return CGF.EmitCheckedInBoundsGEP(ptr, indices, signedIndices,
3106                                       CodeGenFunction::NotSubtraction, loc,
3107                                       name);
3108   } else {
3109     return CGF.Builder.CreateGEP(ptr, indices, name);
3110   }
3111 }
3112 
3113 static CharUnits getArrayElementAlign(CharUnits arrayAlign,
3114                                       llvm::Value *idx,
3115                                       CharUnits eltSize) {
3116   // If we have a constant index, we can use the exact offset of the
3117   // element we're accessing.
3118   if (auto constantIdx = dyn_cast<llvm::ConstantInt>(idx)) {
3119     CharUnits offset = constantIdx->getZExtValue() * eltSize;
3120     return arrayAlign.alignmentAtOffset(offset);
3121 
3122   // Otherwise, use the worst-case alignment for any element.
3123   } else {
3124     return arrayAlign.alignmentOfArrayElement(eltSize);
3125   }
3126 }
3127 
3128 static QualType getFixedSizeElementType(const ASTContext &ctx,
3129                                         const VariableArrayType *vla) {
3130   QualType eltType;
3131   do {
3132     eltType = vla->getElementType();
3133   } while ((vla = ctx.getAsVariableArrayType(eltType)));
3134   return eltType;
3135 }
3136 
3137 static Address emitArraySubscriptGEP(CodeGenFunction &CGF, Address addr,
3138                                      ArrayRef<llvm::Value *> indices,
3139                                      QualType eltType, bool inbounds,
3140                                      bool signedIndices, SourceLocation loc,
3141                                      const llvm::Twine &name = "arrayidx") {
3142   // All the indices except that last must be zero.
3143 #ifndef NDEBUG
3144   for (auto idx : indices.drop_back())
3145     assert(isa<llvm::ConstantInt>(idx) &&
3146            cast<llvm::ConstantInt>(idx)->isZero());
3147 #endif
3148 
3149   // Determine the element size of the statically-sized base.  This is
3150   // the thing that the indices are expressed in terms of.
3151   if (auto vla = CGF.getContext().getAsVariableArrayType(eltType)) {
3152     eltType = getFixedSizeElementType(CGF.getContext(), vla);
3153   }
3154 
3155   // We can use that to compute the best alignment of the element.
3156   CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
3157   CharUnits eltAlign =
3158     getArrayElementAlign(addr.getAlignment(), indices.back(), eltSize);
3159 
3160   llvm::Value *eltPtr = emitArraySubscriptGEP(
3161       CGF, addr.getPointer(), indices, inbounds, signedIndices, loc, name);
3162   return Address(eltPtr, eltAlign);
3163 }
3164 
3165 LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E,
3166                                                bool Accessed) {
3167   // The index must always be an integer, which is not an aggregate.  Emit it
3168   // in lexical order (this complexity is, sadly, required by C++17).
3169   llvm::Value *IdxPre =
3170       (E->getLHS() == E->getIdx()) ? EmitScalarExpr(E->getIdx()) : nullptr;
3171   bool SignedIndices = false;
3172   auto EmitIdxAfterBase = [&, IdxPre](bool Promote) -> llvm::Value * {
3173     auto *Idx = IdxPre;
3174     if (E->getLHS() != E->getIdx()) {
3175       assert(E->getRHS() == E->getIdx() && "index was neither LHS nor RHS");
3176       Idx = EmitScalarExpr(E->getIdx());
3177     }
3178 
3179     QualType IdxTy = E->getIdx()->getType();
3180     bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
3181     SignedIndices |= IdxSigned;
3182 
3183     if (SanOpts.has(SanitizerKind::ArrayBounds))
3184       EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, Accessed);
3185 
3186     // Extend or truncate the index type to 32 or 64-bits.
3187     if (Promote && Idx->getType() != IntPtrTy)
3188       Idx = Builder.CreateIntCast(Idx, IntPtrTy, IdxSigned, "idxprom");
3189 
3190     return Idx;
3191   };
3192   IdxPre = nullptr;
3193 
3194   // If the base is a vector type, then we are forming a vector element lvalue
3195   // with this subscript.
3196   if (E->getBase()->getType()->isVectorType() &&
3197       !isa<ExtVectorElementExpr>(E->getBase())) {
3198     // Emit the vector as an lvalue to get its address.
3199     LValue LHS = EmitLValue(E->getBase());
3200     auto *Idx = EmitIdxAfterBase(/*Promote*/false);
3201     assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
3202     return LValue::MakeVectorElt(LHS.getAddress(), Idx,
3203                                  E->getBase()->getType(),
3204                                  LHS.getBaseInfo());
3205   }
3206 
3207   // All the other cases basically behave like simple offsetting.
3208 
3209   // Handle the extvector case we ignored above.
3210   if (isa<ExtVectorElementExpr>(E->getBase())) {
3211     LValue LV = EmitLValue(E->getBase());
3212     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3213     Address Addr = EmitExtVectorElementLValue(LV);
3214 
3215     QualType EltType = LV.getType()->castAs<VectorType>()->getElementType();
3216     Addr = emitArraySubscriptGEP(*this, Addr, Idx, EltType, /*inbounds*/ true,
3217                                  SignedIndices, E->getExprLoc());
3218     return MakeAddrLValue(Addr, EltType, LV.getBaseInfo());
3219   }
3220 
3221   LValueBaseInfo BaseInfo;
3222   Address Addr = Address::invalid();
3223   if (const VariableArrayType *vla =
3224            getContext().getAsVariableArrayType(E->getType())) {
3225     // The base must be a pointer, which is not an aggregate.  Emit
3226     // it.  It needs to be emitted first in case it's what captures
3227     // the VLA bounds.
3228     Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
3229     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3230 
3231     // The element count here is the total number of non-VLA elements.
3232     llvm::Value *numElements = getVLASize(vla).first;
3233 
3234     // Effectively, the multiply by the VLA size is part of the GEP.
3235     // GEP indexes are signed, and scaling an index isn't permitted to
3236     // signed-overflow, so we use the same semantics for our explicit
3237     // multiply.  We suppress this if overflow is not undefined behavior.
3238     if (getLangOpts().isSignedOverflowDefined()) {
3239       Idx = Builder.CreateMul(Idx, numElements);
3240     } else {
3241       Idx = Builder.CreateNSWMul(Idx, numElements);
3242     }
3243 
3244     Addr = emitArraySubscriptGEP(*this, Addr, Idx, vla->getElementType(),
3245                                  !getLangOpts().isSignedOverflowDefined(),
3246                                  SignedIndices, E->getExprLoc());
3247 
3248   } else if (const ObjCObjectType *OIT = E->getType()->getAs<ObjCObjectType>()){
3249     // Indexing over an interface, as in "NSString *P; P[4];"
3250 
3251     // Emit the base pointer.
3252     Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
3253     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3254 
3255     CharUnits InterfaceSize = getContext().getTypeSizeInChars(OIT);
3256     llvm::Value *InterfaceSizeVal =
3257         llvm::ConstantInt::get(Idx->getType(), InterfaceSize.getQuantity());
3258 
3259     llvm::Value *ScaledIdx = Builder.CreateMul(Idx, InterfaceSizeVal);
3260 
3261     // We don't necessarily build correct LLVM struct types for ObjC
3262     // interfaces, so we can't rely on GEP to do this scaling
3263     // correctly, so we need to cast to i8*.  FIXME: is this actually
3264     // true?  A lot of other things in the fragile ABI would break...
3265     llvm::Type *OrigBaseTy = Addr.getType();
3266     Addr = Builder.CreateElementBitCast(Addr, Int8Ty);
3267 
3268     // Do the GEP.
3269     CharUnits EltAlign =
3270       getArrayElementAlign(Addr.getAlignment(), Idx, InterfaceSize);
3271     llvm::Value *EltPtr =
3272         emitArraySubscriptGEP(*this, Addr.getPointer(), ScaledIdx, false,
3273                               SignedIndices, E->getExprLoc());
3274     Addr = Address(EltPtr, EltAlign);
3275 
3276     // Cast back.
3277     Addr = Builder.CreateBitCast(Addr, OrigBaseTy);
3278   } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3279     // If this is A[i] where A is an array, the frontend will have decayed the
3280     // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
3281     // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3282     // "gep x, i" here.  Emit one "gep A, 0, i".
3283     assert(Array->getType()->isArrayType() &&
3284            "Array to pointer decay must have array source type!");
3285     LValue ArrayLV;
3286     // For simple multidimensional array indexing, set the 'accessed' flag for
3287     // better bounds-checking of the base expression.
3288     if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3289       ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3290     else
3291       ArrayLV = EmitLValue(Array);
3292     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3293 
3294     // Propagate the alignment from the array itself to the result.
3295     Addr = emitArraySubscriptGEP(
3296         *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3297         E->getType(), !getLangOpts().isSignedOverflowDefined(), SignedIndices,
3298         E->getExprLoc());
3299     BaseInfo = ArrayLV.getBaseInfo();
3300   } else {
3301     // The base must be a pointer; emit it with an estimate of its alignment.
3302     Addr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
3303     auto *Idx = EmitIdxAfterBase(/*Promote*/true);
3304     Addr = emitArraySubscriptGEP(*this, Addr, Idx, E->getType(),
3305                                  !getLangOpts().isSignedOverflowDefined(),
3306                                  SignedIndices, E->getExprLoc());
3307   }
3308 
3309   LValue LV = MakeAddrLValue(Addr, E->getType(), BaseInfo);
3310 
3311   // TODO: Preserve/extend path TBAA metadata?
3312 
3313   if (getLangOpts().ObjC1 &&
3314       getLangOpts().getGC() != LangOptions::NonGC) {
3315     LV.setNonGC(!E->isOBJCGCCandidate(getContext()));
3316     setObjCGCLValueClass(getContext(), E, LV);
3317   }
3318   return LV;
3319 }
3320 
3321 static Address emitOMPArraySectionBase(CodeGenFunction &CGF, const Expr *Base,
3322                                        LValueBaseInfo &BaseInfo,
3323                                        QualType BaseTy, QualType ElTy,
3324                                        bool IsLowerBound) {
3325   LValue BaseLVal;
3326   if (auto *ASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParenImpCasts())) {
3327     BaseLVal = CGF.EmitOMPArraySectionExpr(ASE, IsLowerBound);
3328     if (BaseTy->isArrayType()) {
3329       Address Addr = BaseLVal.getAddress();
3330       BaseInfo = BaseLVal.getBaseInfo();
3331 
3332       // If the array type was an incomplete type, we need to make sure
3333       // the decay ends up being the right type.
3334       llvm::Type *NewTy = CGF.ConvertType(BaseTy);
3335       Addr = CGF.Builder.CreateElementBitCast(Addr, NewTy);
3336 
3337       // Note that VLA pointers are always decayed, so we don't need to do
3338       // anything here.
3339       if (!BaseTy->isVariableArrayType()) {
3340         assert(isa<llvm::ArrayType>(Addr.getElementType()) &&
3341                "Expected pointer to array");
3342         Addr = CGF.Builder.CreateStructGEP(Addr, 0, CharUnits::Zero(),
3343                                            "arraydecay");
3344       }
3345 
3346       return CGF.Builder.CreateElementBitCast(Addr,
3347                                               CGF.ConvertTypeForMem(ElTy));
3348     }
3349     LValueBaseInfo TypeInfo;
3350     CharUnits Align = CGF.getNaturalTypeAlignment(ElTy, &TypeInfo);
3351     BaseInfo.mergeForCast(TypeInfo);
3352     return Address(CGF.Builder.CreateLoad(BaseLVal.getAddress()), Align);
3353   }
3354   return CGF.EmitPointerWithAlignment(Base, &BaseInfo);
3355 }
3356 
3357 LValue CodeGenFunction::EmitOMPArraySectionExpr(const OMPArraySectionExpr *E,
3358                                                 bool IsLowerBound) {
3359   QualType BaseTy;
3360   if (auto *ASE =
3361           dyn_cast<OMPArraySectionExpr>(E->getBase()->IgnoreParenImpCasts()))
3362     BaseTy = OMPArraySectionExpr::getBaseOriginalType(ASE);
3363   else
3364     BaseTy = E->getBase()->getType();
3365   QualType ResultExprTy;
3366   if (auto *AT = getContext().getAsArrayType(BaseTy))
3367     ResultExprTy = AT->getElementType();
3368   else
3369     ResultExprTy = BaseTy->getPointeeType();
3370   llvm::Value *Idx = nullptr;
3371   if (IsLowerBound || E->getColonLoc().isInvalid()) {
3372     // Requesting lower bound or upper bound, but without provided length and
3373     // without ':' symbol for the default length -> length = 1.
3374     // Idx = LowerBound ?: 0;
3375     if (auto *LowerBound = E->getLowerBound()) {
3376       Idx = Builder.CreateIntCast(
3377           EmitScalarExpr(LowerBound), IntPtrTy,
3378           LowerBound->getType()->hasSignedIntegerRepresentation());
3379     } else
3380       Idx = llvm::ConstantInt::getNullValue(IntPtrTy);
3381   } else {
3382     // Try to emit length or lower bound as constant. If this is possible, 1
3383     // is subtracted from constant length or lower bound. Otherwise, emit LLVM
3384     // IR (LB + Len) - 1.
3385     auto &C = CGM.getContext();
3386     auto *Length = E->getLength();
3387     llvm::APSInt ConstLength;
3388     if (Length) {
3389       // Idx = LowerBound + Length - 1;
3390       if (Length->isIntegerConstantExpr(ConstLength, C)) {
3391         ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3392         Length = nullptr;
3393       }
3394       auto *LowerBound = E->getLowerBound();
3395       llvm::APSInt ConstLowerBound(PointerWidthInBits, /*isUnsigned=*/false);
3396       if (LowerBound && LowerBound->isIntegerConstantExpr(ConstLowerBound, C)) {
3397         ConstLowerBound = ConstLowerBound.zextOrTrunc(PointerWidthInBits);
3398         LowerBound = nullptr;
3399       }
3400       if (!Length)
3401         --ConstLength;
3402       else if (!LowerBound)
3403         --ConstLowerBound;
3404 
3405       if (Length || LowerBound) {
3406         auto *LowerBoundVal =
3407             LowerBound
3408                 ? Builder.CreateIntCast(
3409                       EmitScalarExpr(LowerBound), IntPtrTy,
3410                       LowerBound->getType()->hasSignedIntegerRepresentation())
3411                 : llvm::ConstantInt::get(IntPtrTy, ConstLowerBound);
3412         auto *LengthVal =
3413             Length
3414                 ? Builder.CreateIntCast(
3415                       EmitScalarExpr(Length), IntPtrTy,
3416                       Length->getType()->hasSignedIntegerRepresentation())
3417                 : llvm::ConstantInt::get(IntPtrTy, ConstLength);
3418         Idx = Builder.CreateAdd(LowerBoundVal, LengthVal, "lb_add_len",
3419                                 /*HasNUW=*/false,
3420                                 !getLangOpts().isSignedOverflowDefined());
3421         if (Length && LowerBound) {
3422           Idx = Builder.CreateSub(
3423               Idx, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "idx_sub_1",
3424               /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3425         }
3426       } else
3427         Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength + ConstLowerBound);
3428     } else {
3429       // Idx = ArraySize - 1;
3430       QualType ArrayTy = BaseTy->isPointerType()
3431                              ? E->getBase()->IgnoreParenImpCasts()->getType()
3432                              : BaseTy;
3433       if (auto *VAT = C.getAsVariableArrayType(ArrayTy)) {
3434         Length = VAT->getSizeExpr();
3435         if (Length->isIntegerConstantExpr(ConstLength, C))
3436           Length = nullptr;
3437       } else {
3438         auto *CAT = C.getAsConstantArrayType(ArrayTy);
3439         ConstLength = CAT->getSize();
3440       }
3441       if (Length) {
3442         auto *LengthVal = Builder.CreateIntCast(
3443             EmitScalarExpr(Length), IntPtrTy,
3444             Length->getType()->hasSignedIntegerRepresentation());
3445         Idx = Builder.CreateSub(
3446             LengthVal, llvm::ConstantInt::get(IntPtrTy, /*V=*/1), "len_sub_1",
3447             /*HasNUW=*/false, !getLangOpts().isSignedOverflowDefined());
3448       } else {
3449         ConstLength = ConstLength.zextOrTrunc(PointerWidthInBits);
3450         --ConstLength;
3451         Idx = llvm::ConstantInt::get(IntPtrTy, ConstLength);
3452       }
3453     }
3454   }
3455   assert(Idx);
3456 
3457   Address EltPtr = Address::invalid();
3458   LValueBaseInfo BaseInfo;
3459   if (auto *VLA = getContext().getAsVariableArrayType(ResultExprTy)) {
3460     // The base must be a pointer, which is not an aggregate.  Emit
3461     // it.  It needs to be emitted first in case it's what captures
3462     // the VLA bounds.
3463     Address Base =
3464         emitOMPArraySectionBase(*this, E->getBase(), BaseInfo, BaseTy,
3465                                 VLA->getElementType(), IsLowerBound);
3466     // The element count here is the total number of non-VLA elements.
3467     llvm::Value *NumElements = getVLASize(VLA).first;
3468 
3469     // Effectively, the multiply by the VLA size is part of the GEP.
3470     // GEP indexes are signed, and scaling an index isn't permitted to
3471     // signed-overflow, so we use the same semantics for our explicit
3472     // multiply.  We suppress this if overflow is not undefined behavior.
3473     if (getLangOpts().isSignedOverflowDefined())
3474       Idx = Builder.CreateMul(Idx, NumElements);
3475     else
3476       Idx = Builder.CreateNSWMul(Idx, NumElements);
3477     EltPtr = emitArraySubscriptGEP(*this, Base, Idx, VLA->getElementType(),
3478                                    !getLangOpts().isSignedOverflowDefined(),
3479                                    /*SignedIndices=*/false, E->getExprLoc());
3480   } else if (const Expr *Array = isSimpleArrayDecayOperand(E->getBase())) {
3481     // If this is A[i] where A is an array, the frontend will have decayed the
3482     // base to be a ArrayToPointerDecay implicit cast.  While correct, it is
3483     // inefficient at -O0 to emit a "gep A, 0, 0" when codegen'ing it, then a
3484     // "gep x, i" here.  Emit one "gep A, 0, i".
3485     assert(Array->getType()->isArrayType() &&
3486            "Array to pointer decay must have array source type!");
3487     LValue ArrayLV;
3488     // For simple multidimensional array indexing, set the 'accessed' flag for
3489     // better bounds-checking of the base expression.
3490     if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(Array))
3491       ArrayLV = EmitArraySubscriptExpr(ASE, /*Accessed*/ true);
3492     else
3493       ArrayLV = EmitLValue(Array);
3494 
3495     // Propagate the alignment from the array itself to the result.
3496     EltPtr = emitArraySubscriptGEP(
3497         *this, ArrayLV.getAddress(), {CGM.getSize(CharUnits::Zero()), Idx},
3498         ResultExprTy, !getLangOpts().isSignedOverflowDefined(),
3499         /*SignedIndices=*/false, E->getExprLoc());
3500     BaseInfo = ArrayLV.getBaseInfo();
3501   } else {
3502     Address Base = emitOMPArraySectionBase(*this, E->getBase(), BaseInfo,
3503                                            BaseTy, ResultExprTy, IsLowerBound);
3504     EltPtr = emitArraySubscriptGEP(*this, Base, Idx, ResultExprTy,
3505                                    !getLangOpts().isSignedOverflowDefined(),
3506                                    /*SignedIndices=*/false, E->getExprLoc());
3507   }
3508 
3509   return MakeAddrLValue(EltPtr, ResultExprTy, BaseInfo);
3510 }
3511 
3512 LValue CodeGenFunction::
3513 EmitExtVectorElementExpr(const ExtVectorElementExpr *E) {
3514   // Emit the base vector as an l-value.
3515   LValue Base;
3516 
3517   // ExtVectorElementExpr's base can either be a vector or pointer to vector.
3518   if (E->isArrow()) {
3519     // If it is a pointer to a vector, emit the address and form an lvalue with
3520     // it.
3521     LValueBaseInfo BaseInfo;
3522     Address Ptr = EmitPointerWithAlignment(E->getBase(), &BaseInfo);
3523     const PointerType *PT = E->getBase()->getType()->getAs<PointerType>();
3524     Base = MakeAddrLValue(Ptr, PT->getPointeeType(), BaseInfo);
3525     Base.getQuals().removeObjCGCAttr();
3526   } else if (E->getBase()->isGLValue()) {
3527     // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
3528     // emit the base as an lvalue.
3529     assert(E->getBase()->getType()->isVectorType());
3530     Base = EmitLValue(E->getBase());
3531   } else {
3532     // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
3533     assert(E->getBase()->getType()->isVectorType() &&
3534            "Result must be a vector");
3535     llvm::Value *Vec = EmitScalarExpr(E->getBase());
3536 
3537     // Store the vector to memory (because LValue wants an address).
3538     Address VecMem = CreateMemTemp(E->getBase()->getType());
3539     Builder.CreateStore(Vec, VecMem);
3540     Base = MakeAddrLValue(VecMem, E->getBase()->getType(),
3541                           LValueBaseInfo(AlignmentSource::Decl, false));
3542   }
3543 
3544   QualType type =
3545     E->getType().withCVRQualifiers(Base.getQuals().getCVRQualifiers());
3546 
3547   // Encode the element access list into a vector of unsigned indices.
3548   SmallVector<uint32_t, 4> Indices;
3549   E->getEncodedElementAccess(Indices);
3550 
3551   if (Base.isSimple()) {
3552     llvm::Constant *CV =
3553         llvm::ConstantDataVector::get(getLLVMContext(), Indices);
3554     return LValue::MakeExtVectorElt(Base.getAddress(), CV, type,
3555                                     Base.getBaseInfo());
3556   }
3557   assert(Base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
3558 
3559   llvm::Constant *BaseElts = Base.getExtVectorElts();
3560   SmallVector<llvm::Constant *, 4> CElts;
3561 
3562   for (unsigned i = 0, e = Indices.size(); i != e; ++i)
3563     CElts.push_back(BaseElts->getAggregateElement(Indices[i]));
3564   llvm::Constant *CV = llvm::ConstantVector::get(CElts);
3565   return LValue::MakeExtVectorElt(Base.getExtVectorAddress(), CV, type,
3566                                   Base.getBaseInfo());
3567 }
3568 
3569 LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
3570   if (DeclRefExpr *DRE = tryToConvertMemberExprToDeclRefExpr(*this, E)) {
3571     EmitIgnoredExpr(E->getBase());
3572     return EmitDeclRefLValue(DRE);
3573   }
3574 
3575   Expr *BaseExpr = E->getBase();
3576   // If this is s.x, emit s as an lvalue.  If it is s->x, emit s as a scalar.
3577   LValue BaseLV;
3578   if (E->isArrow()) {
3579     LValueBaseInfo BaseInfo;
3580     Address Addr = EmitPointerWithAlignment(BaseExpr, &BaseInfo);
3581     QualType PtrTy = BaseExpr->getType()->getPointeeType();
3582     SanitizerSet SkippedChecks;
3583     bool IsBaseCXXThis = IsWrappedCXXThis(BaseExpr);
3584     if (IsBaseCXXThis)
3585       SkippedChecks.set(SanitizerKind::Alignment, true);
3586     if (IsBaseCXXThis || isa<DeclRefExpr>(BaseExpr))
3587       SkippedChecks.set(SanitizerKind::Null, true);
3588     EmitTypeCheck(TCK_MemberAccess, E->getExprLoc(), Addr.getPointer(), PtrTy,
3589                   /*Alignment=*/CharUnits::Zero(), SkippedChecks);
3590     BaseLV = MakeAddrLValue(Addr, PtrTy, BaseInfo);
3591   } else
3592     BaseLV = EmitCheckedLValue(BaseExpr, TCK_MemberAccess);
3593 
3594   NamedDecl *ND = E->getMemberDecl();
3595   if (auto *Field = dyn_cast<FieldDecl>(ND)) {
3596     LValue LV = EmitLValueForField(BaseLV, Field);
3597     setObjCGCLValueClass(getContext(), E, LV);
3598     return LV;
3599   }
3600 
3601   if (const auto *FD = dyn_cast<FunctionDecl>(ND))
3602     return EmitFunctionDeclLValue(*this, E, FD);
3603 
3604   llvm_unreachable("Unhandled member declaration!");
3605 }
3606 
3607 /// Given that we are currently emitting a lambda, emit an l-value for
3608 /// one of its members.
3609 LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
3610   assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
3611   assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
3612   QualType LambdaTagType =
3613     getContext().getTagDeclType(Field->getParent());
3614   LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
3615   return EmitLValueForField(LambdaLV, Field);
3616 }
3617 
3618 /// Drill down to the storage of a field without walking into
3619 /// reference types.
3620 ///
3621 /// The resulting address doesn't necessarily have the right type.
3622 static Address emitAddrOfFieldStorage(CodeGenFunction &CGF, Address base,
3623                                       const FieldDecl *field) {
3624   const RecordDecl *rec = field->getParent();
3625 
3626   unsigned idx =
3627     CGF.CGM.getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field);
3628 
3629   CharUnits offset;
3630   // Adjust the alignment down to the given offset.
3631   // As a special case, if the LLVM field index is 0, we know that this
3632   // is zero.
3633   assert((idx != 0 || CGF.getContext().getASTRecordLayout(rec)
3634                          .getFieldOffset(field->getFieldIndex()) == 0) &&
3635          "LLVM field at index zero had non-zero offset?");
3636   if (idx != 0) {
3637     auto &recLayout = CGF.getContext().getASTRecordLayout(rec);
3638     auto offsetInBits = recLayout.getFieldOffset(field->getFieldIndex());
3639     offset = CGF.getContext().toCharUnitsFromBits(offsetInBits);
3640   }
3641 
3642   return CGF.Builder.CreateStructGEP(base, idx, offset, field->getName());
3643 }
3644 
3645 static bool hasAnyVptr(const QualType Type, const ASTContext &Context) {
3646   const auto *RD = Type.getTypePtr()->getAsCXXRecordDecl();
3647   if (!RD)
3648     return false;
3649 
3650   if (RD->isDynamicClass())
3651     return true;
3652 
3653   for (const auto &Base : RD->bases())
3654     if (hasAnyVptr(Base.getType(), Context))
3655       return true;
3656 
3657   for (const FieldDecl *Field : RD->fields())
3658     if (hasAnyVptr(Field->getType(), Context))
3659       return true;
3660 
3661   return false;
3662 }
3663 
3664 LValue CodeGenFunction::EmitLValueForField(LValue base,
3665                                            const FieldDecl *field) {
3666   LValueBaseInfo BaseInfo = base.getBaseInfo();
3667   AlignmentSource fieldAlignSource =
3668     getFieldAlignmentSource(BaseInfo.getAlignmentSource());
3669   LValueBaseInfo FieldBaseInfo(fieldAlignSource, BaseInfo.getMayAlias());
3670 
3671   QualType type = field->getType();
3672   const RecordDecl *rec = field->getParent();
3673   if (rec->isUnion() || rec->hasAttr<MayAliasAttr>() || type->isVectorType())
3674     FieldBaseInfo.setMayAlias(true);
3675   bool mayAlias = FieldBaseInfo.getMayAlias();
3676 
3677   if (field->isBitField()) {
3678     const CGRecordLayout &RL =
3679       CGM.getTypes().getCGRecordLayout(field->getParent());
3680     const CGBitFieldInfo &Info = RL.getBitFieldInfo(field);
3681     Address Addr = base.getAddress();
3682     unsigned Idx = RL.getLLVMFieldNo(field);
3683     if (Idx != 0)
3684       // For structs, we GEP to the field that the record layout suggests.
3685       Addr = Builder.CreateStructGEP(Addr, Idx, Info.StorageOffset,
3686                                      field->getName());
3687     // Get the access type.
3688     llvm::Type *FieldIntTy =
3689       llvm::Type::getIntNTy(getLLVMContext(), Info.StorageSize);
3690     if (Addr.getElementType() != FieldIntTy)
3691       Addr = Builder.CreateElementBitCast(Addr, FieldIntTy);
3692 
3693     QualType fieldType =
3694       field->getType().withCVRQualifiers(base.getVRQualifiers());
3695     return LValue::MakeBitfield(Addr, Info, fieldType, FieldBaseInfo);
3696   }
3697 
3698   Address addr = base.getAddress();
3699   unsigned cvr = base.getVRQualifiers();
3700   bool TBAAPath = CGM.getCodeGenOpts().StructPathTBAA;
3701   if (rec->isUnion()) {
3702     // For unions, there is no pointer adjustment.
3703     assert(!type->isReferenceType() && "union has reference member");
3704     // TODO: handle path-aware TBAA for union.
3705     TBAAPath = false;
3706 
3707     const auto FieldType = field->getType();
3708     if (CGM.getCodeGenOpts().StrictVTablePointers &&
3709         hasAnyVptr(FieldType, getContext()))
3710       // Because unions can easily skip invariant.barriers, we need to add
3711       // a barrier every time CXXRecord field with vptr is referenced.
3712       addr = Address(Builder.CreateInvariantGroupBarrier(addr.getPointer()),
3713                      addr.getAlignment());
3714   } else {
3715     // For structs, we GEP to the field that the record layout suggests.
3716     addr = emitAddrOfFieldStorage(*this, addr, field);
3717 
3718     // If this is a reference field, load the reference right now.
3719     if (const ReferenceType *refType = type->getAs<ReferenceType>()) {
3720       llvm::LoadInst *load = Builder.CreateLoad(addr, "ref");
3721       if (cvr & Qualifiers::Volatile) load->setVolatile(true);
3722 
3723       // Loading the reference will disable path-aware TBAA.
3724       TBAAPath = false;
3725       TBAAAccessInfo TBAAInfo = mayAlias ? CGM.getTBAAMayAliasAccessInfo() :
3726                                            CGM.getTBAAAccessInfo(type);
3727       CGM.DecorateInstructionWithTBAA(load, TBAAInfo);
3728 
3729       mayAlias = false;
3730       type = refType->getPointeeType();
3731 
3732       CharUnits alignment =
3733         getNaturalTypeAlignment(type, &FieldBaseInfo, /*pointee*/ true);
3734       FieldBaseInfo.setMayAlias(false);
3735       addr = Address(load, alignment);
3736 
3737       // Qualifiers on the struct don't apply to the referencee, and
3738       // we'll pick up CVR from the actual type later, so reset these
3739       // additional qualifiers now.
3740       cvr = 0;
3741     }
3742   }
3743 
3744   // Make sure that the address is pointing to the right type.  This is critical
3745   // for both unions and structs.  A union needs a bitcast, a struct element
3746   // will need a bitcast if the LLVM type laid out doesn't match the desired
3747   // type.
3748   addr = Builder.CreateElementBitCast(addr,
3749                                       CGM.getTypes().ConvertTypeForMem(type),
3750                                       field->getName());
3751 
3752   if (field->hasAttr<AnnotateAttr>())
3753     addr = EmitFieldAnnotations(field, addr);
3754 
3755   LValue LV = MakeAddrLValue(addr, type, FieldBaseInfo);
3756   LV.getQuals().addCVRQualifiers(cvr);
3757 
3758   // Fields of may_alias structs act like 'char' for TBAA purposes.
3759   // FIXME: this should get propagated down through anonymous structs
3760   // and unions.
3761   if (mayAlias) {
3762     LV.setTBAAInfo(CGM.getTBAAMayAliasAccessInfo());
3763   } else if (TBAAPath) {
3764     // If no base type been assigned for the base access, then try to generate
3765     // one for this base lvalue.
3766     TBAAAccessInfo TBAAInfo = base.getTBAAInfo();
3767     if (!TBAAInfo.BaseType) {
3768         TBAAInfo.BaseType = CGM.getTBAABaseTypeInfo(base.getType());
3769         assert(!TBAAInfo.Offset &&
3770                "Nonzero offset for an access with no base type!");
3771     }
3772 
3773     // Adjust offset to be relative to the base type.
3774     const ASTRecordLayout &Layout =
3775         getContext().getASTRecordLayout(field->getParent());
3776     unsigned CharWidth = getContext().getCharWidth();
3777     if (TBAAInfo.BaseType)
3778       TBAAInfo.Offset +=
3779           Layout.getFieldOffset(field->getFieldIndex()) / CharWidth;
3780 
3781     // Update the final access type.
3782     TBAAInfo.AccessType = LV.getTBAAInfo().AccessType;
3783 
3784     LV.setTBAAInfo(TBAAInfo);
3785   }
3786 
3787   // __weak attribute on a field is ignored.
3788   if (LV.getQuals().getObjCGCAttr() == Qualifiers::Weak)
3789     LV.getQuals().removeObjCGCAttr();
3790 
3791   return LV;
3792 }
3793 
3794 LValue
3795 CodeGenFunction::EmitLValueForFieldInitialization(LValue Base,
3796                                                   const FieldDecl *Field) {
3797   QualType FieldType = Field->getType();
3798 
3799   if (!FieldType->isReferenceType())
3800     return EmitLValueForField(Base, Field);
3801 
3802   Address V = emitAddrOfFieldStorage(*this, Base.getAddress(), Field);
3803 
3804   // Make sure that the address is pointing to the right type.
3805   llvm::Type *llvmType = ConvertTypeForMem(FieldType);
3806   V = Builder.CreateElementBitCast(V, llvmType, Field->getName());
3807 
3808   // TODO: access-path TBAA?
3809   LValueBaseInfo BaseInfo = Base.getBaseInfo();
3810   LValueBaseInfo FieldBaseInfo(
3811       getFieldAlignmentSource(BaseInfo.getAlignmentSource()),
3812       BaseInfo.getMayAlias());
3813   return MakeAddrLValue(V, FieldType, FieldBaseInfo);
3814 }
3815 
3816 LValue CodeGenFunction::EmitCompoundLiteralLValue(const CompoundLiteralExpr *E){
3817   LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
3818   if (E->isFileScope()) {
3819     ConstantAddress GlobalPtr = CGM.GetAddrOfConstantCompoundLiteral(E);
3820     return MakeAddrLValue(GlobalPtr, E->getType(), BaseInfo);
3821   }
3822   if (E->getType()->isVariablyModifiedType())
3823     // make sure to emit the VLA size.
3824     EmitVariablyModifiedType(E->getType());
3825 
3826   Address DeclPtr = CreateMemTemp(E->getType(), ".compoundliteral");
3827   const Expr *InitExpr = E->getInitializer();
3828   LValue Result = MakeAddrLValue(DeclPtr, E->getType(), BaseInfo);
3829 
3830   EmitAnyExprToMem(InitExpr, DeclPtr, E->getType().getQualifiers(),
3831                    /*Init*/ true);
3832 
3833   return Result;
3834 }
3835 
3836 LValue CodeGenFunction::EmitInitListLValue(const InitListExpr *E) {
3837   if (!E->isGLValue())
3838     // Initializing an aggregate temporary in C++11: T{...}.
3839     return EmitAggExprToLValue(E);
3840 
3841   // An lvalue initializer list must be initializing a reference.
3842   assert(E->isTransparent() && "non-transparent glvalue init list");
3843   return EmitLValue(E->getInit(0));
3844 }
3845 
3846 /// Emit the operand of a glvalue conditional operator. This is either a glvalue
3847 /// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3848 /// LValue is returned and the current block has been terminated.
3849 static Optional<LValue> EmitLValueOrThrowExpression(CodeGenFunction &CGF,
3850                                                     const Expr *Operand) {
3851   if (auto *ThrowExpr = dyn_cast<CXXThrowExpr>(Operand->IgnoreParens())) {
3852     CGF.EmitCXXThrowExpr(ThrowExpr, /*KeepInsertionPoint*/false);
3853     return None;
3854   }
3855 
3856   return CGF.EmitLValue(Operand);
3857 }
3858 
3859 LValue CodeGenFunction::
3860 EmitConditionalOperatorLValue(const AbstractConditionalOperator *expr) {
3861   if (!expr->isGLValue()) {
3862     // ?: here should be an aggregate.
3863     assert(hasAggregateEvaluationKind(expr->getType()) &&
3864            "Unexpected conditional operator!");
3865     return EmitAggExprToLValue(expr);
3866   }
3867 
3868   OpaqueValueMapping binding(*this, expr);
3869 
3870   const Expr *condExpr = expr->getCond();
3871   bool CondExprBool;
3872   if (ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
3873     const Expr *live = expr->getTrueExpr(), *dead = expr->getFalseExpr();
3874     if (!CondExprBool) std::swap(live, dead);
3875 
3876     if (!ContainsLabel(dead)) {
3877       // If the true case is live, we need to track its region.
3878       if (CondExprBool)
3879         incrementProfileCounter(expr);
3880       return EmitLValue(live);
3881     }
3882   }
3883 
3884   llvm::BasicBlock *lhsBlock = createBasicBlock("cond.true");
3885   llvm::BasicBlock *rhsBlock = createBasicBlock("cond.false");
3886   llvm::BasicBlock *contBlock = createBasicBlock("cond.end");
3887 
3888   ConditionalEvaluation eval(*this);
3889   EmitBranchOnBoolExpr(condExpr, lhsBlock, rhsBlock, getProfileCount(expr));
3890 
3891   // Any temporaries created here are conditional.
3892   EmitBlock(lhsBlock);
3893   incrementProfileCounter(expr);
3894   eval.begin(*this);
3895   Optional<LValue> lhs =
3896       EmitLValueOrThrowExpression(*this, expr->getTrueExpr());
3897   eval.end(*this);
3898 
3899   if (lhs && !lhs->isSimple())
3900     return EmitUnsupportedLValue(expr, "conditional operator");
3901 
3902   lhsBlock = Builder.GetInsertBlock();
3903   if (lhs)
3904     Builder.CreateBr(contBlock);
3905 
3906   // Any temporaries created here are conditional.
3907   EmitBlock(rhsBlock);
3908   eval.begin(*this);
3909   Optional<LValue> rhs =
3910       EmitLValueOrThrowExpression(*this, expr->getFalseExpr());
3911   eval.end(*this);
3912   if (rhs && !rhs->isSimple())
3913     return EmitUnsupportedLValue(expr, "conditional operator");
3914   rhsBlock = Builder.GetInsertBlock();
3915 
3916   EmitBlock(contBlock);
3917 
3918   if (lhs && rhs) {
3919     llvm::PHINode *phi = Builder.CreatePHI(lhs->getPointer()->getType(),
3920                                            2, "cond-lvalue");
3921     phi->addIncoming(lhs->getPointer(), lhsBlock);
3922     phi->addIncoming(rhs->getPointer(), rhsBlock);
3923     Address result(phi, std::min(lhs->getAlignment(), rhs->getAlignment()));
3924     AlignmentSource alignSource =
3925       std::max(lhs->getBaseInfo().getAlignmentSource(),
3926                rhs->getBaseInfo().getAlignmentSource());
3927     bool MayAlias = lhs->getBaseInfo().getMayAlias() ||
3928                     rhs->getBaseInfo().getMayAlias();
3929     return MakeAddrLValue(result, expr->getType(),
3930                           LValueBaseInfo(alignSource, MayAlias));
3931   } else {
3932     assert((lhs || rhs) &&
3933            "both operands of glvalue conditional are throw-expressions?");
3934     return lhs ? *lhs : *rhs;
3935   }
3936 }
3937 
3938 /// EmitCastLValue - Casts are never lvalues unless that cast is to a reference
3939 /// type. If the cast is to a reference, we can have the usual lvalue result,
3940 /// otherwise if a cast is needed by the code generator in an lvalue context,
3941 /// then it must mean that we need the address of an aggregate in order to
3942 /// access one of its members.  This can happen for all the reasons that casts
3943 /// are permitted with aggregate result, including noop aggregate casts, and
3944 /// cast from scalar to union.
3945 LValue CodeGenFunction::EmitCastLValue(const CastExpr *E) {
3946   switch (E->getCastKind()) {
3947   case CK_ToVoid:
3948   case CK_BitCast:
3949   case CK_ArrayToPointerDecay:
3950   case CK_FunctionToPointerDecay:
3951   case CK_NullToMemberPointer:
3952   case CK_NullToPointer:
3953   case CK_IntegralToPointer:
3954   case CK_PointerToIntegral:
3955   case CK_PointerToBoolean:
3956   case CK_VectorSplat:
3957   case CK_IntegralCast:
3958   case CK_BooleanToSignedIntegral:
3959   case CK_IntegralToBoolean:
3960   case CK_IntegralToFloating:
3961   case CK_FloatingToIntegral:
3962   case CK_FloatingToBoolean:
3963   case CK_FloatingCast:
3964   case CK_FloatingRealToComplex:
3965   case CK_FloatingComplexToReal:
3966   case CK_FloatingComplexToBoolean:
3967   case CK_FloatingComplexCast:
3968   case CK_FloatingComplexToIntegralComplex:
3969   case CK_IntegralRealToComplex:
3970   case CK_IntegralComplexToReal:
3971   case CK_IntegralComplexToBoolean:
3972   case CK_IntegralComplexCast:
3973   case CK_IntegralComplexToFloatingComplex:
3974   case CK_DerivedToBaseMemberPointer:
3975   case CK_BaseToDerivedMemberPointer:
3976   case CK_MemberPointerToBoolean:
3977   case CK_ReinterpretMemberPointer:
3978   case CK_AnyPointerToBlockPointerCast:
3979   case CK_ARCProduceObject:
3980   case CK_ARCConsumeObject:
3981   case CK_ARCReclaimReturnedObject:
3982   case CK_ARCExtendBlockObject:
3983   case CK_CopyAndAutoreleaseBlockObject:
3984   case CK_AddressSpaceConversion:
3985   case CK_IntToOCLSampler:
3986     return EmitUnsupportedLValue(E, "unexpected cast lvalue");
3987 
3988   case CK_Dependent:
3989     llvm_unreachable("dependent cast kind in IR gen!");
3990 
3991   case CK_BuiltinFnToFnPtr:
3992     llvm_unreachable("builtin functions are handled elsewhere");
3993 
3994   // These are never l-values; just use the aggregate emission code.
3995   case CK_NonAtomicToAtomic:
3996   case CK_AtomicToNonAtomic:
3997     return EmitAggExprToLValue(E);
3998 
3999   case CK_Dynamic: {
4000     LValue LV = EmitLValue(E->getSubExpr());
4001     Address V = LV.getAddress();
4002     const auto *DCE = cast<CXXDynamicCastExpr>(E);
4003     return MakeNaturalAlignAddrLValue(EmitDynamicCast(V, DCE), E->getType());
4004   }
4005 
4006   case CK_ConstructorConversion:
4007   case CK_UserDefinedConversion:
4008   case CK_CPointerToObjCPointerCast:
4009   case CK_BlockPointerToObjCPointerCast:
4010   case CK_NoOp:
4011   case CK_LValueToRValue:
4012     return EmitLValue(E->getSubExpr());
4013 
4014   case CK_UncheckedDerivedToBase:
4015   case CK_DerivedToBase: {
4016     const RecordType *DerivedClassTy =
4017       E->getSubExpr()->getType()->getAs<RecordType>();
4018     auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
4019 
4020     LValue LV = EmitLValue(E->getSubExpr());
4021     Address This = LV.getAddress();
4022 
4023     // Perform the derived-to-base conversion
4024     Address Base = GetAddressOfBaseClass(
4025         This, DerivedClassDecl, E->path_begin(), E->path_end(),
4026         /*NullCheckValue=*/false, E->getExprLoc());
4027 
4028     return MakeAddrLValue(Base, E->getType(), LV.getBaseInfo());
4029   }
4030   case CK_ToUnion:
4031     return EmitAggExprToLValue(E);
4032   case CK_BaseToDerived: {
4033     const RecordType *DerivedClassTy = E->getType()->getAs<RecordType>();
4034     auto *DerivedClassDecl = cast<CXXRecordDecl>(DerivedClassTy->getDecl());
4035 
4036     LValue LV = EmitLValue(E->getSubExpr());
4037 
4038     // Perform the base-to-derived conversion
4039     Address Derived =
4040       GetAddressOfDerivedClass(LV.getAddress(), DerivedClassDecl,
4041                                E->path_begin(), E->path_end(),
4042                                /*NullCheckValue=*/false);
4043 
4044     // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
4045     // performed and the object is not of the derived type.
4046     if (sanitizePerformTypeCheck())
4047       EmitTypeCheck(TCK_DowncastReference, E->getExprLoc(),
4048                     Derived.getPointer(), E->getType());
4049 
4050     if (SanOpts.has(SanitizerKind::CFIDerivedCast))
4051       EmitVTablePtrCheckForCast(E->getType(), Derived.getPointer(),
4052                                 /*MayBeNull=*/false,
4053                                 CFITCK_DerivedCast, E->getLocStart());
4054 
4055     return MakeAddrLValue(Derived, E->getType(), LV.getBaseInfo());
4056   }
4057   case CK_LValueBitCast: {
4058     // This must be a reinterpret_cast (or c-style equivalent).
4059     const auto *CE = cast<ExplicitCastExpr>(E);
4060 
4061     CGM.EmitExplicitCastExprType(CE, this);
4062     LValue LV = EmitLValue(E->getSubExpr());
4063     Address V = Builder.CreateBitCast(LV.getAddress(),
4064                                       ConvertType(CE->getTypeAsWritten()));
4065 
4066     if (SanOpts.has(SanitizerKind::CFIUnrelatedCast))
4067       EmitVTablePtrCheckForCast(E->getType(), V.getPointer(),
4068                                 /*MayBeNull=*/false,
4069                                 CFITCK_UnrelatedCast, E->getLocStart());
4070 
4071     return MakeAddrLValue(V, E->getType(), LV.getBaseInfo());
4072   }
4073   case CK_ObjCObjectLValueCast: {
4074     LValue LV = EmitLValue(E->getSubExpr());
4075     Address V = Builder.CreateElementBitCast(LV.getAddress(),
4076                                              ConvertType(E->getType()));
4077     return MakeAddrLValue(V, E->getType(), LV.getBaseInfo());
4078   }
4079   case CK_ZeroToOCLQueue:
4080     llvm_unreachable("NULL to OpenCL queue lvalue cast is not valid");
4081   case CK_ZeroToOCLEvent:
4082     llvm_unreachable("NULL to OpenCL event lvalue cast is not valid");
4083   }
4084 
4085   llvm_unreachable("Unhandled lvalue cast kind?");
4086 }
4087 
4088 LValue CodeGenFunction::EmitOpaqueValueLValue(const OpaqueValueExpr *e) {
4089   assert(OpaqueValueMappingData::shouldBindAsLValue(e));
4090   return getOpaqueLValueMapping(e);
4091 }
4092 
4093 RValue CodeGenFunction::EmitRValueForField(LValue LV,
4094                                            const FieldDecl *FD,
4095                                            SourceLocation Loc) {
4096   QualType FT = FD->getType();
4097   LValue FieldLV = EmitLValueForField(LV, FD);
4098   switch (getEvaluationKind(FT)) {
4099   case TEK_Complex:
4100     return RValue::getComplex(EmitLoadOfComplex(FieldLV, Loc));
4101   case TEK_Aggregate:
4102     return FieldLV.asAggregateRValue();
4103   case TEK_Scalar:
4104     // This routine is used to load fields one-by-one to perform a copy, so
4105     // don't load reference fields.
4106     if (FD->getType()->isReferenceType())
4107       return RValue::get(FieldLV.getPointer());
4108     return EmitLoadOfLValue(FieldLV, Loc);
4109   }
4110   llvm_unreachable("bad evaluation kind");
4111 }
4112 
4113 //===--------------------------------------------------------------------===//
4114 //                             Expression Emission
4115 //===--------------------------------------------------------------------===//
4116 
4117 RValue CodeGenFunction::EmitCallExpr(const CallExpr *E,
4118                                      ReturnValueSlot ReturnValue) {
4119   // Builtins never have block type.
4120   if (E->getCallee()->getType()->isBlockPointerType())
4121     return EmitBlockCallExpr(E, ReturnValue);
4122 
4123   if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
4124     return EmitCXXMemberCallExpr(CE, ReturnValue);
4125 
4126   if (const auto *CE = dyn_cast<CUDAKernelCallExpr>(E))
4127     return EmitCUDAKernelCallExpr(CE, ReturnValue);
4128 
4129   if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(E))
4130     if (const CXXMethodDecl *MD =
4131           dyn_cast_or_null<CXXMethodDecl>(CE->getCalleeDecl()))
4132       return EmitCXXOperatorMemberCallExpr(CE, MD, ReturnValue);
4133 
4134   CGCallee callee = EmitCallee(E->getCallee());
4135 
4136   if (callee.isBuiltin()) {
4137     return EmitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(),
4138                            E, ReturnValue);
4139   }
4140 
4141   if (callee.isPseudoDestructor()) {
4142     return EmitCXXPseudoDestructorExpr(callee.getPseudoDestructorExpr());
4143   }
4144 
4145   return EmitCall(E->getCallee()->getType(), callee, E, ReturnValue);
4146 }
4147 
4148 /// Emit a CallExpr without considering whether it might be a subclass.
4149 RValue CodeGenFunction::EmitSimpleCallExpr(const CallExpr *E,
4150                                            ReturnValueSlot ReturnValue) {
4151   CGCallee Callee = EmitCallee(E->getCallee());
4152   return EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue);
4153 }
4154 
4155 static CGCallee EmitDirectCallee(CodeGenFunction &CGF, const FunctionDecl *FD) {
4156   if (auto builtinID = FD->getBuiltinID()) {
4157     return CGCallee::forBuiltin(builtinID, FD);
4158   }
4159 
4160   llvm::Constant *calleePtr = EmitFunctionDeclPointer(CGF.CGM, FD);
4161   return CGCallee::forDirect(calleePtr, FD);
4162 }
4163 
4164 CGCallee CodeGenFunction::EmitCallee(const Expr *E) {
4165   E = E->IgnoreParens();
4166 
4167   // Look through function-to-pointer decay.
4168   if (auto ICE = dyn_cast<ImplicitCastExpr>(E)) {
4169     if (ICE->getCastKind() == CK_FunctionToPointerDecay ||
4170         ICE->getCastKind() == CK_BuiltinFnToFnPtr) {
4171       return EmitCallee(ICE->getSubExpr());
4172     }
4173 
4174   // Resolve direct calls.
4175   } else if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
4176     if (auto FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
4177       return EmitDirectCallee(*this, FD);
4178     }
4179   } else if (auto ME = dyn_cast<MemberExpr>(E)) {
4180     if (auto FD = dyn_cast<FunctionDecl>(ME->getMemberDecl())) {
4181       EmitIgnoredExpr(ME->getBase());
4182       return EmitDirectCallee(*this, FD);
4183     }
4184 
4185   // Look through template substitutions.
4186   } else if (auto NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E)) {
4187     return EmitCallee(NTTP->getReplacement());
4188 
4189   // Treat pseudo-destructor calls differently.
4190   } else if (auto PDE = dyn_cast<CXXPseudoDestructorExpr>(E)) {
4191     return CGCallee::forPseudoDestructor(PDE);
4192   }
4193 
4194   // Otherwise, we have an indirect reference.
4195   llvm::Value *calleePtr;
4196   QualType functionType;
4197   if (auto ptrType = E->getType()->getAs<PointerType>()) {
4198     calleePtr = EmitScalarExpr(E);
4199     functionType = ptrType->getPointeeType();
4200   } else {
4201     functionType = E->getType();
4202     calleePtr = EmitLValue(E).getPointer();
4203   }
4204   assert(functionType->isFunctionType());
4205   CGCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(),
4206                           E->getReferencedDeclOfCallee());
4207   CGCallee callee(calleeInfo, calleePtr);
4208   return callee;
4209 }
4210 
4211 LValue CodeGenFunction::EmitBinaryOperatorLValue(const BinaryOperator *E) {
4212   // Comma expressions just emit their LHS then their RHS as an l-value.
4213   if (E->getOpcode() == BO_Comma) {
4214     EmitIgnoredExpr(E->getLHS());
4215     EnsureInsertPoint();
4216     return EmitLValue(E->getRHS());
4217   }
4218 
4219   if (E->getOpcode() == BO_PtrMemD ||
4220       E->getOpcode() == BO_PtrMemI)
4221     return EmitPointerToDataMemberBinaryExpr(E);
4222 
4223   assert(E->getOpcode() == BO_Assign && "unexpected binary l-value");
4224 
4225   // Note that in all of these cases, __block variables need the RHS
4226   // evaluated first just in case the variable gets moved by the RHS.
4227 
4228   switch (getEvaluationKind(E->getType())) {
4229   case TEK_Scalar: {
4230     switch (E->getLHS()->getType().getObjCLifetime()) {
4231     case Qualifiers::OCL_Strong:
4232       return EmitARCStoreStrong(E, /*ignored*/ false).first;
4233 
4234     case Qualifiers::OCL_Autoreleasing:
4235       return EmitARCStoreAutoreleasing(E).first;
4236 
4237     // No reason to do any of these differently.
4238     case Qualifiers::OCL_None:
4239     case Qualifiers::OCL_ExplicitNone:
4240     case Qualifiers::OCL_Weak:
4241       break;
4242     }
4243 
4244     RValue RV = EmitAnyExpr(E->getRHS());
4245     LValue LV = EmitCheckedLValue(E->getLHS(), TCK_Store);
4246     if (RV.isScalar())
4247       EmitNullabilityCheck(LV, RV.getScalarVal(), E->getExprLoc());
4248     EmitStoreThroughLValue(RV, LV);
4249     return LV;
4250   }
4251 
4252   case TEK_Complex:
4253     return EmitComplexAssignmentLValue(E);
4254 
4255   case TEK_Aggregate:
4256     return EmitAggExprToLValue(E);
4257   }
4258   llvm_unreachable("bad evaluation kind");
4259 }
4260 
4261 LValue CodeGenFunction::EmitCallExprLValue(const CallExpr *E) {
4262   RValue RV = EmitCallExpr(E);
4263 
4264   if (!RV.isScalar())
4265     return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4266                           LValueBaseInfo(AlignmentSource::Decl, false));
4267 
4268   assert(E->getCallReturnType(getContext())->isReferenceType() &&
4269          "Can't have a scalar return unless the return type is a "
4270          "reference type!");
4271 
4272   return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
4273 }
4274 
4275 LValue CodeGenFunction::EmitVAArgExprLValue(const VAArgExpr *E) {
4276   // FIXME: This shouldn't require another copy.
4277   return EmitAggExprToLValue(E);
4278 }
4279 
4280 LValue CodeGenFunction::EmitCXXConstructLValue(const CXXConstructExpr *E) {
4281   assert(E->getType()->getAsCXXRecordDecl()->hasTrivialDestructor()
4282          && "binding l-value to type which needs a temporary");
4283   AggValueSlot Slot = CreateAggTemp(E->getType());
4284   EmitCXXConstructExpr(E, Slot);
4285   return MakeAddrLValue(Slot.getAddress(), E->getType(),
4286                         LValueBaseInfo(AlignmentSource::Decl, false));
4287 }
4288 
4289 LValue
4290 CodeGenFunction::EmitCXXTypeidLValue(const CXXTypeidExpr *E) {
4291   return MakeNaturalAlignAddrLValue(EmitCXXTypeidExpr(E), E->getType());
4292 }
4293 
4294 Address CodeGenFunction::EmitCXXUuidofExpr(const CXXUuidofExpr *E) {
4295   return Builder.CreateElementBitCast(CGM.GetAddrOfUuidDescriptor(E),
4296                                       ConvertType(E->getType()));
4297 }
4298 
4299 LValue CodeGenFunction::EmitCXXUuidofLValue(const CXXUuidofExpr *E) {
4300   return MakeAddrLValue(EmitCXXUuidofExpr(E), E->getType(),
4301                         LValueBaseInfo(AlignmentSource::Decl, false));
4302 }
4303 
4304 LValue
4305 CodeGenFunction::EmitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *E) {
4306   AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4307   Slot.setExternallyDestructed();
4308   EmitAggExpr(E->getSubExpr(), Slot);
4309   EmitCXXTemporary(E->getTemporary(), E->getType(), Slot.getAddress());
4310   return MakeAddrLValue(Slot.getAddress(), E->getType(),
4311                         LValueBaseInfo(AlignmentSource::Decl, false));
4312 }
4313 
4314 LValue
4315 CodeGenFunction::EmitLambdaLValue(const LambdaExpr *E) {
4316   AggValueSlot Slot = CreateAggTemp(E->getType(), "temp.lvalue");
4317   EmitLambdaExpr(E, Slot);
4318   return MakeAddrLValue(Slot.getAddress(), E->getType(),
4319                         LValueBaseInfo(AlignmentSource::Decl, false));
4320 }
4321 
4322 LValue CodeGenFunction::EmitObjCMessageExprLValue(const ObjCMessageExpr *E) {
4323   RValue RV = EmitObjCMessageExpr(E);
4324 
4325   if (!RV.isScalar())
4326     return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4327                           LValueBaseInfo(AlignmentSource::Decl, false));
4328 
4329   assert(E->getMethodDecl()->getReturnType()->isReferenceType() &&
4330          "Can't have a scalar return unless the return type is a "
4331          "reference type!");
4332 
4333   return MakeNaturalAlignPointeeAddrLValue(RV.getScalarVal(), E->getType());
4334 }
4335 
4336 LValue CodeGenFunction::EmitObjCSelectorLValue(const ObjCSelectorExpr *E) {
4337   Address V =
4338     CGM.getObjCRuntime().GetAddrOfSelector(*this, E->getSelector());
4339   return MakeAddrLValue(V, E->getType(),
4340                         LValueBaseInfo(AlignmentSource::Decl, false));
4341 }
4342 
4343 llvm::Value *CodeGenFunction::EmitIvarOffset(const ObjCInterfaceDecl *Interface,
4344                                              const ObjCIvarDecl *Ivar) {
4345   return CGM.getObjCRuntime().EmitIvarOffset(*this, Interface, Ivar);
4346 }
4347 
4348 LValue CodeGenFunction::EmitLValueForIvar(QualType ObjectTy,
4349                                           llvm::Value *BaseValue,
4350                                           const ObjCIvarDecl *Ivar,
4351                                           unsigned CVRQualifiers) {
4352   return CGM.getObjCRuntime().EmitObjCValueForIvar(*this, ObjectTy, BaseValue,
4353                                                    Ivar, CVRQualifiers);
4354 }
4355 
4356 LValue CodeGenFunction::EmitObjCIvarRefLValue(const ObjCIvarRefExpr *E) {
4357   // FIXME: A lot of the code below could be shared with EmitMemberExpr.
4358   llvm::Value *BaseValue = nullptr;
4359   const Expr *BaseExpr = E->getBase();
4360   Qualifiers BaseQuals;
4361   QualType ObjectTy;
4362   if (E->isArrow()) {
4363     BaseValue = EmitScalarExpr(BaseExpr);
4364     ObjectTy = BaseExpr->getType()->getPointeeType();
4365     BaseQuals = ObjectTy.getQualifiers();
4366   } else {
4367     LValue BaseLV = EmitLValue(BaseExpr);
4368     BaseValue = BaseLV.getPointer();
4369     ObjectTy = BaseExpr->getType();
4370     BaseQuals = ObjectTy.getQualifiers();
4371   }
4372 
4373   LValue LV =
4374     EmitLValueForIvar(ObjectTy, BaseValue, E->getDecl(),
4375                       BaseQuals.getCVRQualifiers());
4376   setObjCGCLValueClass(getContext(), E, LV);
4377   return LV;
4378 }
4379 
4380 LValue CodeGenFunction::EmitStmtExprLValue(const StmtExpr *E) {
4381   // Can only get l-value for message expression returning aggregate type
4382   RValue RV = EmitAnyExprToTemp(E);
4383   return MakeAddrLValue(RV.getAggregateAddress(), E->getType(),
4384                         LValueBaseInfo(AlignmentSource::Decl, false));
4385 }
4386 
4387 RValue CodeGenFunction::EmitCall(QualType CalleeType, const CGCallee &OrigCallee,
4388                                  const CallExpr *E, ReturnValueSlot ReturnValue,
4389                                  llvm::Value *Chain) {
4390   // Get the actual function type. The callee type will always be a pointer to
4391   // function type or a block pointer type.
4392   assert(CalleeType->isFunctionPointerType() &&
4393          "Call must have function pointer type!");
4394 
4395   const Decl *TargetDecl = OrigCallee.getAbstractInfo().getCalleeDecl();
4396 
4397   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
4398     // We can only guarantee that a function is called from the correct
4399     // context/function based on the appropriate target attributes,
4400     // so only check in the case where we have both always_inline and target
4401     // since otherwise we could be making a conditional call after a check for
4402     // the proper cpu features (and it won't cause code generation issues due to
4403     // function based code generation).
4404     if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
4405         TargetDecl->hasAttr<TargetAttr>())
4406       checkTargetFeatures(E, FD);
4407 
4408   CalleeType = getContext().getCanonicalType(CalleeType);
4409 
4410   const auto *FnType =
4411       cast<FunctionType>(cast<PointerType>(CalleeType)->getPointeeType());
4412 
4413   CGCallee Callee = OrigCallee;
4414 
4415   if (getLangOpts().CPlusPlus && SanOpts.has(SanitizerKind::Function) &&
4416       (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4417     if (llvm::Constant *PrefixSig =
4418             CGM.getTargetCodeGenInfo().getUBSanFunctionSignature(CGM)) {
4419       SanitizerScope SanScope(this);
4420       llvm::Constant *FTRTTIConst =
4421           CGM.GetAddrOfRTTIDescriptor(QualType(FnType, 0), /*ForEH=*/true);
4422       llvm::Type *PrefixStructTyElems[] = {PrefixSig->getType(), Int32Ty};
4423       llvm::StructType *PrefixStructTy = llvm::StructType::get(
4424           CGM.getLLVMContext(), PrefixStructTyElems, /*isPacked=*/true);
4425 
4426       llvm::Value *CalleePtr = Callee.getFunctionPointer();
4427 
4428       llvm::Value *CalleePrefixStruct = Builder.CreateBitCast(
4429           CalleePtr, llvm::PointerType::getUnqual(PrefixStructTy));
4430       llvm::Value *CalleeSigPtr =
4431           Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 0);
4432       llvm::Value *CalleeSig =
4433           Builder.CreateAlignedLoad(CalleeSigPtr, getIntAlign());
4434       llvm::Value *CalleeSigMatch = Builder.CreateICmpEQ(CalleeSig, PrefixSig);
4435 
4436       llvm::BasicBlock *Cont = createBasicBlock("cont");
4437       llvm::BasicBlock *TypeCheck = createBasicBlock("typecheck");
4438       Builder.CreateCondBr(CalleeSigMatch, TypeCheck, Cont);
4439 
4440       EmitBlock(TypeCheck);
4441       llvm::Value *CalleeRTTIPtr =
4442           Builder.CreateConstGEP2_32(PrefixStructTy, CalleePrefixStruct, 0, 1);
4443       llvm::Value *CalleeRTTIEncoded =
4444           Builder.CreateAlignedLoad(CalleeRTTIPtr, getPointerAlign());
4445       llvm::Value *CalleeRTTI =
4446           DecodeAddrUsedInPrologue(CalleePtr, CalleeRTTIEncoded);
4447       llvm::Value *CalleeRTTIMatch =
4448           Builder.CreateICmpEQ(CalleeRTTI, FTRTTIConst);
4449       llvm::Constant *StaticData[] = {
4450         EmitCheckSourceLocation(E->getLocStart()),
4451         EmitCheckTypeDescriptor(CalleeType)
4452       };
4453       EmitCheck(std::make_pair(CalleeRTTIMatch, SanitizerKind::Function),
4454                 SanitizerHandler::FunctionTypeMismatch, StaticData, CalleePtr);
4455 
4456       Builder.CreateBr(Cont);
4457       EmitBlock(Cont);
4458     }
4459   }
4460 
4461   // If we are checking indirect calls and this call is indirect, check that the
4462   // function pointer is a member of the bit set for the function type.
4463   if (SanOpts.has(SanitizerKind::CFIICall) &&
4464       (!TargetDecl || !isa<FunctionDecl>(TargetDecl))) {
4465     SanitizerScope SanScope(this);
4466     EmitSanitizerStatReport(llvm::SanStat_CFI_ICall);
4467 
4468     llvm::Metadata *MD = CGM.CreateMetadataIdentifierForType(QualType(FnType, 0));
4469     llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD);
4470 
4471     llvm::Value *CalleePtr = Callee.getFunctionPointer();
4472     llvm::Value *CastedCallee = Builder.CreateBitCast(CalleePtr, Int8PtrTy);
4473     llvm::Value *TypeTest = Builder.CreateCall(
4474         CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedCallee, TypeId});
4475 
4476     auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD);
4477     llvm::Constant *StaticData[] = {
4478         llvm::ConstantInt::get(Int8Ty, CFITCK_ICall),
4479         EmitCheckSourceLocation(E->getLocStart()),
4480         EmitCheckTypeDescriptor(QualType(FnType, 0)),
4481     };
4482     if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) {
4483       EmitCfiSlowPathCheck(SanitizerKind::CFIICall, TypeTest, CrossDsoTypeId,
4484                            CastedCallee, StaticData);
4485     } else {
4486       EmitCheck(std::make_pair(TypeTest, SanitizerKind::CFIICall),
4487                 SanitizerHandler::CFICheckFail, StaticData,
4488                 {CastedCallee, llvm::UndefValue::get(IntPtrTy)});
4489     }
4490   }
4491 
4492   CallArgList Args;
4493   if (Chain)
4494     Args.add(RValue::get(Builder.CreateBitCast(Chain, CGM.VoidPtrTy)),
4495              CGM.getContext().VoidPtrTy);
4496 
4497   // C++17 requires that we evaluate arguments to a call using assignment syntax
4498   // right-to-left, and that we evaluate arguments to certain other operators
4499   // left-to-right. Note that we allow this to override the order dictated by
4500   // the calling convention on the MS ABI, which means that parameter
4501   // destruction order is not necessarily reverse construction order.
4502   // FIXME: Revisit this based on C++ committee response to unimplementability.
4503   EvaluationOrder Order = EvaluationOrder::Default;
4504   if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
4505     if (OCE->isAssignmentOp())
4506       Order = EvaluationOrder::ForceRightToLeft;
4507     else {
4508       switch (OCE->getOperator()) {
4509       case OO_LessLess:
4510       case OO_GreaterGreater:
4511       case OO_AmpAmp:
4512       case OO_PipePipe:
4513       case OO_Comma:
4514       case OO_ArrowStar:
4515         Order = EvaluationOrder::ForceLeftToRight;
4516         break;
4517       default:
4518         break;
4519       }
4520     }
4521   }
4522 
4523   EmitCallArgs(Args, dyn_cast<FunctionProtoType>(FnType), E->arguments(),
4524                E->getDirectCallee(), /*ParamsToSkip*/ 0, Order);
4525 
4526   const CGFunctionInfo &FnInfo = CGM.getTypes().arrangeFreeFunctionCall(
4527       Args, FnType, /*isChainCall=*/Chain);
4528 
4529   // C99 6.5.2.2p6:
4530   //   If the expression that denotes the called function has a type
4531   //   that does not include a prototype, [the default argument
4532   //   promotions are performed]. If the number of arguments does not
4533   //   equal the number of parameters, the behavior is undefined. If
4534   //   the function is defined with a type that includes a prototype,
4535   //   and either the prototype ends with an ellipsis (, ...) or the
4536   //   types of the arguments after promotion are not compatible with
4537   //   the types of the parameters, the behavior is undefined. If the
4538   //   function is defined with a type that does not include a
4539   //   prototype, and the types of the arguments after promotion are
4540   //   not compatible with those of the parameters after promotion,
4541   //   the behavior is undefined [except in some trivial cases].
4542   // That is, in the general case, we should assume that a call
4543   // through an unprototyped function type works like a *non-variadic*
4544   // call.  The way we make this work is to cast to the exact type
4545   // of the promoted arguments.
4546   //
4547   // Chain calls use this same code path to add the invisible chain parameter
4548   // to the function type.
4549   if (isa<FunctionNoProtoType>(FnType) || Chain) {
4550     llvm::Type *CalleeTy = getTypes().GetFunctionType(FnInfo);
4551     CalleeTy = CalleeTy->getPointerTo();
4552 
4553     llvm::Value *CalleePtr = Callee.getFunctionPointer();
4554     CalleePtr = Builder.CreateBitCast(CalleePtr, CalleeTy, "callee.knr.cast");
4555     Callee.setFunctionPointer(CalleePtr);
4556   }
4557 
4558   return EmitCall(FnInfo, Callee, ReturnValue, Args);
4559 }
4560 
4561 LValue CodeGenFunction::
4562 EmitPointerToDataMemberBinaryExpr(const BinaryOperator *E) {
4563   Address BaseAddr = Address::invalid();
4564   if (E->getOpcode() == BO_PtrMemI) {
4565     BaseAddr = EmitPointerWithAlignment(E->getLHS());
4566   } else {
4567     BaseAddr = EmitLValue(E->getLHS()).getAddress();
4568   }
4569 
4570   llvm::Value *OffsetV = EmitScalarExpr(E->getRHS());
4571 
4572   const MemberPointerType *MPT
4573     = E->getRHS()->getType()->getAs<MemberPointerType>();
4574 
4575   LValueBaseInfo BaseInfo;
4576   Address MemberAddr =
4577     EmitCXXMemberDataPointerAddress(E, BaseAddr, OffsetV, MPT, &BaseInfo);
4578 
4579   return MakeAddrLValue(MemberAddr, MPT->getPointeeType(), BaseInfo);
4580 }
4581 
4582 /// Given the address of a temporary variable, produce an r-value of
4583 /// its type.
4584 RValue CodeGenFunction::convertTempToRValue(Address addr,
4585                                             QualType type,
4586                                             SourceLocation loc) {
4587   LValue lvalue = MakeAddrLValue(addr, type,
4588                                  LValueBaseInfo(AlignmentSource::Decl, false));
4589   switch (getEvaluationKind(type)) {
4590   case TEK_Complex:
4591     return RValue::getComplex(EmitLoadOfComplex(lvalue, loc));
4592   case TEK_Aggregate:
4593     return lvalue.asAggregateRValue();
4594   case TEK_Scalar:
4595     return RValue::get(EmitLoadOfScalar(lvalue, loc));
4596   }
4597   llvm_unreachable("bad evaluation kind");
4598 }
4599 
4600 void CodeGenFunction::SetFPAccuracy(llvm::Value *Val, float Accuracy) {
4601   assert(Val->getType()->isFPOrFPVectorTy());
4602   if (Accuracy == 0.0 || !isa<llvm::Instruction>(Val))
4603     return;
4604 
4605   llvm::MDBuilder MDHelper(getLLVMContext());
4606   llvm::MDNode *Node = MDHelper.createFPMath(Accuracy);
4607 
4608   cast<llvm::Instruction>(Val)->setMetadata(llvm::LLVMContext::MD_fpmath, Node);
4609 }
4610 
4611 namespace {
4612   struct LValueOrRValue {
4613     LValue LV;
4614     RValue RV;
4615   };
4616 }
4617 
4618 static LValueOrRValue emitPseudoObjectExpr(CodeGenFunction &CGF,
4619                                            const PseudoObjectExpr *E,
4620                                            bool forLValue,
4621                                            AggValueSlot slot) {
4622   SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
4623 
4624   // Find the result expression, if any.
4625   const Expr *resultExpr = E->getResultExpr();
4626   LValueOrRValue result;
4627 
4628   for (PseudoObjectExpr::const_semantics_iterator
4629          i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
4630     const Expr *semantic = *i;
4631 
4632     // If this semantic expression is an opaque value, bind it
4633     // to the result of its source expression.
4634     if (const auto *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
4635 
4636       // If this is the result expression, we may need to evaluate
4637       // directly into the slot.
4638       typedef CodeGenFunction::OpaqueValueMappingData OVMA;
4639       OVMA opaqueData;
4640       if (ov == resultExpr && ov->isRValue() && !forLValue &&
4641           CodeGenFunction::hasAggregateEvaluationKind(ov->getType())) {
4642         CGF.EmitAggExpr(ov->getSourceExpr(), slot);
4643         LValueBaseInfo BaseInfo(AlignmentSource::Decl, false);
4644         LValue LV = CGF.MakeAddrLValue(slot.getAddress(), ov->getType(),
4645                                        BaseInfo);
4646         opaqueData = OVMA::bind(CGF, ov, LV);
4647         result.RV = slot.asRValue();
4648 
4649       // Otherwise, emit as normal.
4650       } else {
4651         opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
4652 
4653         // If this is the result, also evaluate the result now.
4654         if (ov == resultExpr) {
4655           if (forLValue)
4656             result.LV = CGF.EmitLValue(ov);
4657           else
4658             result.RV = CGF.EmitAnyExpr(ov, slot);
4659         }
4660       }
4661 
4662       opaques.push_back(opaqueData);
4663 
4664     // Otherwise, if the expression is the result, evaluate it
4665     // and remember the result.
4666     } else if (semantic == resultExpr) {
4667       if (forLValue)
4668         result.LV = CGF.EmitLValue(semantic);
4669       else
4670         result.RV = CGF.EmitAnyExpr(semantic, slot);
4671 
4672     // Otherwise, evaluate the expression in an ignored context.
4673     } else {
4674       CGF.EmitIgnoredExpr(semantic);
4675     }
4676   }
4677 
4678   // Unbind all the opaques now.
4679   for (unsigned i = 0, e = opaques.size(); i != e; ++i)
4680     opaques[i].unbind(CGF);
4681 
4682   return result;
4683 }
4684 
4685 RValue CodeGenFunction::EmitPseudoObjectRValue(const PseudoObjectExpr *E,
4686                                                AggValueSlot slot) {
4687   return emitPseudoObjectExpr(*this, E, false, slot).RV;
4688 }
4689 
4690 LValue CodeGenFunction::EmitPseudoObjectLValue(const PseudoObjectExpr *E) {
4691   return emitPseudoObjectExpr(*this, E, true, AggValueSlot::ignored()).LV;
4692 }
4693