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