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