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