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