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