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