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