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