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