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