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