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