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