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