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