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