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